问:
Combining form input column data with just created id autoincrement data on the fly
I have a table with cases in which on HTML form POST I create an INT case_id autoincrement number. In this table I would like to have a filed nas_br witch will be a varchar column in whom I would like to combine the ID field from form input + case_id just created on insert.

Example: When I create a new case I pass the ID filed of let's say number 3, case_id is created on an insert with number 4. I need to pass that info automatically to field nas_br so it would be 34. (I will add a dot in between but that's easy I guess).

My question is is this even possible to do on the fly because case_id is made on the insert, or I need separate process. How can I do this automatically on form input?

EDIT:
Generated Columns are not supported in MARIADB on primary key/autoincrement.

```<code>$sql = "INSERT INTO PREDMETIF (ID, NAZIV, PROTUSTRANKA, SUD, SUDBROJ, PREDMET, VPS, grad, post_br, adresa, jb, upr_tj, sudac, datum, status) VALUES ('$STRANKAFID','$STRANKAFNAZ','$PROTUSTRANKA', '$SUD', '$SUDBROJ', '$PREDMET', '$VPS', '$grad', '$post_br', '$adresa', '$jb', '$upr_tj', '$sudac', '$datum', '$status')";
            $query = mysqli_query($conn, $sql);
</code>```

EDIT
As using Generated Columns is not supported on primary keys and AUTO_INCREMENT, found the other solution here: What is the alternative for generated column in MySQL 5.6.
This creates a new table in Views and copy the table PREDMETIF with added column nas_br and does the adding. It's not in the original table but it gets to job done.

```<code>CREATE VIEW PREDMETIFView AS (
    SELECT ID, case_id, COALESCE(CONCAT(ID, '.', case_id)) AS nas_br
    FROM PREDMETIF
)
</code>```

答:
Instead of implemeting some (potentially cumbersome) logic to just generate a derived value, why not simply use a computed column?

If the column does not yet exist:

```<code>alter table predmetif
    add column nas_br varchar(10)
    generated always as concat(id, '.', case_id) stored;
</code>```

Or if is already there:

```<code>alter table predmetif
    modify column nas_br varchar(10)
    generated always as concat(id, '.', case_id) stored;
</code>```

Then, you can just leave that column apart when inserting into the table, and rest assured that your database will manage it under the hood.

Side note: mungling paramaters in the query string is bad practice (some would say: evil). You should seriously consider using paramaterized queries, to make your queries more efficient and safer.

Body:
I have a table with cases in which on HTML form POST I create an INT case_id autoincrement number. In this table I would like to have a filed nas_br witch will be a varchar column in whom I would like to combine the ID field from form input + case_id just created on insert.

Example: When I create a new case I pass the ID filed of let's say number 3, case_id is created on an insert with number 4. I need to pass that info automatically to field nas_br so it would be 34. (I will add a dot in between but that's easy I guess).

My question is is this even possible to do on the fly because case_id is made on the insert, or I need separate process. How can I do this automatically on form input?

EDIT:
Generated Columns are not supported in MARIADB on primary key/autoincrement.

$sql = "INSERT INTO PREDMETIF (ID, NAZIV, PROTUSTRANKA, SUD, SUDBROJ, PREDMET, VPS, grad, post_br, adresa, jb, upr_tj, sudac, datum, status) VALUES ('$STRANKAFID','$STRANKAFNAZ','$PROTUSTRANKA', '$SUD', '$SUDBROJ', '$PREDMET', '$VPS', '$grad', '$post_br', '$adresa', '$jb', '$upr_tj', '$sudac', '$datum', '$status')";
            $query = mysqli_query($conn, $sql);

EDIT
As using Generated Columns is not supported on primary keys and AUTO_INCREMENT, found the other solution here: What is the alternative for generated column in MySQL 5.6.
This creates a new table in Views and copy the table PREDMETIF with added column nas_br and does the adding. It's not in the original table but it gets to job done.

CREATE VIEW PREDMETIFView AS (
    SELECT ID, case_id, COALESCE(CONCAT(ID, '.', case_id)) AS nas_br
    FROM PREDMETIF
)

Body:
Instead of implemeting some (potentially cumbersome) logic to just generate a derived value, why not simply use a computed column?

If the column does not yet exist:

alter table predmetif
    add column nas_br varchar(10)
    generated always as concat(id, '.', case_id) stored;

Or if is already there:

alter table predmetif
    modify column nas_br varchar(10)
    generated always as concat(id, '.', case_id) stored;

Then, you can just leave that column apart when inserting into the table, and rest assured that your database will manage it under the hood.

Side note: mungling paramaters in the query string is bad practice (some would say: evil). You should seriously consider using paramaterized queries, to make your queries more efficient and safer.


来源: stackexchange

问:
How to show that two integers with a sum of zero have one's complement representations that are bit-complementary?
I've been stuck on this question for a while now:

Show mathematically that two integers that have a sum of zero have one’s complement representations that are bit-complementary.

答:
Here is a simple proof and a counter example:

One's complement representation by definition represents negative values with bit-complement. In other words -n is represented as ~n. If any two integers have a sum of zero, either they are both zero or one is the opposite of the other.

if they are both zero, they do not necessarily have one’s complement representations that are bit-complementary.

if they are opposite of each other and non-zero, then yes, they are bit-complementary of one another.

ContentLicense: CC BY-SA 4.0


问:
javascript - call sync function as async
I want to call a sync function as async without making the function itself async. So what I'm basically trying to do is this: ("asynccall" is pseudocode for something calling the function as async)

asynccall doSomething(a, b, c);

function doSomething(a, b, c) {
   //doing something
}
```

<p>the closest I got to doing that is by creating an async function which calls the sync funtion:</p>

<pre class="lang-js prettyprint-override"><code>aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   //doing something
}
</code>```

which does work, but I don't want to create this redundant function. Is there a way to achieve what's done in example 2 in a way that looks like example 1?

答:
When ever I need to, I do it this way:

```<code>setTimeout(function() {
    // do your function
}, 0);
</code>```

This essentially creates a Task Here's an article by MDN explaining what they are and how they work. Note that they also recommend the queueMicrotask function but I would recommend the approach above as it ensures the tasks is queued when the browser is ready.

Edit: I forgot to add the link (silly of me): https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide (Microtask)

https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API (Tasks)

Body:
I want to call a sync function as async without making the function itself async. So what I'm basically trying to do is this: ("asynccall" is pseudocode for something calling the function as async)

asynccall doSomething(a, b, c);

function doSomething(a, b, c) {
   //doing something
}

the closest I got to doing that is by creating an async function which calls the sync funtion:

aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   //doing something
}

which does work, but I don't want to create this redundant function. Is there a way to achieve what's done in example 2 in a way that looks like example 1?

Body:
When ever I need to, I do it this way:

setTimeout(function() {
    // do your function
}, 0);

This essentially creates a Task Here's an article by MDN explaining what they are and how they work. Note that they also recommend the queueMicrotask function but I would recommend the approach above as it ensures the tasks is queued when the browser is ready.

Edit: I forgot to add the link (silly of me): https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide (Microtask)

https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API (Tasks)


答:
What you are trying to do denotes a possible misunderstanding on how Javascript engine works.

Javascript runs single threaded. It means that it can only do one operation at a time (it processes statements one by one). Some sort of async execution can be achieved but only when there are I/O (input/output) operations involved or by using some particular APIs like createTimeout() or createInterval().

I recommend you this article to better understand this concept.

SHORT ANSWER:

If there are not true asynchronous tasks (like I/O operations) involved, then

THIS:

```<code>aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   // do something
}
</code>```

IS the same (but unnecessarily less performant) as this:

```<code>doSomething(a, b, c);

function doSomething(a, b, c) {
   // do something
}
</code>```

NOTE ABOUT OTHER ANSWERS:

```<code>doSomething(a, b, c);

function doSomething(a, b, c) {
    setTimeout(function() {
        // do something
    }, 0);
}
</code>```

This will not make the code in "// do something" "asynchronous". It will only delay the execution of that code until the end of the current stack (see article above). It would be most of the times considered as a bad practice or a hackish workaround. The same happens with promises and any other pattern that attempts to make synchronous code asynchronous in a single threaded engine.

Title: javascript - call sync function as async

Body:
What you are trying to do denotes a possible misunderstanding on how Javascript engine works.

Javascript runs single threaded. It means that it can only do one operation at a time (it processes statements one by one). Some sort of async execution can be achieved but only when there are I/O (input/output) operations involved or by using some particular APIs like createTimeout() or createInterval().

I recommend you this article to better understand this concept.

SHORT ANSWER:

If there are not true asynchronous tasks (like I/O operations) involved, then

THIS:

aDoSomething(a, b, c);

async function aDoSomething(a, b, c) {
   doSomething(a, b, c);
}

function doSomething(a, b, c) {
   // do something
}

IS the same (but unnecessarily less performant) as this:

doSomething(a, b, c);

function doSomething(a, b, c) {
   // do something
}

NOTE ABOUT OTHER ANSWERS:

doSomething(a, b, c);

function doSomething(a, b, c) {
    setTimeout(function() {
        // do something
    }, 0);
}

This will not make the code in "// do something" "asynchronous". It will only delay the execution of that code until the end of the current stack (see article above). It would be most of the times considered as a bad practice or a hackish workaround. The same happens with promises and any other pattern that attempts to make synchronous code asynchronous in a single threaded engine.


问:
Object-safe move element from the end of a vector to the end of another vector
I'm very new in C++.

I investigated a lot of articles about C++ and solution for moving vector's last element to another but I still don't understand how to do that.

I have two vectors:

```<code>std::vector<Person *> persons;
std::vector<Person *> availablePersons;
</code>```

and function:

```<code>MoveLast() {
    std::move(persons.end() - 1, persons.end(), std::back_inserter(availablePersons));
}
</code>```

But it looks very long and doesn't work as expected.

So I need simple and effective method without losing Person objects in the memory

答:
The vectors don't contain Person objects, they just contain pointers. Moving these pointers really means performing a copy. So you're doing two things, copying a pointer to one container and removing a pointer from another container. A simple implementation like this should be all you need:

```<code>MoveLast() {
    if (!persons.empty()) { // ensure source vector isn't empty
        availablePersons.push_back(persons.back()); // copy last element to destination
        persons.pop_back(); // remove last element from source
    }
}
</code>```

If your vectors held a type that was move-enabled then, as an optimization, you might change the second line to this:

```<code>availablePersons.push_back(std::move(persons.back())); // move last element to destination
</code>```

Body:
I'm very new in C++.

I investigated a lot of articles about C++ and solution for moving vector's last element to another but I still don't understand how to do that.

I have two vectors:

std::vector<Person *> persons;
std::vector<Person *> availablePersons;

and function:

MoveLast() {
    std::move(persons.end() - 1, persons.end(), std::back_inserter(availablePersons));
}

But it looks very long and doesn't work as expected.

So I need simple and effective method without losing Person objects in the memory

Body:
The vectors don't contain Person objects, they just contain pointers. Moving these pointers really means performing a copy. So you're doing two things, copying a pointer to one container and removing a pointer from another container. A simple implementation like this should be all you need:

MoveLast() {
    if (!persons.empty()) { // ensure source vector isn't empty
        availablePersons.push_back(persons.back()); // copy last element to destination
        persons.pop_back(); // remove last element from source
    }
}

If your vectors held a type that was move-enabled then, as an optimization, you might change the second line to this:

availablePersons.push_back(std::move(persons.back())); // move last element to destination


问:
CUDA : How to detect shared memory bank conflict on device with compute capabiliy >= 7.2?
On device with compute capability <= 7.2 , I always use

nvprof --events shared_st_bank_conflict

but when i run it on RTX2080ti with CUDA10 , it returns

Warning: Skipping profiling on device 0 since profiling is not supported on devices with compute capability greater than 7.2

So how can i detect whether there's share memory bank conflict on this devices ?

I've installed Nvidia Nsight Systems and Nsight Compute , find no such profiling report...

thks

答:
You can use --metrics:

Either

```<code>nv-nsight-cu-cli --metrics l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_ld.sum
</code>```

for conflicts when reading (load'ing) from shared memory, or

```<code>nv-nsight-cu-cli --metrics l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_st.sum
</code>```

for conflicting when writing  (store'ing) to shared memory.

Body:
You can use --metrics:

Either

nv-nsight-cu-cli --metrics l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_ld.sum

for conflicts when reading (load'ing) from shared memory, or

nv-nsight-cu-cli --metrics l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_st.sum

for conflicting when writing  (store'ing) to shared memory.


问:
matching row values (text) with column names and return value
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

```<code>region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396
</code>```

And I want to get something that looks like this:

```<code>region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA
</code>```

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396

And I want to get something that looks like this:

region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
A fifth option also using base functions

idx <- na.omit(cbind(match(names(df1), df1$region),
                     1:length(df1)))
vals <- as.integer(df1[idx])
df1[-1] <- NA
df1[idx] <- vals
df1
#   region   A  B   C  D   E   F
#1       H  NA NA  NA NA  NA  NA
#2       J  NA NA  NA NA  NA  NA
#3       A 820 NA  NA NA  NA  NA
#4       X  NA NA  NA NA  NA  NA
#5       M  NA NA  NA NA  NA  NA
#6       N  NA NA  NA NA  NA  NA
#7       C  NA NA 952 NA  NA  NA
#8       L  NA NA  NA NA  NA  NA
#9       E  NA NA  NA NA 944  NA
#10      F  NA NA  NA NA  NA 616
#11      P  NA NA  NA NA  NA  NA
#12      Q  NA NA  NA NA  NA  NA

data

Thanks to @akrun

df1 <- structure(list(region = c("H", "J", "A", "X", "M", "N", "C",
"L", "E", "F", "P", "Q"), A = c(796L, 568L, 820L, 292L, 872L,
100L, 940L, 960L, 980L, 236L, 796L, 568L), B = c(792L, 564L,
804L, 272L, 812L, 992L, 948L, 956L, 968L, 364L, 792L, 564L),
    C = c(844L, 508L, 748L, 260L, 792L, 972L, 952L, 952L, 956L,
    460L, 844L, 508L), D = c(812L, 268L, 528L, 324L, 760L, 880L,
    916L, 920L, 940L, 524L, 812L, 268L), E = c(796L, 320L, 560L,
    224L, 668L, 872L, 864L, 900L, 944L, 552L, 796L, 320L), F = c(776L,
    396L, 600L, 200L, 656L, 864L, 880L, 920L, 932L, 616L, 776L,
    396L)), class = "data.frame", row.names = c(NA, -12L))


问:
Speed up linq query perfomance
I'm running this linq query which is a little big.

```<code>var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());
</code>```

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.

答:
Overall, the performance of the query will largely depend on the table size, and availability of suitable indices.

A couple things I can note from that query:

This statement doesn't make a lot of sense: .Where(e => e.StartDate > new DateTime()). new DateTime() will initialize a DateTime from 01/01/0001. Any dates stored in an SQL Server DateTime column for example will be from 01/01/1753, so this seems rather moot. If the database/entity DateTime value is null-able, then .Where(e => e.StartDate.HasValue) would be more applicable. If the DateTime value is not null-able then this condition can be left off entirely.

So if the field is null-able, the Linq expression would look more like:

```<code>var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .OrderByDescending(e => e.StartDate)
    .ToList();
</code>```

If it's not null-able:

```<code>var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled)
    .OrderByDescending(e => e.StartDate)
    .ToList();
</code>```

The next culprit to eliminate: Lazy Load proxy hits. Does the Event property have navigation properties to any other entities?  If this is something like a web application and you are serializing entities to send back to the client, navigation property EF proxies can absolutely kill performance. Any code after this call that touches a navigation property will result in extra individual DB calls to lazy load these navigation properties. For methods that return lists of entities this can be critical. If an Event has a reference to something like a User and you load 1000 events referencing roughly 1000 users, when a serializer goes to serialize those 1000 events, it will "touch" each of the user references. This leads to ~1000 extra SQL statements effectively doing SELECT * FROM tblUser WHERE UserId = 1, SELECT * FROM tblUser WHERE UserId = 2... etc. etc. for each User ID in each Event.  If you need these related entities you can Eager load them with Include(e => e.User) which will be faster than loading them individually, but this does mean loading a lot of extra data into memory that your client/code may not need. You can avoid the lazy load hits by turning off lazy loading & proxies, but this will leave these entities with #null references which means any code expecting an Event entity with any related details may get one of these partially loaded entities. (not good, the entity should always be in a complete or complete-able state) The final option is to use Select to populate a view model for your results. This can speed up queries considerably because you can have EF compose a query to pull back just the data you need from whatever entities rather than everything or triggering lazy loads.

For example if you just need an EventId, EventNumber, Name, StartDate, and a UserName to display for the events:

```<code>var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .Select(e => new EventViewModel
    {
        EventId = e.EventId,
        EventNumber = e.EventNumber,
        Name = e.Name,
        StartDate = e.StartDate,
        UserName = e.User.Name
    })
    .OrderByDescending(e => e.StartDate)
    .ToList();
</code>```

This avoids any lazy load hits and reduces the query run to just the columns needed which can speed up queries significantly.

Next would be to look at the queries EF is running and their relevant execution plan. This can highlight missing/poor indexes, and any unexpected lazy load hits. The method for doing this would depend on your database, but involves running a Profiler against the DB to capture the SQL statements being run while you debug.  From here you can capture the SQL statements that EF generates then run those manually against your database with any DB-side analysis tools. (such as SSMS with SQL Server to get an execution plan which can identify missing indexes) Serializer lazy load hits in a web application are detectable as a lot of extra SQL statements executing after your method appears to have completed, but before the data gets back to the client. This is the serializer "touching" proxies resulting in lots of additional queries that the server has to wait to complete before the data is returned to the client.

Lastly would be data volume. Any system that is expected to grow over time should consider the amount of data that can eventually be returned. Anything that returns lists of data over time should incorporate server-side pagination where the client sends a page size and page # where the server can translate this into a .Skip(pageNumber * pageSize).Take(pageSize) operation. (/w page # starting at 0) Most data grid and like components should support server-side pagination to send these arguments to their data load methods.  These controls will need to know the total row count to set up pagination so you would need a method to return that count:

```<code>var rowCount = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .Count();
</code>```

Same conditions, no order by, and a .Count() with no ToList() etc. will compose an efficient Count query.

This should give you a few things to check and tweak to eliminate your performance pitfalls.

Title: Speed up linq query perfomance

Body:
I'm running this linq query which is a little big.

var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.

Body:
Overall, the performance of the query will largely depend on the table size, and availability of suitable indices.

A couple things I can note from that query:

This statement doesn't make a lot of sense: .Where(e => e.StartDate > new DateTime()). new DateTime() will initialize a DateTime from 01/01/0001. Any dates stored in an SQL Server DateTime column for example will be from 01/01/1753, so this seems rather moot. If the database/entity DateTime value is null-able, then .Where(e => e.StartDate.HasValue) would be more applicable. If the DateTime value is not null-able then this condition can be left off entirely.

So if the field is null-able, the Linq expression would look more like:

var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .OrderByDescending(e => e.StartDate)
    .ToList();

If it's not null-able:

var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled)
    .OrderByDescending(e => e.StartDate)
    .ToList();

The next culprit to eliminate: Lazy Load proxy hits. Does the Event property have navigation properties to any other entities?  If this is something like a web application and you are serializing entities to send back to the client, navigation property EF proxies can absolutely kill performance. Any code after this call that touches a navigation property will result in extra individual DB calls to lazy load these navigation properties. For methods that return lists of entities this can be critical. If an Event has a reference to something like a User and you load 1000 events referencing roughly 1000 users, when a serializer goes to serialize those 1000 events, it will "touch" each of the user references. This leads to ~1000 extra SQL statements effectively doing SELECT * FROM tblUser WHERE UserId = 1, SELECT * FROM tblUser WHERE UserId = 2... etc. etc. for each User ID in each Event.  If you need these related entities you can Eager load them with Include(e => e.User) which will be faster than loading them individually, but this does mean loading a lot of extra data into memory that your client/code may not need. You can avoid the lazy load hits by turning off lazy loading & proxies, but this will leave these entities with #null references which means any code expecting an Event entity with any related details may get one of these partially loaded entities. (not good, the entity should always be in a complete or complete-able state) The final option is to use Select to populate a view model for your results. This can speed up queries considerably because you can have EF compose a query to pull back just the data you need from whatever entities rather than everything or triggering lazy loads.

For example if you just need an EventId, EventNumber, Name, StartDate, and a UserName to display for the events:

var events = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .Select(e => new EventViewModel
    {
        EventId = e.EventId,
        EventNumber = e.EventNumber,
        Name = e.Name,
        StartDate = e.StartDate,
        UserName = e.User.Name
    })
    .OrderByDescending(e => e.StartDate)
    .ToList();

This avoids any lazy load hits and reduces the query run to just the columns needed which can speed up queries significantly.

Next would be to look at the queries EF is running and their relevant execution plan. This can highlight missing/poor indexes, and any unexpected lazy load hits. The method for doing this would depend on your database, but involves running a Profiler against the DB to capture the SQL statements being run while you debug.  From here you can capture the SQL statements that EF generates then run those manually against your database with any DB-side analysis tools. (such as SSMS with SQL Server to get an execution plan which can identify missing indexes) Serializer lazy load hits in a web application are detectable as a lot of extra SQL statements executing after your method appears to have completed, but before the data gets back to the client. This is the serializer "touching" proxies resulting in lots of additional queries that the server has to wait to complete before the data is returned to the client.

Lastly would be data volume. Any system that is expected to grow over time should consider the amount of data that can eventually be returned. Anything that returns lists of data over time should incorporate server-side pagination where the client sends a page size and page # where the server can translate this into a .Skip(pageNumber * pageSize).Take(pageSize) operation. (/w page # starting at 0) Most data grid and like components should support server-side pagination to send these arguments to their data load methods.  These controls will need to know the total row count to set up pagination so you would need a method to return that count:

var rowCount = _context.Event
    .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate.HasValue)
    .Count();

Same conditions, no order by, and a .Count() with no ToList() etc. will compose an efficient Count query.

This should give you a few things to check and tweak to eliminate your performance pitfalls.


问:
Svelte bind parent store from child
Can I use bind directive inside a child component,
If the variable I'm binding to is a parent's store?
How this relates to lifecycle events?
As long as child's onMount triggers before parent's onMount (at least when I create a tree of new components at once), if bind is successful, but variable starts with null, do I get reactivity or not?</p>

答:
No need to bind to a parent store, if reactivity is what you want.
Binds are reactive by default.
So when you bind a child variable to a parent variable, you get the child one updated whenever the parent one changes.
Per the relation to lifecycle events, considering that in the scenario you provide, parent-child couple is instantiated as a whole (i.e. the parent is not already mounted), what child sees from the parent variable depends on how it is declared and how, if any, it is updated with any of the available lifecycle events and/or it is read from any of the lifecycle events.
Rest assured the order:

parent beforeUpdate

parent afterUpdate

child beforeUpdate

child afterUpdate

child onMount

parent onMount

Thanks to everyone for taking time to reply and provide a repl,
Hope this answer gets agreement.

Thanks.

Title: Svelte bind parent store from child


答:
One way to call something "later", getting a promise in return, is to use Promise.resolve().then:

function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = Promise.resolve().then(() => doSomething(1, 2));

result.then(console.log);

console.log("synchronous code completed");```
</div>
</div>
</p>

<p>But you could also use your original idea, but with an IIFE:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = (async () => {
    await null;
    return doSomething(1, 2);
})();

result.then(console.log);

console.log("synchronous code completed");</code>```

If that looks like too much writing still, then make a generic function called asynccall, which you can then use for any function call:

function asynccall(f, thisArg, ...args) {
     return Promise.resolve().then(() => f.call(thisArg, ...args));
}

function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = asynccall(doSomething, null, 1, 2);

result.then(console.log);

console.log("synchronous code completed");```

Body:
One way to call something "later", getting a promise in return, is to use Promise.resolve().then:

function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = Promise.resolve().then(() => doSomething(1, 2));

result.then(console.log);

console.log("synchronous code completed");

But you could also use your original idea, but with an IIFE:

function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = (async () => {
    await null;
    return doSomething(1, 2);
})();

result.then(console.log);

console.log("synchronous code completed");

If that looks like too much writing still, then make a generic function called asynccall, which you can then use for any function call:

function asynccall(f, thisArg, ...args) {
     return Promise.resolve().then(() => f.call(thisArg, ...args));
}

function doSomething(a, b) {
     console.log("doing something");
     return a+b;
}

let result = asynccall(doSomething, null, 1, 2);

result.then(console.log);

console.log("synchronous code completed");


问:
I can't seem to make navigation drawer work: how to fix this?
I am new to Android Studio and I'm trying to learn how to use navigation drawer. However, I can't make it appear in preview. I have tried doing it automatically when creating a new activity but the result is the same here is what it looks like

These are the dependencies:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example."
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'androidx.navigation:navigation-fragment:2.0.0'
    implementation 'androidx.navigation:navigation-ui:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

答:
If you want show in editor preview - tools:openDrawer="start"

I found similar question:
What's the purpose of tools:openDrawer="start" when creating a DrawerLayout (with NavigationView) from the wizard?

Body:
I am new to Android Studio and I'm trying to learn how to use navigation drawer. However, I can't make it appear in preview. I have tried doing it automatically when creating a new activity but the result is the same here is what it looks like

These are the dependencies:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example."
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'androidx.navigation:navigation-fragment:2.0.0'
    implementation 'androidx.navigation:navigation-ui:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}


问:
create ActiveRecord model at runtime rails3
I want to create an ActiveRecord model at run time.

In my system I'm generating some reports and all of them bind with a database table/ views. So the only difference will be the table name.

So what I want to do is have an active record common class (preferably generated at runtime) and assign the table name at runtime. and i should be able to assign a a scope to select a date range. And I'm thinking of getting the column names at runtime to display data.

can anyone help me out on how to
create ActiveRecord model at runtime

assign scope method

and I'm on rails3

thanks in advance

cheers

sameera

答:
The easiest way to do this assuming the view names are static is to create one module with the common functionality and then include it into your base models..

module ModuleA
...
end

class A extends ActiveRecord::Base
  include ModuleA
end

Class B extends ActiveRecord::Base
  include ModuleA
end

ContentLicense: CC BY-SA 3.0


问:
open_basedir restriction in effect. File(/) is not within the allowed path(s):
I'm getting this error on an avatar upload on my site.  I've never gotten it before and nothing was changed recently for me to begin getting this error...</p>

```<code>Warning: is_writable() [function.is-writable]:
open_basedir restriction in effect.
File(/) is not within the allowed path(s):
</code>```

答:
If used ispconfig3:

Go to Website section -> Options -> PHP open_basedir:

In this field has described allowed paths and each path is separated
with ":"

/var/www/clients/client2/web3/image:/var/www/clients/client2/web3/web:/var/www/...
  and so on

So here must put the path that you want to have access, in my case is:

/var/www/clients/client2/web3/image:

The problem appears because:

When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it.

ContentLicense: CC BY-SA 2.5

Body:
I'm getting this error on an avatar upload on my site.  I've never gotten it before and nothing was changed recently for me to begin getting this error...

Warning: is_writable() [function.is-writable]:
open_basedir restriction in effect.
File(/) is not within the allowed path(s):


问:
Iteration over two vectors and deleting specific positions
I am build a game and I am trying to work out the collision detection. I got four classes for now. Game, Player, Projectile and Enemy. So if I shoot with the Player or the Enemy shoots I create a new projectile and emlace_back() it into a vector. All my Enemys are also stored inside a vector. All of theses Objects are created with new.
So my collision detections looks like this:

```<code>void Game::CheckHit() {

    auto enemy = m_Enemys.begin();
    auto projectile = m_Projectiles.begin();

    while(projectile != m_Projectiles.end()){

        if (//Hit Detected with player) {
            delete (*projectile);
            m_Projectiles.erase(projectile);
            m_Player->PlayerHit();
        }

        while (enemy != m_Enemys.end()) {
            if (//Hit Detected with enemy) {

                delete (*enemy);
                delete (*projectile);
                m_Projectiles.erase(projectile);
                m_Enemys.erase(enemy);
                m_Player->BulletHit();
            } else
                enemy++;
        }
    }
}
</code>```

The Problem I have is I dont actually know when I should increment the projectile iterator because I only need to do that if neither an Player nor and Enemys got it with that specific projectile. Any help is appreciated.

答:
If the projectile hits the player you delete it, so continuing to use it would be UB. You need to start checking the next projectile instead.

Also note that erase returns an iterator to the element after the erased one, so when you erase, you should not increase the iterator, just use what's returned from erase.

I also recommend that you use a vector of smart pointers instead of raw pointers. You could then just call erase and not have to manually delete every object.

It could look like this:

```<code>void Game::CheckHit() {
    for(auto projectile = m_Projectiles.begin(); projectile != m_Projectiles.end();) {
        bool hit = false;

        if(/*Hit player*/) {
            hit = true;
            m_Player->PlayerHit();
        } else {
            for(auto enemy = m_Enemys.begin(); enemy != m_Enemys.end();) {
                if(/* Hit enemy*/) {
                    hit = true;
                    enemy = m_Enemys.erase(enemy);
                    m_Player->BulletHit();
                    break;
                } else {
                    ++enemy;
                }
            }
        }

        if(hit) projectile = m_Projectiles.erase(projectile);
        else ++projectile;
    }
}
</code>```

Body:
I am build a game and I am trying to work out the collision detection. I got four classes for now. Game, Player, Projectile and Enemy. So if I shoot with the Player or the Enemy shoots I create a new projectile and emlace_back() it into a vector. All my Enemys are also stored inside a vector. All of theses Objects are created with new.
So my collision detections looks like this:

void Game::CheckHit() {

    auto enemy = m_Enemys.begin();
    auto projectile = m_Projectiles.begin();

    while(projectile != m_Projectiles.end()){

        if (//Hit Detected with player) {
            delete (*projectile);
            m_Projectiles.erase(projectile);
            m_Player->PlayerHit();
        }

        while (enemy != m_Enemys.end()) {
            if (//Hit Detected with enemy) {

                delete (*enemy);
                delete (*projectile);
                m_Projectiles.erase(projectile);
                m_Enemys.erase(enemy);
                m_Player->BulletHit();
            } else
                enemy++;
        }
    }
}

The Problem I have is I dont actually know when I should increment the projectile iterator because I only need to do that if neither an Player nor and Enemys got it with that specific projectile. Any help is appreciated.

Body:
If the projectile hits the player you delete it, so continuing to use it would be UB. You need to start checking the next projectile instead.

Also note that erase returns an iterator to the element after the erased one, so when you erase, you should not increase the iterator, just use what's returned from erase.

I also recommend that you use a vector of smart pointers instead of raw pointers. You could then just call erase and not have to manually delete every object.

It could look like this:

void Game::CheckHit() {
    for(auto projectile = m_Projectiles.begin(); projectile != m_Projectiles.end();) {
        bool hit = false;

        if(/*Hit player*/) {
            hit = true;
            m_Player->PlayerHit();
        } else {
            for(auto enemy = m_Enemys.begin(); enemy != m_Enemys.end();) {
                if(/* Hit enemy*/) {
                    hit = true;
                    enemy = m_Enemys.erase(enemy);
                    m_Player->BulletHit();
                    break;
                } else {
                    ++enemy;
                }
            }
        }

        if(hit) projectile = m_Projectiles.erase(projectile);
        else ++projectile;
    }
}


问:
Is there a Java library for the Bitly API?
Is there a Java library for making Bitly requests?  I'm looking to both shorten links, and look up info on clicks, etc. of links.  Yes, I know it's a straight-forward HTML API and I could just code directly to the HTML or write a library myself, but surely someone else has written such a library, and it would save me a couple of steps to use it.</p>

答: This looks promising: http://code.google.com/p/bitlyj/</p>


问:
How to filter multidimensional array based on another multidimensional array of exclusions?
I'm attempting to filter a multidimensional array containing (>40,000) products.  Each product entry/subarray contains the product id and some product attributes.

I have an associative exclusion array which has 1 or more blacklisted values pertaining to specific attributes.

If a product has any key-value pairs that are specified in my exclusion array, then that product/subarray should be filtered out.

Exclusions array:

```<code>$exclusions = [
    'Discontinue Status' => [
        'Discontinued',
        'Run Down Stock',
    ],
    'Hazardous' => [
        'No',
    ],
];
</code>```

Sample products array:

```<code>$products = [
    [
        'Product ID' => '452',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '463',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '477',
        'Discontinue Status' => 'Run Down Stock',
        'Hazardous' => 'Yes',
    ],
    [
        'Product ID' => '502',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
];
</code>```

Expected output:

```<code>[
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
]
</code>```

I was only able to get as far as returning the correct number of products/items but only the exclusion associated with that item and not the item itself with the following code.

```<code>    $exclusions = $this->exclusions;

    $products = [];

    foreach ($array as $product) {

        $filtered = array_filter($product, function ($val, $key) use ($exclusions) {
                return isset($exclusions[$key]) && !in_array($val, $exclusions[$key]);
            },
            ARRAY_FILTER_USE_BOTH
        );

        $products[] = $filtered;

    }

    $result = array_filter(array_map('array_filter', $products));

    echo '```' . var_export($result, true) . '```';
    echo count($result);
</code>```

答:
Breaking your exclusion array into separate variables is not advisable because this will make your code harder / more tedious to maintain when you want to modify the exclusion list.

Iterate your products array just one time.  Inside that loop, loop the attributes in each product having keys which match the first level keys in the exclusion array. This is what array_intersect_key() does best and this prevents performing an unnecessary comparison on the Product ID elements.  As soon as you find a disqualifying condition to be satisfied, stop the inner loop for best efficiency.

Code #1 (Demo) *my recommendation

```<code>$result = [];
foreach ($products as $product) {
    foreach (array_intersect_key($product, $exclusions) as $key => $value) {
        if (in_array($value, $exclusions[$key])) {
            continue 2;
        }
    }
    $result[] = $product;
}
var_export($result);
</code>```

Code #2: (Demo)

```<code>foreach ($products as $index => $product) {
    foreach (array_intersect_key($product, $exclusions) as $key => $value) {
        if (in_array($value, $exclusions[$key])) {
            unset($products[$index]);
            break;
        }
    }
}
var_export(array_values($products));
</code>```

Code #3: (Demo)

```<code>var_export(
    array_values(
        array_filter(
            $products,
            function($product) use ($exclusions) {
                return !array_filter(
                    array_intersect_key($product, $exclusions),
                    function($value, $key) use ($exclusions) {
                        return in_array($value, $exclusions[$key]);
                    },
                    ARRAY_FILTER_USE_BOTH
                );
            }
        )
    )
);
</code>```

Code #4: (Demo)

```<code>var_export(
    array_values(
        array_filter(
            $products,
            fn($product) => !array_filter(
                array_intersect_key($product, $exclusions),
                fn($value, $key) => in_array($value, $exclusions[$key]),
                ARRAY_FILTER_USE_BOTH
            )
        )
    )
);
</code>```

Code #1 uses continue 2; to stop the halt the inner loop, avoid storing the current product in the output array, then return to the outer loop to carry on processing the next product.

Code #2 is directly modifying the $products array.  By unsetting products, the array may cease to be an indexed array (the keys may have gaps between integers). If desirable, call array_values() after the loop to re-index the output.

Code #3 is using a functional style.  It is common for language constructs (e.g. foreach()) to outperform functional iterators, so I will assume this snippet (and Code #4) will be slightly slower than the first two.  Furthermore, array_filter() doesn't enjoy the early return that the foreach loops have with break and continue.  In other words, Code #3 & #4 will continue checking against the exclusion array even if a disqualifying condition has already been satisfied for a given product. And if that wasn't enough, I simply find the syntax too convoluted.

Code #4 is the same as Code #3, but is using the slightly shorter "arrow function" syntax which is available from PHP7.4 and up.  This affords the omission of use() and some other characters, but I still find the snippet less intuitive/readable compared to Code #1 & #2.

Body:
I'm attempting to filter a multidimensional array containing (>40,000) products.  Each product entry/subarray contains the product id and some product attributes.

I have an associative exclusion array which has 1 or more blacklisted values pertaining to specific attributes.

If a product has any key-value pairs that are specified in my exclusion array, then that product/subarray should be filtered out.

Exclusions array:

$exclusions = [
    'Discontinue Status' => [
        'Discontinued',
        'Run Down Stock',
    ],
    'Hazardous' => [
        'No',
    ],
];

Sample products array:

$products = [
    [
        'Product ID' => '452',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '463',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '477',
        'Discontinue Status' => 'Run Down Stock',
        'Hazardous' => 'Yes',
    ],
    [
        'Product ID' => '502',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
];

Expected output:

[
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
]

I was only able to get as far as returning the correct number of products/items but only the exclusion associated with that item and not the item itself with the following code.

    $exclusions = $this->exclusions;

    $products = [];

    foreach ($array as $product) {

        $filtered = array_filter($product, function ($val, $key) use ($exclusions) {
                return isset($exclusions[$key]) && !in_array($val, $exclusions[$key]);
            },
            ARRAY_FILTER_USE_BOTH
        );

        $products[] = $filtered;

    }

    $result = array_filter(array_map('array_filter', $products));

    echo '
' . var_export($result, true) . '
';
    echo count($result);

Body:
Breaking your exclusion array into separate variables is not advisable because this will make your code harder / more tedious to maintain when you want to modify the exclusion list.

Iterate your products array just one time.  Inside that loop, loop the attributes in each product having keys which match the first level keys in the exclusion array. This is what array_intersect_key() does best and this prevents performing an unnecessary comparison on the Product ID elements.  As soon as you find a disqualifying condition to be satisfied, stop the inner loop for best efficiency.

Code #1 (Demo) *my recommendation

$result = [];
foreach ($products as $product) {
    foreach (array_intersect_key($product, $exclusions) as $key => $value) {
        if (in_array($value, $exclusions[$key])) {
            continue 2;
        }
    }
    $result[] = $product;
}
var_export($result);

Code #2: (Demo)

foreach ($products as $index => $product) {
    foreach (array_intersect_key($product, $exclusions) as $key => $value) {
        if (in_array($value, $exclusions[$key])) {
            unset($products[$index]);
            break;
        }
    }
}
var_export(array_values($products));

Code #3: (Demo)

var_export(
    array_values(
        array_filter(
            $products,
            function($product) use ($exclusions) {
                return !array_filter(
                    array_intersect_key($product, $exclusions),
                    function($value, $key) use ($exclusions) {
                        return in_array($value, $exclusions[$key]);
                    },
                    ARRAY_FILTER_USE_BOTH
                );
            }
        )
    )
);

Code #4: (Demo)

var_export(
    array_values(
        array_filter(
            $products,
            fn($product) => !array_filter(
                array_intersect_key($product, $exclusions),
                fn($value, $key) => in_array($value, $exclusions[$key]),
                ARRAY_FILTER_USE_BOTH
            )
        )
    )
);

Code #1 uses continue 2; to stop the halt the inner loop, avoid storing the current product in the output array, then return to the outer loop to carry on processing the next product.

Code #2 is directly modifying the $products array.  By unsetting products, the array may cease to be an indexed array (the keys may have gaps between integers). If desirable, call array_values() after the loop to re-index the output.

Code #3 is using a functional style.  It is common for language constructs (e.g. foreach()) to outperform functional iterators, so I will assume this snippet (and Code #4) will be slightly slower than the first two.  Furthermore, array_filter() doesn't enjoy the early return that the foreach loops have with break and continue.  In other words, Code #3 & #4 will continue checking against the exclusion array even if a disqualifying condition has already been satisfied for a given product. And if that wasn't enough, I simply find the syntax too convoluted.

Code #4 is the same as Code #3, but is using the slightly shorter "arrow function" syntax which is available from PHP7.4 and up.  This affords the omission of use() and some other characters, but I still find the snippet less intuitive/readable compared to Code #1 & #2.


问:
Check whether certain function is used inside a nested function in R
I want to create a function check_sym that takes another function f as argument and checks whether inside f a specific function is used.

Specifically I want to check if inside f non-standard evaluation in the form of !! sym is used.

I can do this with a simple trick that turns a functions body into a character string and then uses regex to check for "!!sym\\(".

library(dplyr)
library(purrr)
library(rlang)

check_sym <- function(f) {
  f <- as.list(body(f))
  f <- unlist(as.character(f))
  purrr::some(f, function(x) grepl("!!sym\\(", x))
}

foo <- function(df, x) {
  select(df, !! sym(x))
}

check_sym(foo)
#> [1] TRUE
```

<p><sup>Created on 2020-02-16 by the reprex package (v0.3.0)</sup></p>

<p>However, while this is possible, I am looking for a way that does not rely on character strings and regex, but rather ideally some method which looks inside the function and "sees" all function calls at a deeper level, which would be more reliable.</p>

<p>Any ideas appreciated.</p>

<p><strong>Final solution based on accepted answer:</strong></p>

<p>Based on MrFlick's answer below my actual solution is the following:</p>

<p>I define check_syms as:</p>

<pre class="lang-r prettyprint-override"><code>check_sym <- function(f) {
  grepl("!!sym", paste(all.names(body(f)), collapse = ""))
}
</code>```

It correctly identifies functions which make a function call to "!! sym" compared to functions that only call for example paste0("!!sym").

foo <- function(df, x) {
  select(df, !! sym(x))
}

test_f <- function(x) {
  print(paste0("!!sym", x))
}

check_sym(foo)
#> [1] TRUE

check_sym(test_f)
#> [1] FALSE
```

答:
In base R, we can capture the output of body into a vector of strings and use grepl

```<code>check_sym <- function(f)  any(grepl('!!sym(', capture.output(body(f)), fixed = TRUE))

check_sym(foo)
# [1] TRUE

some_fct <- function(x) print("sym")
check_sym(some_fct)
#[1] FALSE
</code>```

Body:
I want to create a function check_sym that takes another function f as argument and checks whether inside f a specific function is used.

Specifically I want to check if inside f non-standard evaluation in the form of !! sym is used.

I can do this with a simple trick that turns a functions body into a character string and then uses regex to check for "!!sym\\(".

library(dplyr)
library(purrr)
library(rlang)

check_sym <- function(f) {
  f <- as.list(body(f))
  f <- unlist(as.character(f))
  purrr::some(f, function(x) grepl("!!sym\\(", x))
}

foo <- function(df, x) {
  select(df, !! sym(x))
}

check_sym(foo)
#> [1] TRUE

Created on 2020-02-16 by the reprex package (v0.3.0)

However, while this is possible, I am looking for a way that does not rely on character strings and regex, but rather ideally some method which looks inside the function and "sees" all function calls at a deeper level, which would be more reliable.

Any ideas appreciated.

Final solution based on accepted answer:

Based on MrFlick's answer below my actual solution is the following:

I define check_syms as:

check_sym <- function(f) {
  grepl("!!sym", paste(all.names(body(f)), collapse = ""))
}

It correctly identifies functions which make a function call to "!! sym" compared to functions that only call for example paste0("!!sym").

foo <- function(df, x) {
  select(df, !! sym(x))
}

test_f <- function(x) {
  print(paste0("!!sym", x))
}

check_sym(foo)
#> [1] TRUE

check_sym(test_f)
#> [1] FALSE

Body:
In base R, we can capture the output of body into a vector of strings and use grepl

check_sym <- function(f)  any(grepl('!!sym(', capture.output(body(f)), fixed = TRUE))

check_sym(foo)
# [1] TRUE

some_fct <- function(x) print("sym")
check_sym(some_fct)
#[1] FALSE


问:
Showing map markers by location in list outside map
I have a number of markers and I want to show the markers in a list outside of the map. How can this be achieved using javascript? I am new to Javascript so help is appreciated. Code I have currently below, this is all working as expected apart from listing the map marker information. </p>

<p>I idea is that a list will appear depending on the option chosen in the dropdown for counties. </p>

```<code>//List of Counties
var counties = [{
    name: "Armagh",
    code: "am",
    zoom : 8,
    center: {
        lat: 54.274911,
        lng: -6.626583
    }
}, {
    name: "Cork",
    code: "c",
    zoom : 8,
    center: {
        lat: 51.904246,
        lng: -8.474038
    }
}];

//List of Practices
var practice = [{
    name: "Cross Veterinary Clinic",
    position: {
        lat: 54.07531,
        lng: -6.60590
    },
    code: "am",
    address: "8 Dundalk Road, Crossmaglen, Co. Armagh",
    vet: "Carol Peterson",
    programme: ['bvd', 'jd']
}, {
    name: "Keltic Veterinary",
    position: {
        lat: 52.35386,
        lng: -8.68204
    },
    code: "c",
    address: "Charleville Town Centre, Bakers Road, Charleville, Co. Cork",
    vet: "Gerald Gonzales",
    programme: ['cck', 'bvd']
}];

var countyselect = document.getElementById('county')
countyselect.addEventListener("change", onCountySelect);

//render map

function initialize() {
    var options = {
        center: {
            lat: 53.2734,
            lng: -7.77832031
        },
        zoom: 6.5
    };
    map = new google.maps.Map(document.getElementById('map'), options);
    marker = renderMarker();

}

function renderMarker() {
    for (var i = 0; i < practice.length; i++) {
        var marker = new google.maps.Marker({
            position: practice[i].position,
            title: practice[i].name,
            map: map,
        });
        inforwindow(marker, map);
    }
}

function inforwindow(marker, map) {
    var infowindow = new google.maps.InfoWindow(); {
        google.maps.event.addListener(marker, 'click', function(renderMarker) {
            infowindow.setContent(marker.getTitle());
            infowindow.open(map, marker);
        });
    }
}

 function onCountySelect() {
    let countySelect = document.getElementById("county");
     let selectedCounty = countySelect.options[countySelect.selectedIndex];
     let countyFound = (counties.find(({ name }) => name === selectedCounty.value));
    if (selectedCounty.value === "all") {
        map.setCenter({ lat: 53.2734, lng: -7.77832031 });
        map.setZoom(6.5);
    } else {
        map.setCenter(countyFound.center);
       map.setZoom(countyFound.zoom);
    }
 }

function resultsList() {
  if (selectedCounty.value === "all") {
  let countySelect = document.write(`<h3>${practice.name}</h3><p>${practice.address}</p><p>${practice.vet}</p>`);

  }
}
</code>```

答:
I'm not sure at all from your code what your plan is with markers, or whether you intend to make items in the list clickable so that they highlight a specific marker on the map. But in any case, here's code to do what you asked - to create a list of relevant practices when a county is selected. I've dropped in some hacky test HTML just as it's easier to test.

Hopefully this will get you on the right path.

A couple of notes - you have used the backtick, ie using ` and ${variable} approach to rendering some content - this may not work on older browsers directly.

Also, please excuse the mix of single and double quotes - that's a matter of taste but I didn't see the point in going back and changing everything you had done. Good luck!

<!doctype html>

    <title>Map Thing</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <select id="county" name="county" value="">
          <option value="">Please choose</option>
          <option value="am">Armagh</option>
          <option value="c">Cork</option>
        </select>

```

Body:
I have a number of markers and I want to show the markers in a list outside of the map. How can this be achieved using javascript? I am new to Javascript so help is appreciated. Code I have currently below, this is all working as expected apart from listing the map marker information.

I idea is that a list will appear depending on the option chosen in the dropdown for counties.

//List of Counties
var counties = [{
    name: "Armagh",
    code: "am",
    zoom : 8,
    center: {
        lat: 54.274911,
        lng: -6.626583
    }
}, {
    name: "Cork",
    code: "c",
    zoom : 8,
    center: {
        lat: 51.904246,
        lng: -8.474038
    }
}];

//List of Practices
var practice = [{
    name: "Cross Veterinary Clinic",
    position: {
        lat: 54.07531,
        lng: -6.60590
    },
    code: "am",
    address: "8 Dundalk Road, Crossmaglen, Co. Armagh",
    vet: "Carol Peterson",
    programme: ['bvd', 'jd']
}, {
    name: "Keltic Veterinary",
    position: {
        lat: 52.35386,
        lng: -8.68204
    },
    code: "c",
    address: "Charleville Town Centre, Bakers Road, Charleville, Co. Cork",
    vet: "Gerald Gonzales",
    programme: ['cck', 'bvd']
}];

var countyselect = document.getElementById('county')
countyselect.addEventListener("change", onCountySelect);

//render map

function initialize() {
    var options = {
        center: {
            lat: 53.2734,
            lng: -7.77832031
        },
        zoom: 6.5
    };
    map = new google.maps.Map(document.getElementById('map'), options);
    marker = renderMarker();

}

function renderMarker() {
    for (var i = 0; i < practice.length; i++) {
        var marker = new google.maps.Marker({
            position: practice[i].position,
            title: practice[i].name,
            map: map,
        });
        inforwindow(marker, map);
    }
}

function inforwindow(marker, map) {
    var infowindow = new google.maps.InfoWindow(); {
        google.maps.event.addListener(marker, 'click', function(renderMarker) {
            infowindow.setContent(marker.getTitle());
            infowindow.open(map, marker);
        });
    }
}

 function onCountySelect() {
    let countySelect = document.getElementById("county");
     let selectedCounty = countySelect.options[countySelect.selectedIndex];
     let countyFound = (counties.find(({ name }) => name === selectedCounty.value));
    if (selectedCounty.value === "all") {
        map.setCenter({ lat: 53.2734, lng: -7.77832031 });
        map.setZoom(6.5);
    } else {
        map.setCenter(countyFound.center);
       map.setZoom(countyFound.zoom);
    }
 }

function resultsList() {
  if (selectedCounty.value === "all") {
  let countySelect = document.write(`<h3>${practice.name}</h3><p>${practice.address}</p><p>${practice.vet}</p>`);

  }
}

Body:
I'm not sure at all from your code what your plan is with markers, or whether you intend to make items in the list clickable so that they highlight a specific marker on the map. But in any case, here's code to do what you asked - to create a list of relevant practices when a county is selected. I've dropped in some hacky test HTML just as it's easier to test.

Hopefully this will get you on the right path.

A couple of notes - you have used the backtick, ie using ` and ${variable} approach to rendering some content - this may not work on older browsers directly.

Also, please excuse the mix of single and double quotes - that's a matter of taste but I didn't see the point in going back and changing everything you had done. Good luck!

<!doctype html>
<html>
  <head>
    <title>Map Thing</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">

      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      html, body {
        font-family: Helvetica;
        min-height: 100vh;
        display: flex;
        flex-direction: column;
      }

      #container {
        flex: 1;
        display: flex;
      }

      #options {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }

      #results {
        margin-top: 40px;
        padding: 40px;
      }

      .result {
        padding: 30px;
        border: 1px solid #ddd;
      }

      #map {
        flex: 3;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="options">
        <select id="county" name="county" value="">
          <option value="">Please choose</option>
          <option value="am">Armagh</option>
          <option value="c">Cork</option>
        </select>

        <div id="results"><!-- will be populated --></div>
      </div>
      <div id="map"></div>
    </div>

    <script>

      //List of Counties
      var counties = [{
        name: "Armagh",
        code: "am",
        zoom : 8,
        center: {
          lat: 54.274911,
          lng: -6.626583
        }
      }, {
        name: "Cork",
        code: "c",
        zoom : 8,
        center: {
          lat: 51.904246,
          lng: -8.474038
        }
      }];

      //List of Practices
      var practices = [{
        name: "Cross Veterinary Clinic",
        position: {
          lat: 54.07531,
          lng: -6.60590
        },
        code: "am",
        address: "8 Dundalk Road, Crossmaglen, Co. Armagh",
        vet: "Carol Peterson",
        programme: ['bvd', 'jd']
    }, {
        name: "Keltic Veterinary",
        position: {
            lat: 52.35386,
            lng: -8.68204
        },
        code: "c",
        address: "Charleville Town Centre, Bakers Road, Charleville, Co. Cork",
        vet: "Gerald Gonzales",
        programme: ['cck', 'bvd']
      }];

      function initialize() {
        var options = {
          center: {
            lat: 53.2734,
            lng: -7.77832031
          },
          zoom: 6.5
        };

        map = new google.maps.Map(document.getElementById('map'), options);

        var countyselect = document.getElementById('county');
        countyselect.addEventListener('change', onCountySelect);

        renderMarkers();
      }

      function renderMarkers() {
        for (var i = 0; i < practices.length; i++) {
          var marker = new google.maps.Marker({
            position: practices[i].position,
            title: practices[i].name,
            map: map,
          });
        }
      }

      function showInfoWindow(marker, map) {
        var infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(marker.getTitle());
          infowindow.open(map, marker);
        });
      }

      function onCountySelect() {
        var countySelect = document.getElementById("county");
        var countiesByCode = counties.map(function(c){
          return c.code;
        });
        var index = countiesByCode.indexOf(countySelect.value)

        if (index > -1) {
          var selectedCounty = counties[index];
          map.setCenter(selectedCounty.center);
          map.setZoom(selectedCounty.zoom);

          renderResultsList(selectedCounty);
        } else {
          map.setCenter({ lat: 53.2734, lng: -7.77832031 });
          map.setZoom(6.5);

          clearResultsList();
        }
      }

      function renderResultsList(selectedCounty) {
        var relevantPractices = practices.filter(function(p){
          return p.code === selectedCounty.code;
        });
        var resultsArea = document.getElementById("results");
        resultsArea.innerHTML = "";

        for(var i = 0; i < relevantPractices.length; i++) {
          var practice = relevantPractices[i];
          var div = document.createElement("div");
          div.className = "result";
          div.innerHTML = `<h3>${practice.name}</h3><p>${practice.address}</p><p>${practice.vet}</p>`;
          resultsArea.appendChild(div);
        }
      }

      function clearResultsList() {
        document.getElementById("results").innerHTML = "";
      }

    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&callback=initialize"
    async defer></script>

  </body>
</html>


问:
Pie chart using only values of a certain group
```<code>Asset Type   Amount  Value

EUR   FIAT   0.43   0.4577449106
USD   FIAT   0  0
SC1   Crypto 190.37 50.64
SC2   Crypto 776.3  14.04
SC3   Crypto 4.9    10.51
SC4   Crypto 70 70.15
SC5   Crypto 155    39.50
SC6   Crypto 680    38.1142304
SC7   Crypto 0.62   15.7643779
SC8   Crypto 50.00  56.25312541
Gold  Resource  10.50   441.665
</code>```

I want to createa a pie chart that ONLY uses the values of type crypto, and not gold or fiat (and others). Is this possible? I didn't find a way without increasing the number of rows, which would not be a nice idea imho, just for a chart to being able to display the data.

The chart should show all crypto assets and their percentage in the overall crypto share. I want to see how much "value" each crypto has from the whole pool, as percentage. So SC1 would be like 20% of the whole portfolio, SC2 only 7%, etc.

I would like to have a pie chart for this.

Here is a visualisation if it is unclear what I try to ask for:

答:
the only way is to filter it out with:

```<code>=FILTER(A:D, B:B="crypto")
</code>```

and then use that for pie chart

Body:
Asset Type   Amount  Value

EUR   FIAT   0.43   0.4577449106
USD   FIAT   0  0
SC1   Crypto 190.37 50.64
SC2   Crypto 776.3  14.04
SC3   Crypto 4.9    10.51
SC4   Crypto 70 70.15
SC5   Crypto 155    39.50
SC6   Crypto 680    38.1142304
SC7   Crypto 0.62   15.7643779
SC8   Crypto 50.00  56.25312541
Gold  Resource  10.50   441.665

I want to createa a pie chart that ONLY uses the values of type crypto, and not gold or fiat (and others). Is this possible? I didn't find a way without increasing the number of rows, which would not be a nice idea imho, just for a chart to being able to display the data.

The chart should show all crypto assets and their percentage in the overall crypto share. I want to see how much "value" each crypto has from the whole pool, as percentage. So SC1 would be like 20% of the whole portfolio, SC2 only 7%, etc.

I would like to have a pie chart for this.

Here is a visualisation if it is unclear what I try to ask for:

Body:
the only way is to filter it out with:

=FILTER(A:D, B:B="crypto")

and then use that for pie chart


问:
Which of these lines is more efficient (CPU/memory-wise) when executed in jQuery?
I have two scenerios. In each scenerio, tell me which version of doing the same exact thing is more efficient (e.g. uses less CPU or memory):

First scenerio:

```<code>/*version 1*/
    $('body').append('#something');
/*version 2*/
    $('#something').insertAfter('body > *:last-child');
</code>```

Second scenerio:

```<code>/*version 1*/
    $('#something').method1();
    $('#something').method2();
    $('#something').method3();
/*version 2*/
    var $reference = $('#something');
    $reference.method1();
    $reference.method2();
    $reference.method3();
</code>```

So in each scenerio, which version is more efficient?

答:
This may not be the answer you're looking for, but...

In the grand scheme of things, the difference is going to be so barely measurable that it doesn't really matter.  Just focus on writing clean, simple and easily maintainable code.

Body:
I have two scenerios. In each scenerio, tell me which version of doing the same exact thing is more efficient (e.g. uses less CPU or memory):

First scenerio:

/*version 1*/
    $('body').append('#something');
/*version 2*/
    $('#something').insertAfter('body > *:last-child');

Second scenerio:

/*version 1*/
    $('#something').method1();
    $('#something').method2();
    $('#something').method3();
/*version 2*/
    var $reference = $('#something');
    $reference.method1();
    $reference.method2();
    $reference.method3();

So in each scenerio, which version is more efficient?


问:
Why adding two numbers from data type less than int is converted to int?
Why is java convert byte or short data type to int when adding two number?

```<code>byte a = 10;
byte b = 20;
byte c = a + b; // Compile Time Error
byte c = (byte) a + b; //Should do typecasting
</code>```

10 + 20 = 30 and byte can hold til 127 so why does it convert to int type?

答:
Tl;dr:
That's just how Java was designed.

Long version:

JVM bytecode is designed to have opcodes of only one byte. This (in theory) keeps bytecode relatively memory efficient. As a result there are only 256 possible opcodes, which significantly limits the number of supported operations. This limitation means tat Java must choose only the most common operations when allocating opcodes.

Additionaly Java bytecode was designed to be compiled to machine code, and on many machines there is no byte addition instruction, and instead all operation have to be done on 32+ bit integers, so it makes little sense to have a bytecode instruction which would have to be compiled to a sequence of byte to integer conversion, followed by addition, followed by integer to byte conversion.

This limitation of the JVM appears to have trickled down into the Java language design resulting in byte addition actually being integer addition, since that is what is supported in JVMs.

Body:
Why is java convert byte or short data type to int when adding two number?

byte a = 10;
byte b = 20;
byte c = a + b; // Compile Time Error
byte c = (byte) a + b; //Should do typecasting

10 + 20 = 30 and byte can hold til 127 so why does it convert to int type?


问:
SonarQube exits with 143
I am trying to Setup SonarQube on Centos 6 VM with 6GB of RAM. The process always exits with 143.

On analysis I found that the JVM is being sent a SIGTERM signal and thus exiting. There are no core dumps and dmesg is also quite unhelpful. I also tried fiddling with the Memory options to no avail.

If some can help me debug this issue it will be quite useful. At least, I will have some idea why this software is being terminated.

```<code>jvm 1    | 2018.03.06 15:32:59 INFO  app[][o.e.p.PluginsService] no modules loaded
jvm 1    | 2018.03.06 15:32:59 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
jvm 1    | 2018.03.06 15:33:07 INFO  app[][o.s.a.SchedulerImpl] Process[es] is up
jvm 1    | 2018.03.06 15:33:07 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='web', ipcIndex=2, logFilenamePrefix=web]] from [/home/sonar/sonar/sonarqube-7.0]: /opt/jdk1.8.0_161/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/home/sonar/sonar/sonarqube-7.0/temp -Xrs -Xmx4g -Xms4g -XX:+HeapDumpOnOutOfMemoryError -cp ./lib/common/*:./lib/server/*:/home/sonar/sonar/sonarqube-7.0/lib/jdbc/mysql/mysql-connector-java-5.1.42.jar org.sonar.server.app.WebServer /home/sonar/sonar/sonarqube-7.0/temp/sq-process3024208901604150849properties
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] Process [web] is stopped
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] Process [es] is stopped
jvm 1    | 2018.03.06 15:33:12 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 143
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
wrapper  | <-- Wrapper Stopped
</code>```

答:
Check in your /opt/sonarqube/conf/sonar.propeties, the following line:

```<code>sonar.jdbc.url=jdbc:postgresql://localhost/your_db_schema
</code>```

For example, if you inster this in PG

```<code>CREATE DATABASE db_sonarqube;
…
…
\q
</code>```

Your line is going to be like this:

```<code>sonar.jdbc.url=jdbc:postgresql://localhost/db_sonarqube
</code>```

Title: SonarQube exits with 143

Body:
I am trying to Setup SonarQube on Centos 6 VM with 6GB of RAM. The process always exits with 143.

On analysis I found that the JVM is being sent a SIGTERM signal and thus exiting. There are no core dumps and dmesg is also quite unhelpful. I also tried fiddling with the Memory options to no avail.

If some can help me debug this issue it will be quite useful. At least, I will have some idea why this software is being terminated.

jvm 1    | 2018.03.06 15:32:59 INFO  app[][o.e.p.PluginsService] no modules loaded
jvm 1    | 2018.03.06 15:32:59 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
jvm 1    | 2018.03.06 15:33:07 INFO  app[][o.s.a.SchedulerImpl] Process[es] is up
jvm 1    | 2018.03.06 15:33:07 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='web', ipcIndex=2, logFilenamePrefix=web]] from [/home/sonar/sonar/sonarqube-7.0]: /opt/jdk1.8.0_161/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/home/sonar/sonar/sonarqube-7.0/temp -Xrs -Xmx4g -Xms4g -XX:+HeapDumpOnOutOfMemoryError -cp ./lib/common/*:./lib/server/*:/home/sonar/sonar/sonarqube-7.0/lib/jdbc/mysql/mysql-connector-java-5.1.42.jar org.sonar.server.app.WebServer /home/sonar/sonar/sonarqube-7.0/temp/sq-process3024208901604150849properties
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] Process [web] is stopped
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] Process [es] is stopped
jvm 1    | 2018.03.06 15:33:12 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 143
jvm 1    | 2018.03.06 15:33:12 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
wrapper  | <-- Wrapper Stopped

Body:
Check in your /opt/sonarqube/conf/sonar.propeties, the following line:

sonar.jdbc.url=jdbc:postgresql://localhost/your_db_schema

For example, if you inster this in PG

CREATE DATABASE db_sonarqube;
…
…
\q

Your line is going to be like this:

sonar.jdbc.url=jdbc:postgresql://localhost/db_sonarqube


问:
in php, what is the purpose of using concatenation operator (.) for adding values to an array?
I am relatively new to php and was following a tutorial where there was a code to add values to array like this:

```<code>$errors = array();
$errors[] .= 'You must enter a value';
</code>```

So I am confused about the above code.

I know that i can declare and add values to array like below.

```<code>$myarr = array();
$myarr[]= "aa";
$myarr[]= "bb";

print_r($myarr);
</code>```

Also, I can append strings by using string concatenation operator (.) like below:

```<code>$str = "val1"."val2";
</code>```

But what's the point of putting concatenation operator (.) before adding a value to an array?

答:
In this particular case there is no point in using the concatenation operator. The left hand side of the expression, $errors[] creates a new, empty, element in the $errors array, so concatenating something to it has the same effect as assigning to it. Indeed if you try the following code with and without the concatenation operator, you'll see the results are the same:

```<code>$errors = array();
$errors[] .= 'You must enter a value';
print_r($errors);

$errors = array();
$errors[] = 'You must enter a value';
print_r($errors);
</code>```

Output:

```<code>Array
(
    [0] => You must enter a value
)
Array
(
    [0] => You must enter a value
)
</code>```

Body:
I am relatively new to php and was following a tutorial where there was a code to add values to array like this:

$errors = array();
$errors[] .= 'You must enter a value';

So I am confused about the above code.

I know that i can declare and add values to array like below.

$myarr = array();
$myarr[]= "aa";
$myarr[]= "bb";

print_r($myarr);

Also, I can append strings by using string concatenation operator (.) like below:

$str = "val1"."val2";

But what's the point of putting concatenation operator (.) before adding a value to an array?

Body:
In this particular case there is no point in using the concatenation operator. The left hand side of the expression, $errors[] creates a new, empty, element in the $errors array, so concatenating something to it has the same effect as assigning to it. Indeed if you try the following code with and without the concatenation operator, you'll see the results are the same:

$errors = array();
$errors[] .= 'You must enter a value';
print_r($errors);

$errors = array();
$errors[] = 'You must enter a value';
print_r($errors);

Output:

Array
(
    [0] => You must enter a value
)
Array
(
    [0] => You must enter a value
)


问:
SQL - Need help filtering results based on rows
I have a table that looks like this:

```<code>p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1
</code>```

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

答:
```<code>SELECT p_id
  FROM table
 WHERE comp_id in (1,2)
 GROUP BY p_id
HAVING COUNT(DISTINCT comp_id) = 2
</code>```

or

assumig #t is the following table (the comp_id's you're searching for):

```<code>comp_id
-------
      1
      2

SELECT t1.p_id
  FROM table t1
 WHERE NOT EXITS (SELECT NULL
                    FROM table t2
              RIGHT JOIN #t
                      ON t2.p_id    = t1.p_id
                     AND t2.comp_id = #t.comp_id
                   WHERE t2.comp_id IS NULL)
</code>```

Body:
I have a table that looks like this:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

Body:
SELECT p_id
  FROM table
 WHERE comp_id in (1,2)
 GROUP BY p_id
HAVING COUNT(DISTINCT comp_id) = 2

or

assumig #t is the following table (the comp_id's you're searching for):

comp_id
-------
      1
      2

SELECT t1.p_id
  FROM table t1
 WHERE NOT EXITS (SELECT NULL
                    FROM table t2
              RIGHT JOIN #t
                      ON t2.p_id    = t1.p_id
                     AND t2.comp_id = #t.comp_id
                   WHERE t2.comp_id IS NULL)


问:
Chaining lambda functions vs. Making program async
I have an AWS Lambda function written in python that is starting to get a bit too big. It often runs over the AWS Lambda limit of 15 minutes.

The function is responsible for making loads of API calls, and unfortunately I have not taken the time to make them all async yet.

The workflow for the function looks something roughly like this:

Receive data for xxx clients (1 api call)

Place API call for each client and wait for response (xxx api calls)

Based on #2 API call response, place yet another API call for each client and wait for response (xxx api calls)

Store response from #3 in DynamoDB (xxx DB updates)

Initially my plan was to just keep everything in 1 lambda function, and modify my code such that all API calls run async, and to do one big dynamoDB batch update at the end.

However, it occurs to me that theoretically this function could still grow too large in the future, if we start needing to run it for enormous numbers of clients. Additionally, in my opinion, managing all those python async calls can be a bit cumbersome in specific situations.

My second approach, is to chain together lambda functions. That is, create a second lambda function, let's name it "order_for_single_client", which perform steps #2-4 for just one client.

The top level lambda function will gather data on all clients, and for each one, make a separate lambda call to "order_for_single_client". So, if we need to order for 500 clients, the top level function will just make 500 separate lambda calls. Naturally, all the async behavior should take care of itself on the end of AWS since it will run the lambda functions in parallel. (with the exception of the batch dynamoDB update we wanted, but we can worry about that later).

What is the preferred way of handling this situation from an architecture perspective? Splitting things up into a lambda chain, or trying to speed things up using async inside a single lambda function?

If we were to implement the lambda chain, will it be more or less expensive to run at scale compared to the single function async approach?

Is there a third design solution to this problem that I have not considered? (Apart from spinning up an EC2 instance, which I would prefer not to do).

答: This is a perfect case for Step Functions. </p>


问:
Python - Array of Indexes of all appearances of a certain element in an array
This question is very similar to this question, Question, except for the fact that I need an answer for Python.

I'll explain the question anyway. If I have an array of characters, for example ["a", "b", "a", "c"], then it needs to return an array that includes the indexes of all the appearances of a certain character.

This means that if I input ['a', 'b', 'a', 'c', 'c', 'a'], and I need to find all appearances of 'a', then it would output [0, 2, 5].

I also need the program to be pretty fast, as I need to mass generate my final product, so the whole program needs to be quick. I will probably be running this piece of code millions of times in my code so the quicker it is the better, but I am accepting anything right now.

Right now my code does not work since it simply output [0, 0, 0] (I am running through a for loop so it isn't fast either)

Could someone please help? Thanks!

答:
You can use a defaultdict to default the index locations of each character to a list, then just enumerate over your list and append the index locations.  This allows you to later index the location of any character in the list.

```<code>from collections import defaultdict

my_list = ['a', 'b', 'a', 'c', 'c', 'a']

dd = defaultdict(list)
for n, c in enumerate(my_list):
    dd[c].append(n)

>>> dd['a']
[0, 2, 5]

>>> dict(dd)
{'a': [0, 2, 5], 'b': [1], 'c': [3, 4]}
</code>```

Body:
You can use a defaultdict to default the index locations of each character to a list, then just enumerate over your list and append the index locations.  This allows you to later index the location of any character in the list.

from collections import defaultdict

my_list = ['a', 'b', 'a', 'c', 'c', 'a']

dd = defaultdict(list)
for n, c in enumerate(my_list):
    dd[c].append(n)

>>> dd['a']
[0, 2, 5]

>>> dict(dd)
{'a': [0, 2, 5], 'b': [1], 'c': [3, 4]}


问:
How can I convert a regular WAV file to a 4bit WAV file using ffmpeg?
I have tried something along the lines of

C:\ffmpeg\ffmpeg -i "Blip_Select2.wav" -c:a wav -sample_fmt u8 "Blip_Select2_8bit.wav"

but I cannot figure out how to access a 4bit conversion.

I am using the audio for a c# project, 4 bit is sufficient and I prefer wav so I won't have to distribute a possibly restricted usage decoder with my files.

答:
Just a heads up that -b 4 with sox seems to use MS ADPCM codec which encodes the difference between samples using 4 bits. If you want to produce a similar result using ffmpeg you can use:

ffmpeg -i sound.wav -codec:a adpcm_ms -f wav sound_4bit.wav
```


问:
how to write and print some constraints in python?
I need to generate some constraints for an optimization problem. Its a little frustrating to make them by hand. could anybody help me to do that in python?

1-first I need to generate these 7 vectors: V_1,V_2,...,V_7

for m=0 to 6 do the following:

```<code>V_m=(1,cos(2mpi/7),cos(2*2mpi/7),cos(2*3mpi/7),cos(2*4mpi/7),cos(2*5mpi/7),cos(2*6mpi/7))
</code>```

Then I need the dot product of V_m m=0,...,6 with U=(x1,x7,x12,x16,x19,x21,x6).

For example for m=3:

```<code>A3= 1*x1+cos(2mpi/7)*x7+cos(2*2mpi/7)*x12+cos(2*3mpi/7)*x16+cos(2*4mpi/7)*x19+cos(2*5mpi/7)*x21+cos(2*6mpi/7)*x6;
</code>```

答:
Here's a basic version using lists to store the variables. Hopefully it's fairly self-explanatory

import math
V = []

for m in range(7): # 0,1,...6
    V_m = [1]
    for i in range(1,7): # 1,2,...,6
        V_m.append(math.cos(2*i*m*math.pi / 7))
    V.append(V_m)

U = ['x1','x7','x12','x16','x19','x21','x6']

for i in range(7):
    # zip iterates through both lists at the same time
    # a=V_m[0] b=x1, then a=V_m[1] b=x7, et c.
    print(' + '.join([str(a)+'*'+ b for a,b in zip(V[i], U)]))
```

Body:
I need to generate some constraints for an optimization problem. Its a little frustrating to make them by hand. could anybody help me to do that in python?

1-first I need to generate these 7 vectors: V_1,V_2,...,V_7

for m=0 to 6 do the following:

V_m=(1,cos(2mpi/7),cos(2*2mpi/7),cos(2*3mpi/7),cos(2*4mpi/7),cos(2*5mpi/7),cos(2*6mpi/7))

Then I need the dot product of V_m m=0,...,6 with U=(x1,x7,x12,x16,x19,x21,x6).

For example for m=3:

A3= 1*x1+cos(2mpi/7)*x7+cos(2*2mpi/7)*x12+cos(2*3mpi/7)*x16+cos(2*4mpi/7)*x19+cos(2*5mpi/7)*x21+cos(2*6mpi/7)*x6;