Explore all Business open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Business

yfinance

0.1.70

invoiceninja

v5.3.82

akaunting

2.1.33

stock

发布 v1.0 版本

ticker

v4.5.0

Popular Libraries in Business

tushare

by waditu doticonpythondoticon

star image 11075 doticonBSD-3-Clause

TuShare is a utility for crawling historical data of China stocks

yfinance

by ranaroussi doticonpythondoticon

star image 6548 doticonApache-2.0

Download market data from Yahoo! Finance's API

invoiceninja

by invoiceninja doticonphpdoticon

star image 6444 doticonNOASSERTION

Invoices, Expenses and Tasks built with Laravel and Flutter

ta-lib

by mrjbq7 doticonpythondoticon

star image 5392 doticonNOASSERTION

Python wrapper for TA-Lib (http://ta-lib.org/).

Manta

by hql287 doticonjavascriptdoticon

star image 5187 doticonLGPL-3.0

🎉 Flexible invoicing desktop app with beautiful & customizable templates.

akaunting

by akaunting doticonphpdoticon

star image 4821 doticonGPL-3.0

Free and Online Accounting Software

stock

by pythonstock doticonpythondoticon

star image 4553 doticonApache-2.0

stock,股票系统。使用python进行开发。

ticker

by achannarasappa doticongodoticon

star image 4150 doticonGPL-3.0

Terminal stock ticker with live updates and position tracking

crater

by bytefury doticonphpdoticon

star image 4101 doticonNOASSERTION

Free & Open Source Invoice App for Freelancers & Small Businesses

Trending New libraries in Business

ticker

by achannarasappa doticongodoticon

star image 4150 doticonGPL-3.0

Terminal stock ticker with live updates and position tracking

Reddit-Stock-Trends

by iam-abbas doticonpythondoticon

star image 1464 doticonMIT

Fetch currently trending stocks on Reddit

FinanceDatabase

by JerBouma doticonpythondoticon

star image 662 doticonMIT

This is a database of 180.000+ symbols containing Equities, ETFs, Funds, Indices, Futures, Options, Currencies, Cryptocurrencies and Money Markets.

x-stock

by axiaoxin-com doticongodoticon

star image 520 doticonApache-2.0

Golang实现财报分析、股票检测、基本面选股、基金检测、基金筛选、4433法则、基金持仓相似度、股票选基

jacktrip-webrtc

by jacktrip-webrtc doticonjavascriptdoticon

star image 371 doticonGPL-3.0

JackTrip meets WebRTC

stock_market

by wbbhcb doticonjupyter notebookdoticon

star image 350 doticon

mslive_public

by marketsentiment doticonpythondoticon

star image 269 doticonGPL-3.0

Track live sentiment for stocks from Reddit and Twitter and identify growing stocks

reddit-hyped-stocks

by lukstei doticonjavascriptdoticon

star image 260 doticon

A web application to explore currently hyped stocks on Reddit

Finance

by shashankvemuri doticonpythondoticon

star image 256 doticonMIT

Here you can find all the quantitative finance algorithms that I've worked on and refined over the past year!

Top Authors in Business

1

intrinio

7 Libraries

star icon206

2

hackingthemarkets

5 Libraries

star icon140

3

contributte

4 Libraries

star icon83

4

rubenafo

4 Libraries

star icon188

5

LastAncientOne

3 Libraries

star icon178

6

akretion

3 Libraries

star icon93

7

fbriden

3 Libraries

star icon20

8

PacktPublishing

3 Libraries

star icon348

9

spidezad

3 Libraries

star icon130

10

xendit

3 Libraries

star icon86

1

7 Libraries

star icon206

2

5 Libraries

star icon140

3

4 Libraries

star icon83

4

4 Libraries

star icon188

5

3 Libraries

star icon178

6

3 Libraries

star icon93

7

3 Libraries

star icon20

8

3 Libraries

star icon348

9

3 Libraries

star icon130

10

3 Libraries

star icon86

Trending Kits in Business

No Trending Kits are available at this moment for Business

Trending Discussions on Business

Is there a C++14 alternative to explicit(expr) introduced in C++20?

Material-UI Data Grid onSortModelChange Causing an Infinite Loop

Java map function throws non-static method compiler error

How to access all draft campaigns with the Facebook marketing API?

How to implement the Hindenburg omen indicator?

jQuery .append doesn't work with $(document).ready

Project loom, what happens when virtual thread makes a blocking system call?

Koltin return null if value is null else

Pandas group cumsum with condition

Reactjs separation of UI and business logic

QUESTION

Is there a C++14 alternative to explicit(expr) introduced in C++20?

Asked 2022-Mar-04 at 07:43

TL;DR: I am looking for a C++14 equivalent of the following C++20 MWE:

1template<int sz>
2struct bits {
3  int v; // note explicit(expr) below
4  explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8  bool c = bits<1>{1}; // Should work
9  bool d = bits<3>{1}; // Should fail
10}
11

Context:

We have a C++ class bits<sz> representing bitvectors of length sz. Conversion to bool used to be implicit for all sz, but this proved to be error-prone, so we changed operator bool() to be explicit.

However, 1-bit bitvectors are (in our context) almost-completely equivalent to Booleans, so it would be desirable for operator bool() to be implicit when sz == 1.

This can be achieved with explicit(sz > 1) in C++20, but we are targeting C++14.

I tried to overload the operator for sz == 1, but it seems that the explicit qualifier applies to it as well: the following does not work.

1template&lt;int sz&gt;
2struct bits {
3  int v; // note explicit(expr) below
4  explicit(sz &gt; 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8  bool c = bits&lt;1&gt;{1}; // Should work
9  bool d = bits&lt;3&gt;{1}; // Should fail
10}
11template&lt;int sz&gt;
12struct bits {
13  int v;
14  explicit operator bool() const { return bool(v); }
15};
16
17template&lt;&gt; bits&lt;1&gt;::operator bool() const {
18  return bool(v);
19}
20
21int main() {
22  bool c = bits&lt;1&gt;{1}; // Fails: &quot;No viable conversion&quot;
23}
24

Hence the question: How can I specify in C++14 that operator bool() should be explicit only for sz > 1?

I'm including some background below for curious readers.

Background:

This problem came up in the context of an embedded domain-specific language in C++. One of the business requirements is that operator== returns a bit<1>, not a bool. This is working smoothly with GNU's libstdc++, but we're running into trouble with that requirement on macOS because libstdc++ there implements operator== on std::array using the version of std::equal that takes a predicate, and implements that predicate using a struct whose operator() returns bool with body a == b (which in our case returns a bits<1>, causing a conversion error).

To make it concrete for curious readers, the following program compiles fine on GNU, but not on macOS, because of the way operator== on std::array is implemented:

1template&lt;int sz&gt;
2struct bits {
3  int v; // note explicit(expr) below
4  explicit(sz &gt; 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8  bool c = bits&lt;1&gt;{1}; // Should work
9  bool d = bits&lt;3&gt;{1}; // Should fail
10}
11template&lt;int sz&gt;
12struct bits {
13  int v;
14  explicit operator bool() const { return bool(v); }
15};
16
17template&lt;&gt; bits&lt;1&gt;::operator bool() const {
18  return bool(v);
19}
20
21int main() {
22  bool c = bits&lt;1&gt;{1}; // Fails: &quot;No viable conversion&quot;
23}
24#include &lt;array&gt;
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32  std::array&lt;T, 1&gt; arr = { T() };
33  return arr == arr;
34}
35

That's because deep down in the implementation of == on arrays GNU libstdc++ has a test if (!(*it1 == *it2)), which invokes the explicit operator bool() on S without trouble, where as on macOS the library uses if (!__pred(*it1, *it2)) with __pred roughly equivalent to bool __pred(S a, S b) { return a == b; }, which doesn't typecheck.

ANSWER

Answered 2022-Mar-04 at 07:43

Yes. You can SFINAE the conversion operator:

1template&lt;int sz&gt;
2struct bits {
3  int v; // note explicit(expr) below
4  explicit(sz &gt; 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8  bool c = bits&lt;1&gt;{1}; // Should work
9  bool d = bits&lt;3&gt;{1}; // Should fail
10}
11template&lt;int sz&gt;
12struct bits {
13  int v;
14  explicit operator bool() const { return bool(v); }
15};
16
17template&lt;&gt; bits&lt;1&gt;::operator bool() const {
18  return bool(v);
19}
20
21int main() {
22  bool c = bits&lt;1&gt;{1}; // Fails: &quot;No viable conversion&quot;
23}
24#include &lt;array&gt;
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32  std::array&lt;T, 1&gt; arr = { T() };
33  return arr == arr;
34}
35#include &lt;type_traits&gt;
36
37template&lt;int sz&gt;
38struct bits {
39  int v;
40  explicit operator bool() const { return bool(v); }
41
42  template &lt;int S = sz&gt;
43  operator std::enable_if_t&lt;S == 1, bool&gt; () const { return bool(v);}
44};
45

Check it on godbolt

1template&lt;int sz&gt;
2struct bits {
3  int v; // note explicit(expr) below
4  explicit(sz &gt; 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8  bool c = bits&lt;1&gt;{1}; // Should work
9  bool d = bits&lt;3&gt;{1}; // Should fail
10}
11template&lt;int sz&gt;
12struct bits {
13  int v;
14  explicit operator bool() const { return bool(v); }
15};
16
17template&lt;&gt; bits&lt;1&gt;::operator bool() const {
18  return bool(v);
19}
20
21int main() {
22  bool c = bits&lt;1&gt;{1}; // Fails: &quot;No viable conversion&quot;
23}
24#include &lt;array&gt;
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32  std::array&lt;T, 1&gt; arr = { T() };
33  return arr == arr;
34}
35#include &lt;type_traits&gt;
36
37template&lt;int sz&gt;
38struct bits {
39  int v;
40  explicit operator bool() const { return bool(v); }
41
42  template &lt;int S = sz&gt;
43  operator std::enable_if_t&lt;S == 1, bool&gt; () const { return bool(v);}
44};
45int main()
46{
47  bool c1 = bits&lt;1&gt;{1};                    // Ok
48  bool c2 = bits&lt;3&gt;{1};                    // error cannot convert
49  bool c3 = static_cast&lt;bool&gt;(bits&lt;3&gt;{1}); // OK
50}
51

Source https://stackoverflow.com/questions/71347981

QUESTION

Material-UI Data Grid onSortModelChange Causing an Infinite Loop

Asked 2022-Feb-14 at 23:31

I'm following the Sort Model documentation (https://material-ui.com/components/data-grid/sorting/#basic-sorting) and am using sortModel and onSortModelChange exactly as used in the documentation. However, I'm getting an infinite loop immediately after loading the page (I can tell this based on the console.log).

What I've tried:

I always end up with the same issue. I'm using Blitz.js.

My code:

useState:

1const [sortModel, setSortModel] = useState&lt;GridSortModel&gt;([
2    {
3      field: &quot;updatedAt&quot;,
4      sort: &quot;desc&quot; as GridSortDirection,
5    },
6  ])
7

rows definition:

1const [sortModel, setSortModel] = useState&lt;GridSortModel&gt;([
2    {
3      field: &quot;updatedAt&quot;,
4      sort: &quot;desc&quot; as GridSortDirection,
5    },
6  ])
7  const rows = currentUsersApplications.map((application) =&gt; {
8    return {
9      id: application.id,
10      business_name: application.business_name,
11      business_phone: application.business_phone,
12      applicant_name: application.applicant_name,
13      applicant_email: application.applicant_email,
14      owner_cell_phone: application.owner_cell_phone,
15      status: application.status,
16      agent_name: application.agent_name,
17      equipment_description: application.equipment_description,
18      createdAt: formattedDate(application.createdAt),
19      updatedAt: formattedDate(application.updatedAt),
20      archived: application.archived,
21    }
22  })
23

columns definition:

1const [sortModel, setSortModel] = useState&lt;GridSortModel&gt;([
2    {
3      field: &quot;updatedAt&quot;,
4      sort: &quot;desc&quot; as GridSortDirection,
5    },
6  ])
7  const rows = currentUsersApplications.map((application) =&gt; {
8    return {
9      id: application.id,
10      business_name: application.business_name,
11      business_phone: application.business_phone,
12      applicant_name: application.applicant_name,
13      applicant_email: application.applicant_email,
14      owner_cell_phone: application.owner_cell_phone,
15      status: application.status,
16      agent_name: application.agent_name,
17      equipment_description: application.equipment_description,
18      createdAt: formattedDate(application.createdAt),
19      updatedAt: formattedDate(application.updatedAt),
20      archived: application.archived,
21    }
22  })
23
24  const columns = [
25    { field: &quot;id&quot;, headerName: &quot;ID&quot;, width: 70, hide: true },
26    {
27      field: &quot;business_name&quot;,
28      headerName: &quot;Business Name&quot;,
29      width: 200,
30      // Need renderCell() here because this is a link and not just a string
31      renderCell: (params: GridCellParams) =&gt; {
32        console.log(params)
33        return &lt;BusinessNameLink application={params.row} /&gt;
34      },
35    },
36    { field: &quot;business_phone&quot;, headerName: &quot;Business Phone&quot;, width: 180 },
37    { field: &quot;applicant_name&quot;, headerName: &quot;Applicant Name&quot;, width: 180 },
38    { field: &quot;applicant_email&quot;, headerName: &quot;Applicant Email&quot;, width: 180 },
39    { field: &quot;owner_cell_phone&quot;, headerName: &quot;Ownership/Guarantor Phone&quot;, width: 260 },
40    { field: &quot;status&quot;, headerName: &quot;Status&quot;, width: 130 },
41    { field: &quot;agent_name&quot;, headerName: &quot;Agent&quot;, width: 130 },
42    { field: &quot;equipment_description&quot;, headerName: &quot;Equipment&quot;, width: 200 },
43    { field: &quot;createdAt&quot;, headerName: &quot;Submitted At&quot;, width: 250 },
44    { field: &quot;updatedAt&quot;, headerName: &quot;Last Edited&quot;, width: 250 },
45    { field: &quot;archived&quot;, headerName: &quot;Archived&quot;, width: 180, type: &quot;boolean&quot; },
46  ]
47

Rendering DataGrid and using sortModel/onSortChange

1const [sortModel, setSortModel] = useState&lt;GridSortModel&gt;([
2    {
3      field: &quot;updatedAt&quot;,
4      sort: &quot;desc&quot; as GridSortDirection,
5    },
6  ])
7  const rows = currentUsersApplications.map((application) =&gt; {
8    return {
9      id: application.id,
10      business_name: application.business_name,
11      business_phone: application.business_phone,
12      applicant_name: application.applicant_name,
13      applicant_email: application.applicant_email,
14      owner_cell_phone: application.owner_cell_phone,
15      status: application.status,
16      agent_name: application.agent_name,
17      equipment_description: application.equipment_description,
18      createdAt: formattedDate(application.createdAt),
19      updatedAt: formattedDate(application.updatedAt),
20      archived: application.archived,
21    }
22  })
23
24  const columns = [
25    { field: &quot;id&quot;, headerName: &quot;ID&quot;, width: 70, hide: true },
26    {
27      field: &quot;business_name&quot;,
28      headerName: &quot;Business Name&quot;,
29      width: 200,
30      // Need renderCell() here because this is a link and not just a string
31      renderCell: (params: GridCellParams) =&gt; {
32        console.log(params)
33        return &lt;BusinessNameLink application={params.row} /&gt;
34      },
35    },
36    { field: &quot;business_phone&quot;, headerName: &quot;Business Phone&quot;, width: 180 },
37    { field: &quot;applicant_name&quot;, headerName: &quot;Applicant Name&quot;, width: 180 },
38    { field: &quot;applicant_email&quot;, headerName: &quot;Applicant Email&quot;, width: 180 },
39    { field: &quot;owner_cell_phone&quot;, headerName: &quot;Ownership/Guarantor Phone&quot;, width: 260 },
40    { field: &quot;status&quot;, headerName: &quot;Status&quot;, width: 130 },
41    { field: &quot;agent_name&quot;, headerName: &quot;Agent&quot;, width: 130 },
42    { field: &quot;equipment_description&quot;, headerName: &quot;Equipment&quot;, width: 200 },
43    { field: &quot;createdAt&quot;, headerName: &quot;Submitted At&quot;, width: 250 },
44    { field: &quot;updatedAt&quot;, headerName: &quot;Last Edited&quot;, width: 250 },
45    { field: &quot;archived&quot;, headerName: &quot;Archived&quot;, width: 180, type: &quot;boolean&quot; },
46  ]
47      &lt;div style={{ height: 580, width: &quot;100%&quot; }} className={classes.gridRowColor}&gt;
48        &lt;DataGrid
49          getRowClassName={(params) =&gt; `MuiDataGrid-row--${params.getValue(params.id, &quot;status&quot;)}`}
50          rows={rows}
51          columns={columns}
52          pageSize={10}
53          components={{
54            Toolbar: GridToolbar,
55          }}
56          filterModel={{
57            items: [{ columnField: &quot;archived&quot;, operatorValue: &quot;is&quot;, value: showArchived }],
58          }}
59          sortModel={sortModel}
60          onSortModelChange={(model) =&gt; {
61            console.log(model)
62            //Infinitely logs model immediately
63            setSortModel(model)
64          }}
65        /&gt;
66      &lt;/div&gt;
67

Thanks in advance!

ANSWER

Answered 2021-Aug-31 at 19:57

I fixed this by wrapping rows and columns in useRefs and used their .current property for both of them. Fixed it immediately.

Source https://stackoverflow.com/questions/69004286

QUESTION

Java map function throws non-static method compiler error

Asked 2022-Jan-27 at 04:17

I have an odd problem, where I am struggling to understand the nature of "static context" in Java, despite the numerous SO questions regarding the topic.

TL;DR:

I have a design flaw, where ...

This works:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3

But this does not:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4

Issue The error shown in the second version is "Non-static method cannot be referenced from a static context".

The long version:

Object Model: The model consists of Business Type specific orders (eg. Stock exchange, payments), which inherit from a an order entity via an "InheritanceType.JOINED" inheritance strategy. The parent order can be parameterized with the business type specific DTO object of that order, so for example DtoStockExchangeOrder. This is to enable, that JPA objects can be mapped to their DTO equivalent within the Entity, rather than in a service (which I did previously. It worked, but its "less clean").

JPA Order:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13

JPA Order - Business Type specific example:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13@Entity
14@Table(name = &quot;ORDER_STEX&quot;)
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order&lt;DtoOrderStex&gt; implements Serializable {
17

Likewise, DTO orders follow the same pattern, where they can be parameterized with the business type specific JPA entity, to enable the relevant mapping:

DTO Order:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13@Entity
14@Table(name = &quot;ORDER_STEX&quot;)
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order&lt;DtoOrderStex&gt; implements Serializable {
17public class DtoOrder&lt;OrderType extends Order&gt; extends DtoEntity {
18

DTO Order - Business Type Specific Example

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13@Entity
14@Table(name = &quot;ORDER_STEX&quot;)
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order&lt;DtoOrderStex&gt; implements Serializable {
17public class DtoOrder&lt;OrderType extends Order&gt; extends DtoEntity {
18public class DtoOrderStex extends DtoOrder&lt;OrderStex&gt; {
19

The DTOEntity class it inherits from is just a "wrapper" class, consisting of an ID and a name.

Now the tricky part: The DTOOrder class has a constructor which populates the fields that are common to all business types, like the list of process status transitions, an order goes through in its life cycle (placed, cancelled, executed, etc..). Staying with the example of the process status transitions, these are also modelled as JPA entities in the database, with their corresponding DTO counterparts (likewise parameterized, that part works fine).

Here the constructor:

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13@Entity
14@Table(name = &quot;ORDER_STEX&quot;)
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order&lt;DtoOrderStex&gt; implements Serializable {
17public class DtoOrder&lt;OrderType extends Order&gt; extends DtoEntity {
18public class DtoOrderStex extends DtoOrder&lt;OrderStex&gt; {
19public DtoOrder(OrderType orderType) {
20    super(orderType);
21    // this is the part from above, which works (but it shows a warning: Unchecked assignment: 'java.util.List' to 'java.util.List&lt;com.tradingvessel.core.persistence.model.OrderExtnTrans&gt;' )
22    List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
23    this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
24    // this is how I would have expected it to work, but it does not, with the error shown above: &quot;Non-static method cannot be referenced from a static context&quot;
25    this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
26}
27

If I comment out the non-working version, the application behaves as expected and throws no error, so "logically", this works. But JAVA does not allow it as developed in the second version.

If instead of OrderType I use "Order", it works as well, but obviously throws errors elsewhere, because the signature of the constructor changed. I assume another approach would be to parameterise the method based on the the caller of the constructor or to parameterise the parent class DtoOrder to know the type of the child class, but there should be a better way?

What am I doing wrong, and why does the upper version work as expected?

ANSWER

Answered 2022-Jan-26 at 17:11

One way to solve the issue is by parameterizing the ParentDTO Class with its own children.

1List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = &quot;ORDER_BASE&quot;)
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order&lt;DtoOrderType extends DtoOrder&gt; implements Serializable {
8
9    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;order&quot;, orphanRemoval = true)
10    private List&lt;OrderExtnTrans&gt; orderExtnTransList = new ArrayList&lt;&gt;();
11
12}
13@Entity
14@Table(name = &quot;ORDER_STEX&quot;)
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order&lt;DtoOrderStex&gt; implements Serializable {
17public class DtoOrder&lt;OrderType extends Order&gt; extends DtoEntity {
18public class DtoOrderStex extends DtoOrder&lt;OrderStex&gt; {
19public DtoOrder(OrderType orderType) {
20    super(orderType);
21    // this is the part from above, which works (but it shows a warning: Unchecked assignment: 'java.util.List' to 'java.util.List&lt;com.tradingvessel.core.persistence.model.OrderExtnTrans&gt;' )
22    List&lt;OrderExtnTrans&gt; list = orderType.getOrderExtnTransList();
23    this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
24    // this is how I would have expected it to work, but it does not, with the error shown above: &quot;Non-static method cannot be referenced from a static context&quot;
25    this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
26}
27public class DtoOrderStex extends DtoOrder&lt;OrderStex, DtoOrderStex&gt; {
28
29
30    public DtoOrderStex(OrderStex orderStex) {
31        super(orderStex);
32    }
33
34    public DtoOrderStex() {
35    }
36}
37

This raises the question: Does this have any serious negative side effects, apart from the redundancy in the child classes? And why is that necessary in the first place, given that the class is already a child of its parent?

Source https://stackoverflow.com/questions/70860253

QUESTION

How to access all draft campaigns with the Facebook marketing API?

Asked 2022-Jan-17 at 14:53

I'm trying to list all of my draft campaigns using the Facebook marketing API. By default, it seems, only non-draft (published?) campaigns are listed when calling

1curl -i -X GET \
2 &quot;https://graph.facebook.com/v12.0/act_12345/campaigns?fields=id,name&amp;access_token=&lt;mytoken&gt;&quot;
3

When looking at the code of the facebook-python-business-sdk, there are multiple references to unpublished content type, which makes me think that there should be a way to list all unpublished campaigns. So my question is how can I list all campaigns, published and unpublished?

I know this question is a duplicate (see here, here, and here) but I'm asking it again since it has not been answered and I'd like to put out a bounty for a helpful response.

ANSWER

Answered 2021-Dec-01 at 15:44

I believe the only way to get draft campaigns is below:

  1. You should get all addrafts. On my account I have only 1 addraft that contains all draft campaigns, but maybe you can have more. URL for getting addrafts:

https://graph.facebook.com/v12.0/act_<ad_account_id>/addrafts?access_token=<access_token>&fields=name,ad_object_id,id

  1. Now you can get addraft_fragments. You can see all draft fragments of your ad_account (campaigns, adsets, ads), but you can easily find here what you want. URL for getting addraft_fragments:

https://graph.facebook.com/v12.0/<addraft_id>/addraft_fragments?access_token=<access_token>&fields=name,id,ad_object_id,ad_object_type,budget,ad_object_name,values

Source https://stackoverflow.com/questions/70058289

QUESTION

How to implement the Hindenburg omen indicator?

Asked 2021-Dec-21 at 02:21

As defined here the Hindenburg omen indicator is:

The daily number of new 52-week highs and 52-week lows in a stock market index are greater than a threshold amount (typically 2.2%).

To me it means, we roll daily and look back 52 weeks or 252 business/trading days, then count the number of highs (or lows) and finally compute the return of that or pct_change, which is the ratio of new highs (or lows) they want to monitor e.g., being above 2.2%

1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&amp;P500 
6df = yf.download('^GSPC')
7# compute the &quot;highs&quot; and &quot;lows&quot;
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9    apply(lambda x: np.where(x &gt; 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11    apply(lambda x: np.where(x &lt; 0, 1, 0)).sum()).pct_change()
12

Did we understand it the same way? is there a better way to do it?

ANSWER

Answered 2021-Dec-21 at 02:21

Interesting question! Could I suggest the following code - it runs much faster than the apply solution because it is vectorised, and also lays out the steps a bit more clearly so you can inspect the interim results.

I got a different result to your code - you can compare by also plotting your result on the timeseries at bottom.

1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&amp;P500 
6df = yf.download('^GSPC')
7# compute the &quot;highs&quot; and &quot;lows&quot;
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9    apply(lambda x: np.where(x &gt; 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11    apply(lambda x: np.where(x &lt; 0, 1, 0)).sum()).pct_change()
12import pandas as pd
13import numpy as np
14import yfinance as yf
15
16# download the S&amp;P500 
17df = yf.download('^GSPC')
18
19# Constants
20n_trading_day_window = 252
21
22# Simplify the input dataframe to only the relevant column
23df_hin_omen = df[['Close']]
24# Calculate rolling highs and lows
25df_hin_omen.insert(1, 'rolling_high', df_hin_omen['Close'].rolling(n_trading_day_window).max())
26df_hin_omen.insert(2, 'rolling_low', df_hin_omen['Close'].rolling(n_trading_day_window).min())
27# High and low are simply when the given row matches the 252 day high or low
28df_hin_omen.insert(3, 'is_high', df_hin_omen.Close == df_hin_omen.rolling_high)
29df_hin_omen.insert(4, 'is_low', df_hin_omen.Close == df_hin_omen.rolling_low)
30# Calculate rolling percentages
31df_hin_omen.insert(5, 'percent_highs', df_hin_omen.is_high.rolling(n_trading_day_window).sum() / n_trading_day_window)
32df_hin_omen.insert(6, 'percent_lows', df_hin_omen.is_low.rolling(n_trading_day_window).sum() / n_trading_day_window)
33

Once you have run this, you can inspect the results as follows:

1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&amp;P500 
6df = yf.download('^GSPC')
7# compute the &quot;highs&quot; and &quot;lows&quot;
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9    apply(lambda x: np.where(x &gt; 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11    apply(lambda x: np.where(x &lt; 0, 1, 0)).sum()).pct_change()
12import pandas as pd
13import numpy as np
14import yfinance as yf
15
16# download the S&amp;P500 
17df = yf.download('^GSPC')
18
19# Constants
20n_trading_day_window = 252
21
22# Simplify the input dataframe to only the relevant column
23df_hin_omen = df[['Close']]
24# Calculate rolling highs and lows
25df_hin_omen.insert(1, 'rolling_high', df_hin_omen['Close'].rolling(n_trading_day_window).max())
26df_hin_omen.insert(2, 'rolling_low', df_hin_omen['Close'].rolling(n_trading_day_window).min())
27# High and low are simply when the given row matches the 252 day high or low
28df_hin_omen.insert(3, 'is_high', df_hin_omen.Close == df_hin_omen.rolling_high)
29df_hin_omen.insert(4, 'is_low', df_hin_omen.Close == df_hin_omen.rolling_low)
30# Calculate rolling percentages
31df_hin_omen.insert(5, 'percent_highs', df_hin_omen.is_high.rolling(n_trading_day_window).sum() / n_trading_day_window)
32df_hin_omen.insert(6, 'percent_lows', df_hin_omen.is_low.rolling(n_trading_day_window).sum() / n_trading_day_window)
33import matplotlib, matplotlib.pyplot as plt
34fig, ax = plt.subplots(figsize=(16, 6))
35df_hin_omen.resample('w').mean().percent_highs.plot(ax=ax)
36df_hin_omen.resample('w').mean().percent_lows.plot(ax=ax)
37

From the Hindenburg Omen Definition, "The Hindenburg Omen looks for a statistical deviation from the premise that under normal conditions, some stocks are either making new 52-week highs or new 52-week lows. It would be abnormal if both were occurring at the same time."

So from a look at our graph, my interpretation is that the stock market is currently closing at a lot of 52 week highs, but is not showing many 52 week lows. Please also note the article cited states that "It was reported that it had correctly predicted a significant stock market decline only 25% of the time." so I'm not sure if we can read too much into this...

enter image description here

Edit

I've had a look at your code and I don't think that the use of the pct_change function is correct - that will calculate the change on the rolling differential, so a movement from eg 0.10% to 0.11% would actually equate to a 10% change. Instead you want the rolling sum over the past year and divide that by the number of days in the year, per my code above.

Source https://stackoverflow.com/questions/70251565

QUESTION

jQuery .append doesn't work with $(document).ready

Asked 2021-Dec-19 at 18:08

This is a followup to toggleClass of parent div not changing with onClick

In my HTML layout, I've found that I need to generate the div #filters after the records, not before, because I need to use PHP to build the buttons for each state. This gave me the idea to use jQuery .append to move the #filters to the #move-filters-here above the records. But after I filter on a state, the filters appear below the records and .append doesn't work to move the #filters to #move-filters-here above the records.

Is .append not working with (document).ready?

Is there a different way to get .append to move the #filters?

Does .append need to "fire" again after the Onclick function?

Fiddle: https://jsfiddle.net/j3semt6h/10/

1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7  let _this = $(this);
8
9  if (!_this.hasClass('active')) {
10
11    $('.state-button.active, .record.active').removeClass('active');
12    $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14  }
15
16});
17
18});
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7  let _this = $(this);
8
9  if (!_this.hasClass('active')) {
10
11    $('.state-button.active, .record.active').removeClass('active');
12    $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14  }
15
16});
17
18});  .record {
19    display: none;
20}
21
22.state-button {
23    border: 2px solid #c2c2c2;
24    padding: 5px;
25    border-radius: 5px;
26    margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30    border-color: red;
31}
32
33.record.active {
34    display: block;
35}
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7  let _this = $(this);
8
9  if (!_this.hasClass('active')) {
10
11    $('.state-button.active, .record.active').removeClass('active');
12    $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14  }
15
16});
17
18});  .record {
19    display: none;
20}
21
22.state-button {
23    border: 2px solid #c2c2c2;
24    padding: 5px;
25    border-radius: 5px;
26    margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30    border-color: red;
31}
32
33.record.active {
34    display: block;
35} &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
36
37&lt;div id="move-filters-here"&gt;&lt;/div&gt;
38
39&lt;div class="record" data-state="AK"&gt;
40    &lt;h1 class="name"&gt;Customer 1&lt;/h1&gt;
41    &lt;ul&gt;
42        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
43        &lt;li class="course"&gt;Course: &lt;/li&gt;
44        &lt;li class="business"&gt;Business: &lt;/li&gt;
45        &lt;li class="address"&gt;Location: 345 Cow Town, Anchorage, &lt;span class="state"&gt;AK&lt;/span&gt;&lt;/li&gt;
46    &lt;/ul&gt;
47&lt;/div&gt;
48&lt;div class="record" data-state="AR"&gt;
49    &lt;h1 class="name"&gt;Customer 2&lt;/h1&gt;
50    &lt;ul&gt;
51        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
52        &lt;li class="course"&gt;Course: &lt;/li&gt;
53        &lt;li class="business"&gt;Business: &lt;/li&gt;
54        &lt;li class="address"&gt;Location: Mobile, &lt;span class="state"&gt;AR&lt;/span&gt;&lt;/li&gt;
55    &lt;/ul&gt;
56&lt;/div&gt;
57&lt;div class="record" data-state="CA"&gt;
58    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
59    &lt;ul&gt;
60        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
61        &lt;li class="course"&gt;Course: &lt;/li&gt;
62        &lt;li class="business"&gt;Business: &lt;/li&gt;
63        &lt;li class="address"&gt;Location: Los Angeles &lt;span class="state"&gt;CA&lt;/span&gt;&lt;/li&gt;
64    &lt;/ul&gt;
65&lt;/div&gt;
66
67&lt;div class="record" data-state="AZ"&gt;
68    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
69    &lt;ul&gt;
70        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
71        &lt;li class="course"&gt;Course: &lt;/li&gt;
72        &lt;li class="business"&gt;Business: &lt;/li&gt;
73        &lt;li class="address"&gt;Location: Flagstaff &lt;span class="state"&gt;AZ&lt;/span&gt;&lt;/li&gt;
74    &lt;/ul&gt;
75&lt;/div&gt;
76
77&lt;div class="record" data-state="UT"&gt;
78    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
79    &lt;ul&gt;
80        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
81        &lt;li class="course"&gt;Course: &lt;/li&gt;
82        &lt;li class="business"&gt;Business: &lt;/li&gt;
83        &lt;li class="address"&gt;Location: SLC &lt;span class="state"&gt;UT&lt;/span&gt;&lt;/li&gt;
84    &lt;/ul&gt;
85&lt;/div&gt;
86
87
88&lt;div id="filters"&gt;
89&lt;button class="state-button state-button-ak" data-state="AK"&gt;Alaska&lt;/button&gt;
90&lt;button class="state-button state-button-ar" data-state="AR"&gt;Arkansas&lt;/button&gt;
91&lt;button class="state-button state-button-ca" data-state="CA"&gt;California&lt;/button&gt;
92&lt;button class="state-button state-button-ca" data-state="AZ"&gt;Arizona&lt;/button&gt;
93&lt;button class="state-button state-button-ut" data-state="UT"&gt;Utah&lt;/button&gt;
94&lt;/div&gt;

ANSWER

Answered 2021-Dec-19 at 18:07

if you want append #filter to #move-filters-here you can do it like this:

1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7  let _this = $(this);
8
9  if (!_this.hasClass('active')) {
10
11    $('.state-button.active, .record.active').removeClass('active');
12    $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14  }
15
16});
17
18});  .record {
19    display: none;
20}
21
22.state-button {
23    border: 2px solid #c2c2c2;
24    padding: 5px;
25    border-radius: 5px;
26    margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30    border-color: red;
31}
32
33.record.active {
34    display: block;
35} &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
36
37&lt;div id="move-filters-here"&gt;&lt;/div&gt;
38
39&lt;div class="record" data-state="AK"&gt;
40    &lt;h1 class="name"&gt;Customer 1&lt;/h1&gt;
41    &lt;ul&gt;
42        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
43        &lt;li class="course"&gt;Course: &lt;/li&gt;
44        &lt;li class="business"&gt;Business: &lt;/li&gt;
45        &lt;li class="address"&gt;Location: 345 Cow Town, Anchorage, &lt;span class="state"&gt;AK&lt;/span&gt;&lt;/li&gt;
46    &lt;/ul&gt;
47&lt;/div&gt;
48&lt;div class="record" data-state="AR"&gt;
49    &lt;h1 class="name"&gt;Customer 2&lt;/h1&gt;
50    &lt;ul&gt;
51        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
52        &lt;li class="course"&gt;Course: &lt;/li&gt;
53        &lt;li class="business"&gt;Business: &lt;/li&gt;
54        &lt;li class="address"&gt;Location: Mobile, &lt;span class="state"&gt;AR&lt;/span&gt;&lt;/li&gt;
55    &lt;/ul&gt;
56&lt;/div&gt;
57&lt;div class="record" data-state="CA"&gt;
58    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
59    &lt;ul&gt;
60        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
61        &lt;li class="course"&gt;Course: &lt;/li&gt;
62        &lt;li class="business"&gt;Business: &lt;/li&gt;
63        &lt;li class="address"&gt;Location: Los Angeles &lt;span class="state"&gt;CA&lt;/span&gt;&lt;/li&gt;
64    &lt;/ul&gt;
65&lt;/div&gt;
66
67&lt;div class="record" data-state="AZ"&gt;
68    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
69    &lt;ul&gt;
70        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
71        &lt;li class="course"&gt;Course: &lt;/li&gt;
72        &lt;li class="business"&gt;Business: &lt;/li&gt;
73        &lt;li class="address"&gt;Location: Flagstaff &lt;span class="state"&gt;AZ&lt;/span&gt;&lt;/li&gt;
74    &lt;/ul&gt;
75&lt;/div&gt;
76
77&lt;div class="record" data-state="UT"&gt;
78    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
79    &lt;ul&gt;
80        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
81        &lt;li class="course"&gt;Course: &lt;/li&gt;
82        &lt;li class="business"&gt;Business: &lt;/li&gt;
83        &lt;li class="address"&gt;Location: SLC &lt;span class="state"&gt;UT&lt;/span&gt;&lt;/li&gt;
84    &lt;/ul&gt;
85&lt;/div&gt;
86
87
88&lt;div id="filters"&gt;
89&lt;button class="state-button state-button-ak" data-state="AK"&gt;Alaska&lt;/button&gt;
90&lt;button class="state-button state-button-ar" data-state="AR"&gt;Arkansas&lt;/button&gt;
91&lt;button class="state-button state-button-ca" data-state="CA"&gt;California&lt;/button&gt;
92&lt;button class="state-button state-button-ca" data-state="AZ"&gt;Arizona&lt;/button&gt;
93&lt;button class="state-button state-button-ut" data-state="UT"&gt;Utah&lt;/button&gt;
94&lt;/div&gt;$(&quot;#move-filters-here&quot;).append($(&quot;#filters&quot;));
95

and if you do it vice-versa, you can acheive your goal like this:

1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7  let _this = $(this);
8
9  if (!_this.hasClass('active')) {
10
11    $('.state-button.active, .record.active').removeClass('active');
12    $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14  }
15
16});
17
18});  .record {
19    display: none;
20}
21
22.state-button {
23    border: 2px solid #c2c2c2;
24    padding: 5px;
25    border-radius: 5px;
26    margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30    border-color: red;
31}
32
33.record.active {
34    display: block;
35} &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
36
37&lt;div id="move-filters-here"&gt;&lt;/div&gt;
38
39&lt;div class="record" data-state="AK"&gt;
40    &lt;h1 class="name"&gt;Customer 1&lt;/h1&gt;
41    &lt;ul&gt;
42        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
43        &lt;li class="course"&gt;Course: &lt;/li&gt;
44        &lt;li class="business"&gt;Business: &lt;/li&gt;
45        &lt;li class="address"&gt;Location: 345 Cow Town, Anchorage, &lt;span class="state"&gt;AK&lt;/span&gt;&lt;/li&gt;
46    &lt;/ul&gt;
47&lt;/div&gt;
48&lt;div class="record" data-state="AR"&gt;
49    &lt;h1 class="name"&gt;Customer 2&lt;/h1&gt;
50    &lt;ul&gt;
51        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
52        &lt;li class="course"&gt;Course: &lt;/li&gt;
53        &lt;li class="business"&gt;Business: &lt;/li&gt;
54        &lt;li class="address"&gt;Location: Mobile, &lt;span class="state"&gt;AR&lt;/span&gt;&lt;/li&gt;
55    &lt;/ul&gt;
56&lt;/div&gt;
57&lt;div class="record" data-state="CA"&gt;
58    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
59    &lt;ul&gt;
60        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
61        &lt;li class="course"&gt;Course: &lt;/li&gt;
62        &lt;li class="business"&gt;Business: &lt;/li&gt;
63        &lt;li class="address"&gt;Location: Los Angeles &lt;span class="state"&gt;CA&lt;/span&gt;&lt;/li&gt;
64    &lt;/ul&gt;
65&lt;/div&gt;
66
67&lt;div class="record" data-state="AZ"&gt;
68    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
69    &lt;ul&gt;
70        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
71        &lt;li class="course"&gt;Course: &lt;/li&gt;
72        &lt;li class="business"&gt;Business: &lt;/li&gt;
73        &lt;li class="address"&gt;Location: Flagstaff &lt;span class="state"&gt;AZ&lt;/span&gt;&lt;/li&gt;
74    &lt;/ul&gt;
75&lt;/div&gt;
76
77&lt;div class="record" data-state="UT"&gt;
78    &lt;h1 class="name"&gt;Customer 3&lt;/h1&gt;
79    &lt;ul&gt;
80        &lt;li class="focus"&gt;Focus: &lt;/li&gt;
81        &lt;li class="course"&gt;Course: &lt;/li&gt;
82        &lt;li class="business"&gt;Business: &lt;/li&gt;
83        &lt;li class="address"&gt;Location: SLC &lt;span class="state"&gt;UT&lt;/span&gt;&lt;/li&gt;
84    &lt;/ul&gt;
85&lt;/div&gt;
86
87
88&lt;div id="filters"&gt;
89&lt;button class="state-button state-button-ak" data-state="AK"&gt;Alaska&lt;/button&gt;
90&lt;button class="state-button state-button-ar" data-state="AR"&gt;Arkansas&lt;/button&gt;
91&lt;button class="state-button state-button-ca" data-state="CA"&gt;California&lt;/button&gt;
92&lt;button class="state-button state-button-ca" data-state="AZ"&gt;Arizona&lt;/button&gt;
93&lt;button class="state-button state-button-ut" data-state="UT"&gt;Utah&lt;/button&gt;
94&lt;/div&gt;$(&quot;#move-filters-here&quot;).append($(&quot;#filters&quot;));
95$(&quot;#filters&quot;).append(&quot;#move-filters-here&quot;);
96

Source https://stackoverflow.com/questions/70413990

QUESTION

Project loom, what happens when virtual thread makes a blocking system call?

Asked 2021-Nov-30 at 21:58

I was investigating how Project Loom works and what kind of benefits it can bring to my company.

So I understand the motivation, for standard servlet based backend, there is always a thread pool that executes a business logic, once thread is blocked because of IO it can't do anything but wait. So let's say I have a backend application that has single endpoint , the business logic behind this endpoint is to read some data using JDBC which internally uses InputStream which again will use blocking system call( read() in terms of Linux). So if I have 200 hundred users reaching this endpoint, I need to create 200 threads each waiting for IO.

Now let's say I switched a thread pool to use virtual threads instead. According to Ben Evans in the article Going inside Java’s Project Loom and virtual threads:

Instead, virtual threads automatically give up (or yield) their carrier thread when a blocking call (such as I/O) is made.

So as far as I understand, if I have amount of OS threads equals to amount of CPU cores and unbounded amount of virtual threads, all OS threads will still wait for IO and Executor service won't be able to assign new work for Virtual threads because there are no available threads to execute it. How is it different from regular threads , at least for OS threads I can scale it to thousand to increase the throughput. Or Did I just misunderstood the use case for Loom ? Thanks in advance

Addon

I just read this mailing list:

Virtual threads love blocking I/O. If the thread needs to block in say a Socket read then this releases the underlying kernel thread to do other work

I am not sure I understand it, there is no way for OS to release the thread if it does a blocking call such as read, for these purposes kernel has non blocking syscalls such as epoll which doesn't block the thread and immediately returns a list of file descriptors that have some data available. Does the quote above implies that under the hood , JVM will replace a blocking read with non blocking epoll if thread that called it is virtual ?

ANSWER

Answered 2021-Nov-30 at 21:58

Your first excerpt is missing the important point:

Instead, virtual threads automatically give up (or yield) their carrier thread when a blocking call (such as I/O) is made. This is handled by the library and runtime [...]

The implication is this: if your code makes a blocking call into the library (for example NIO) the library detects that you call it from a virtual thread and will turn the blocking call into a non-blocking call, park the virtual thread and continue processing some other virtual threads code.

Only if no virtual thread is ready to execute will a native thread be parked.

Note that your code never calls a blocking syscall, it calls into the java libraries (that currently execute the blocking syscall). Project Loom replaces the layers between your code and the blocking syscall and can therefore do anything it wants - as long as the result for your calling code looks the same.

Source https://stackoverflow.com/questions/70174468

QUESTION

Koltin return null if value is null else

Asked 2021-Nov-24 at 14:17

I work with some business logic written in Kotlin. I've got such a case in my method - I check a value for null, and if it IS null - I want to return null, else do some logic. My version looks like:

1fun calculateFoo(parameter: SomeObject?): ReturnObject? = 
2    if (parameter == null) null
3    else performCalculation(parameter)
4

Literally "If value is null then return itself else process it". Normally, we do something if value is NOT null, like elvis operator, but here is "reversed" logic. Is there a better solution for this?

ANSWER

Answered 2021-Nov-24 at 14:14

You can use the ?. operator in combination with let.

1fun calculateFoo(parameter: SomeObject?): ReturnObject? = 
2    if (parameter == null) null
3    else performCalculation(parameter)
4fun calculateFoo(parameter: SomeObject?): ReturnObject? = 
5    parameter?.let { performCalculation(it) }
6

Source https://stackoverflow.com/questions/70097097

QUESTION

Pandas group cumsum with condition

Asked 2021-Oct-12 at 20:27

I have the following df:

1df = pd.DataFrame({&quot;values&quot;:[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],&quot;signal&quot;:['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4    values  signal
50   1       L_exit
61   5       None
72   7       None
83   3       R_entry
94   0       R_exit
105   9       None
116   8       L_entry
127   8       L_exit
138   7       None
149   5       R_entry
1510  8       R_exit
1611  1       R_entry
1712  0       R_exit
1813  0       L_entry
1914  0       L_exit
2015  0       L_entry
2116  2       R_exit
2217  5       None
23

My goal is to add a tx column like this:

1df = pd.DataFrame({&quot;values&quot;:[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],&quot;signal&quot;:['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4    values  signal
50   1       L_exit
61   5       None
72   7       None
83   3       R_entry
94   0       R_exit
105   9       None
116   8       L_entry
127   8       L_exit
138   7       None
149   5       R_entry
1510  8       R_exit
1611  1       R_entry
1712  0       R_exit
1813  0       L_entry
1914  0       L_exit
2015  0       L_entry
2116  2       R_exit
2217  5       None
23   values   signal  num
240   1       L_exit  nan
251   5       None    nan
262   7       None    nan
273   3       R_entry 1.00
284   0       R_exit  1.00
295   9       None    1.00
306   8       L_entry 1.00
317   8       L_exit  1.00
328   7       None    nan
339   5       R_entry 2.00
3410  8       R_exit  2.00
3511  1       R_entry 2.00
3612  0       R_exit  2.00
3713  0       L_entry 2.00
3814  0       L_exit  2.00
3915  0       L_entry nan
4016  2       R_exit  nan
4117  5       None    nan
42

Business logic: when there's a signal of R_entry we group a tx until there's L_exit (if theres another R_entry - ignore it)

visualizing enter image description here

What have I tried?

1df = pd.DataFrame({&quot;values&quot;:[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],&quot;signal&quot;:['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4    values  signal
50   1       L_exit
61   5       None
72   7       None
83   3       R_entry
94   0       R_exit
105   9       None
116   8       L_entry
127   8       L_exit
138   7       None
149   5       R_entry
1510  8       R_exit
1611  1       R_entry
1712  0       R_exit
1813  0       L_entry
1914  0       L_exit
2015  0       L_entry
2116  2       R_exit
2217  5       None
23   values   signal  num
240   1       L_exit  nan
251   5       None    nan
262   7       None    nan
273   3       R_entry 1.00
284   0       R_exit  1.00
295   9       None    1.00
306   8       L_entry 1.00
317   8       L_exit  1.00
328   7       None    nan
339   5       R_entry 2.00
3410  8       R_exit  2.00
3511  1       R_entry 2.00
3612  0       R_exit  2.00
3713  0       L_entry 2.00
3814  0       L_exit  2.00
3915  0       L_entry nan
4016  2       R_exit  nan
4117  5       None    nan
42g = ( df['signal'].eq('R_entry') |  df_tx['signal'].eq('L_exit') ).cumsum() 
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill() 
44

problem is that it increments every time it has 'R_entry'

ANSWER

Answered 2021-Oct-12 at 20:18

Let's try (hopefully self-explained):

1df = pd.DataFrame({&quot;values&quot;:[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],&quot;signal&quot;:['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4    values  signal
50   1       L_exit
61   5       None
72   7       None
83   3       R_entry
94   0       R_exit
105   9       None
116   8       L_entry
127   8       L_exit
138   7       None
149   5       R_entry
1510  8       R_exit
1611  1       R_entry
1712  0       R_exit
1813  0       L_entry
1914  0       L_exit
2015  0       L_entry
2116  2       R_exit
2217  5       None
23   values   signal  num
240   1       L_exit  nan
251   5       None    nan
262   7       None    nan
273   3       R_entry 1.00
284   0       R_exit  1.00
295   9       None    1.00
306   8       L_entry 1.00
317   8       L_exit  1.00
328   7       None    nan
339   5       R_entry 2.00
3410  8       R_exit  2.00
3511  1       R_entry 2.00
3612  0       R_exit  2.00
3713  0       L_entry 2.00
3814  0       L_exit  2.00
3915  0       L_entry nan
4016  2       R_exit  nan
4117  5       None    nan
42g = ( df['signal'].eq('R_entry') |  df_tx['signal'].eq('L_exit') ).cumsum() 
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill() 
44signals = df['signal']
45
46after_entry = signals.where(signals.eq('R_entry')).ffill().eq('R_entry')
47before_exit = signals.where(signals.eq('L_exit')).bfill().eq('L_exit')
48
49valids = after_entry &amp; before_exit
50
51
52blocks = signals.where(valids).ffill()[::-1].eq('L_exit').cumsum()[::-1]
53valid_blocks = (blocks.groupby(blocks).transform('size') &gt; 2)
54valid_entries = valid_blocks &amp; (~blocks.duplicated())
55
56df.loc[valid_blocks, 'num'] = valid_entries.cumsum()
57

Output:

1df = pd.DataFrame({&quot;values&quot;:[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],&quot;signal&quot;:['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4    values  signal
50   1       L_exit
61   5       None
72   7       None
83   3       R_entry
94   0       R_exit
105   9       None
116   8       L_entry
127   8       L_exit
138   7       None
149   5       R_entry
1510  8       R_exit
1611  1       R_entry
1712  0       R_exit
1813  0       L_entry
1914  0       L_exit
2015  0       L_entry
2116  2       R_exit
2217  5       None
23   values   signal  num
240   1       L_exit  nan
251   5       None    nan
262   7       None    nan
273   3       R_entry 1.00
284   0       R_exit  1.00
295   9       None    1.00
306   8       L_entry 1.00
317   8       L_exit  1.00
328   7       None    nan
339   5       R_entry 2.00
3410  8       R_exit  2.00
3511  1       R_entry 2.00
3612  0       R_exit  2.00
3713  0       L_entry 2.00
3814  0       L_exit  2.00
3915  0       L_entry nan
4016  2       R_exit  nan
4117  5       None    nan
42g = ( df['signal'].eq('R_entry') |  df_tx['signal'].eq('L_exit') ).cumsum() 
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill() 
44signals = df['signal']
45
46after_entry = signals.where(signals.eq('R_entry')).ffill().eq('R_entry')
47before_exit = signals.where(signals.eq('L_exit')).bfill().eq('L_exit')
48
49valids = after_entry &amp; before_exit
50
51
52blocks = signals.where(valids).ffill()[::-1].eq('L_exit').cumsum()[::-1]
53valid_blocks = (blocks.groupby(blocks).transform('size') &gt; 2)
54valid_entries = valid_blocks &amp; (~blocks.duplicated())
55
56df.loc[valid_blocks, 'num'] = valid_entries.cumsum()
57    values   signal  num
580        1   L_exit  NaN
591        5     None  NaN
602        7     None  NaN
613        3  R_entry  1.0
624        0   R_exit  1.0
635        9     None  1.0
646        8  L_entry  1.0
657        8   L_exit  1.0
668        7     None  NaN
679        5  R_entry  2.0
6810       8   R_exit  2.0
6911       1  R_entry  2.0
7012       0   R_exit  2.0
7113       0  L_entry  2.0
7214       0   L_exit  2.0
7315       0  L_entry  NaN
7416       2   R_exit  NaN
7517       5     None  NaN
76

Source https://stackoverflow.com/questions/69546268

QUESTION

Reactjs separation of UI and business logic

Asked 2021-Sep-26 at 09:14

I am new to react and I find it sore in the eyes to look at the component flooded with lots of functions and variable initializations together with the UI. Is it possible to separate them?

Instead of the default setup, like below. How do I separate the business logic into another file?

1function MyComponent() {
2    const [data, setData] = useState('');
3    const someFunc = () =&gt; {
4        //do something.
5    };
6    ... some 100-liner initializations
7
8   return ( 
9       ...
10   )
11}
12

ANSWER

Answered 2021-Sep-26 at 08:50

A common approach that I use myself is to separate the business logic into its own file myComponentHelper.js

This will also make it easier to test the function because it will not be able to use and change the react state without having it passed in as arguments and returning the changes.

1function MyComponent() {
2    const [data, setData] = useState('');
3    const someFunc = () =&gt; {
4        //do something.
5    };
6    ... some 100-liner initializations
7
8   return ( 
9       ...
10   )
11}
12myComponent/
13  myComponent.jsx
14  myComponentHelper.js
15  myComponentTest.js
16
1function MyComponent() {
2    const [data, setData] = useState('');
3    const someFunc = () =&gt; {
4        //do something.
5    };
6    ... some 100-liner initializations
7
8   return ( 
9       ...
10   )
11}
12myComponent/
13  myComponent.jsx
14  myComponentHelper.js
15  myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21    const [data, setData] = useState('');
22    
23    const x = someFunc(data);
24
25    return ( 
26        ...
27    )
28}
29
1function MyComponent() {
2    const [data, setData] = useState('');
3    const someFunc = () =&gt; {
4        //do something.
5    };
6    ... some 100-liner initializations
7
8   return ( 
9       ...
10   )
11}
12myComponent/
13  myComponent.jsx
14  myComponentHelper.js
15  myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21    const [data, setData] = useState('');
22    
23    const x = someFunc(data);
24
25    return ( 
26        ...
27    )
28}
29// myComponentHelper.js
30
31export const someFunc = (data) =&gt; {
32    //do something.
33    return something;
34}
35
1function MyComponent() {
2    const [data, setData] = useState('');
3    const someFunc = () =&gt; {
4        //do something.
5    };
6    ... some 100-liner initializations
7
8   return ( 
9       ...
10   )
11}
12myComponent/
13  myComponent.jsx
14  myComponentHelper.js
15  myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21    const [data, setData] = useState('');
22    
23    const x = someFunc(data);
24
25    return ( 
26        ...
27    )
28}
29// myComponentHelper.js
30
31export const someFunc = (data) =&gt; {
32    //do something.
33    return something;
34}
35// myComponentTest.js
36
37import { someFunc } from './myComponentHelper';
38
39test(&quot;someFunc - When data is this - Should return this&quot;, () =&gt; {
40    const data = {...};
41    const result = someFunc(data);
42    expect(result).toEqual(&quot;correct business data&quot;);
43});
44

Source https://stackoverflow.com/questions/69332889

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Business

Tutorials and Learning Resources are not available at this moment for Business

Share this Page

share link

Get latest updates on Business