text:
Q: PHP gets commented out by the browser I have created a contact.php file with a standard html form but used PHP to retrieve the information entered and to create the email.
The page currently works on one of my websites but when I've copied the file and not changed anything on it but the browser comments it out.
I've looked online for some way around this but all I could find is saying its a problem with the server, both the website are on the same server so that is not the problem.
I've tried putting add handler into my htaccess file as recommended by some people and this has had no effect.
Any help would be appreciated.
Heres My code
$ToEmail = 'email@hotmail.co.uk';
$EmailSubject = 'Website Enquiry ';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html;";
$MESSAGE_BODY = "Name:
".$_POST["yourname"]."
";
$MESSAGE_BODY .= "Email:
 ".$_POST["email"]."
";
$MESSAGE_BODY .= "Phone Number:
 ".$_POST["Telephone-Number"]."
";
$heard = $_POST['heard'];
foreach($_POST['heard'] as $value) {
$heard_msg .= "$value, ";
}
$MESSAGE_BODY .= "How they heard about us:
 ".$heard_msg."
";
$MESSAGE_BODY .= "Enquiry:
 ".nl2br($_POST["Message"])."
";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
echo '
Thanks for you Enquiry
';
echo '
Please carry on browsing our site
';
echo ' Return to home page';

All inside a php if statement starting with 'php'

A: Browsers shouldn't comment out PHP, they shouldn't even see PHP.
Most likely, what you are experiencing is that the <? is not being parsed by the PHP engine and being delivered to the browser. The browser is then treating it as an unknown tag and ignoring it.
The solutions are:

*

*Don't use short tags as they are not turned on for all PHP installations. If you have <? some code change it to <?php some code.

*Make sure you are trying to run your PHP on a server that supports PHP.

A: Your hosting server probably doesn't support PHP, this is why it is interpreted as comments.
Take a look at your package and see if it should support it.


text:
Q: Distance of edges from each other Consider the following code:
\begin{tikzpicture}[node distance=4cm]
    \node[state,initial, initial text=O] (q0) {$q_0$};
    \node[state,right=3cm of q0] (q1) {$q_1$};
    \node[state,right=3cm of q1] (q2) {$q_2$};
    \node[state,right=3cm of q2] (q3) {$q_3$};
    \draw (q0) edge[bend left] node{true} (q3);
    \draw (q0) edge[bend left=2cm] node{false} (q3);
    \draw (q0) edge[bend left=4cm] node{predicate} (q3);
\begin{tikzpicture}[node distance=4cm]

This is the result:

I thought that adding values to bend left may make these edges more apart from each other. But it doesn't. How can I resolve that ?

A: I just copied and pasted your code snippet so no tikzset are taken in account. Next time, please include a complete minimal working example (MWE) in your question.
In the following you can see two different options, one with bend and looseness, and one with out=<>,in=<> and looseness.
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{automata,positioning}

\begin{document}

\begin{tikzpicture}[node distance=4cm]
    \node[state,initial, initial text=O] (q0) {$q_0$};
    \node[state,right=3cm of q0] (q1) {$q_1$};
    \node[state,right=3cm of q1] (q2) {$q_2$};
    \node[state,right=3cm of q2] (q3) {$q_3$};
    \draw (q0) edge[bend left] node[above]{true} (q3);
    \draw (q0) edge[bend left=2cm,looseness=1] node[above]{false} (q3);
    \draw (q0) edge[out=90,in=90,looseness=1.5] node[above]{predicate} (q3);
\end{tikzpicture}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass arguments to Python script in Alfred Workflows I am trying to pass the {query} parameter to my python script (python newbie) so I can create a really simply calculation.
Heres what the workflow looks like:

My python script looks like this:
query="{query}"

x = float(query)/60

y = x*100

print "%.2f" % x, "%.2f" % y

However when I run it my debug returns this error:
[2018-10-13 21:56:25][ERROR: action.script]
Traceback (most recent call last):
  File "/Users/Imran/Library/Caches/com.runningwithcrayons.Alfred-3/Workflow Scripts/A4A451B6-E747-4D1C-A957-431E755787A5", line 3, in <module>
    x = float(query)/60
ValueError: could not convert string to float: {query}

How can I resolve this? I want to be able to run bill 30 to return a percentage calculation for me.

A: In addition to the language you have two options in your Run Script object: with input as argv and with input as {query}.
If you have the first option selected your code should be this:
import sys

query = sys.argv[1]

x = float(query)/60

y = x*100

print "%.2f" % x, "%.2f" % y

In the second case your code should be this:
import sys

query = "{query}"

x = float(query)/60

y = x*100

print "%.2f" % x, "%.2f" % y


text:
Q: Excel / VBscript: Need to sort columns with a header I have a vbsctipt that opens an Excel(2007) document copies the used range from two sheets (minus the header on sheet 2) puts it all on 3rd sheet. I then need to sort that data using the header. I have the values of the range I need to sort in a vairable already. I just don't know the sytax to get Excel to sort it based on the data in Column A.

A: See if this is what you're looking for.
http://www.tek-tips.com/viewthread.cfm?qid=1243616&page=1


text:
Q: R: How to select not continous rows? How can I select several not continuous rows ?
If I wanted to select rows 1 to 7 I'll write
mydata[,1:7]
But what if I need to select rows 1 to 5 and 10 to 15?

A: Briefly:

*

*Your example is wrong, you selected columns. You meant mydata[1:7,]

*The generalisation is easy: change the indexing expression as in mydata[ c(1:5, 10:15), ]
You may want to acquaint yourself with the An Introduction to R manual that came with your R installation to learn more about indexing.

A: mydata[:,range(1,6)+range(10,16)]. In python a suppose.


text:
Q: What are Objective Business Reasons to Prefer SQL Server 2012 over 2008 R2? My company is facing the decision whether to purchase SQL Server 2012 Denali or SQL Server 2008 R2 for a new database server. I am looking for objective reasons to choose one over the other.
Our requirements:

*

*Standard edition (for financial reasons and a lack of need for enterprise features)

*OLTP workload (this means we don't need the new windowing functions and column store indexes)

*Database size of 10-100 GB

*No business intelligence features needed. Only the relational engine is required

*Synchronous Database Mirroring

Currently, the following reasons are known to me:
SQL Server 2012 Denali

*

*Newest version available

SQL Server 2008 R2

*

*Proven technology

I can't seem to find a lot of technical reasons to prefer one over the other. Basically, it comes down to choosing proven technology that is running successfully vs. the newest and greatest version available.
What are objective reasons to make the decision?

A: Everybody's excited about AlwaysOn and ColumnStore, but many of the benefits of SQL Server 2012 are not exclusive to high-end editions. I don't want to sound like a spokesperson, but I've given plenty of presentations on SQL Server 2012 and I think it has a lot to offer at whatever edition suits you.

*

*Partially Contained Databases which allow you to move databases between servers or environments with a few less shackles (namely server-level logins and server collation dependencies - future versions will handle thornier items like linked servers and Agent jobs).

*Management Studio is now a much better tool, aligned with Visual Studio. IntelliSense is better and a whole bunch of other features make editing easier. Now of course you can have 2008 R2 on your server and use the 2012 version of SSMS, but I'm not sure how that works licensing-wise, and some shops don't want mixed versions (I prefer having the most recent tools on my workstation even to manage downlevel servers). I blogged about the changes early on, when there were still bugs, so please ignore the negatives since most or all are fixed as of RTM. I shudder now when I have to use an earlier version of SSMS.

*Metadata enhancements allow you to inspect resultsets of objects and ad hoc queries, and also allow you to better shape the output of queries.

*Custom Server Roles allow you to define a much more granular set of permissions for users at a role level instead of granting/revoking one by one, or just giving in to complexity and giving them sysadmin.

*FileTable lets you manage a folder like a table of documents, but still have external control over the contents (so imagine being able to do this with T-SQL, and imagine how hard it would be to do in cmd or PowerShell: UPDATE C:\Docs\*.* SET ReadOnly = 1 WHERE Author = 'Bob' AND Created < '20100101';)... think FileStream meets WinFS and gets some usability to boot.

*T-SQL Enhancements allow you to do many things that were a pain in previous versions:

*

*THROW (think of it as re-raise)

*OFFSET / FETCH (simpler, ANSI-standard paging - also see this post)

*SEQUENCE (centralized IDENTITY mechanism, like in Oracle)

*Windowing/Framing enhancements (various things here, such as awesome running totals performance)

*IIF() / CHOOSE() / CONCAT() / EOMONTH()

*Date/Time Constructors (e.g. DATEFROMPARTS) similar to DateSerial in VB

*PARSE() / FORMAT() - like their .NET counterparts (but see this post about the latter)

*TRY_CONVERT() / TRY_PARSE() - return NULL if CONVERT / PARSE fail

*Extended Events has an enhanced UI for configuration / viewing, and finally completely covers trace / audit functionality (including much better causality tracking).

*Lots of new DMVs, system procedures and ShowPlan enhancements for diagnostics and performance troubleshooting. Also take a look at what CSS is calling "The Black Box Recorder."

*Server Core allows you to run on a bare-minimum server without all the UI components (smaller surface area means it is more secure, and reduced maintenance since less parts of OS are subject to Windows Update).

*Full-Text Search gets some important underlying performance enhancements, as well as semantic search (think keywords) and customizable proximity / NEAR.

*AWE is no longer supported, meaning your SQL Server instance on x86 with 32GB of RAM is only going to be able to use 4GB - so you will finally have motivation to get off your old 32-bit hardware.

A: When you are buying new the choice is far different than when you are considering upgrading. Buying new it is my belief that you should always buy the newest version you can get. 2008 version will be no longer supported far earlier than the 2012 version. Better to start new with the lastest as you will be using this backend for a long time.
As to the need to the first service pack, it will be out before you know it and since you are doing new development, the problems it fixes will likely not affect you as much a legacy database with millions of records would face.
Now if you are just getting a new server but putting an old database on it, then the question becomes what are you upgrading from? If the database is already a 2008 database, it will be significantly less risky to use the same version. If you are upgrading, check to see if you can upgrade directly to 2012 from your version.

A: The following is just a few examples regarding "actual evidence for or against reliability in the first version of any new release", as requested. This is not meant to be a complete analysis, but rather a suggestion on what you might want to research.
You can google up "List of issues that are fixed by SQL Server 2008 Service Pack 1" and "List of issues that are fixed by SQL Server 2008 Service Pack 3" on MSDN website. Compare the number and severity of issues in both lists. IMO the first list is longer, and it has more items that could ruin my day, such as:

*

*Error message when you connect to a named instance of SQL Server on a client computer that is running Windows Vista or Windows Server 2008

*The Log Reader Agent skips some transactions when the Log Reader Agent runs to replicate transactions

*Error message when you run a query that involves an outer join operation in SQL Server 2008

*Error message when you perform an update or a delete operation on a table that does not have a clustered index created in SQL Server 2008

*A query that uses parameters and the RECOMPILE option returns incorrect results when you run the query in multiple connections concurrently in SQL Server 2008

Let us drill down one more level and consider just one command, the MERGE. It was released as part of SQL 2008 with several problems, described in the following links:

*

*An Interesting MERGE Bug,

*SQL Server 2008 RTM MERGE Bug and Fix,

*MERGE bug when Foreign Key constraint is created on non-clustered index (2008RTM),

*MERGE statement bug when INSERT/DELETE used and filtered index,

*MERGE query plans allow FK and CHECK constraint violations,

*MERGE statement bypasses Referential Integrity,

*Parameterized DELETE and MERGE Allow Foreign Key Constraint Violations.

As such, at the time of the original release of SQL 2008, I decided against using MERGE. I am using MERGE a lot now, on 2008 R2, and I think it is a really great feature.
Edit: here is the list of defects in SQL 2012 that were recently fixed. Hope it helps.
Another edit: I have chosen MERGE for more detailed analysis, because it is a very important improvement. In fact, it is a major step in catching up with Oracle, and it does improve our productivity. As such, MERGE has been marketed a lot at the time of SQL 2008 release. Yet it was not completely ready to use in serious production systems when it was originally released, and there was no easy way to know it from the presentations/articles/blog posts and such.
Similarly, snapshot isolation is an awesome new feature which just works, but invoking scalar UDFs in CHECK constraints does not work in all cases and as such should not be used in production when we need data integrity. However, both new features were recommended in "What is new in SQL xxxx" presentations, as well as in books, articles etc, and with similar enthusiasm.
We need to be very careful with new features - not all of them are going to be useful/reliable/performant.

A: One point that hasn't been mentioned here is completely irrelevant to the feature set.  If you're doing a new build you can put off a database upgrade for quite a bit longer, so this will save in migration costs.
For a greenfield project you have some breathing space to work around bugs and raise them with the vendor if they do turn up, so it's not a completely uncontrolled process.  I was involved in one of the first data warehouse projects on SQL Server 2005 just as it went to RTM and we got away with it.
If the feature set of 2008R2 will do what you want then the decision is down to some risk of bugs/workarounds vs. the value of postponing the necessity to upgrade and saving an upgrade cycle.


text:
Q: Cloud authentication with AD synced users We currently use an AAD instance with Federated user sign (via ADFS) and password sync enabled on AD Connect to sync the AD and AAD user accounts. The login on the portal redirects to the ADFS sts and correctly authenticates the directory users with the AD passwords.
Trying to achieve resource owner grant against the AAD instance for a client app registered on Azure using the token endpoint which results in a password error (despite using correct user password)

error_description":"AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password

POST to https://login.microsoftonline.com/<domain>/oauth2/token
client_id={registered app id on azure}
&client_secret={secret}
&scope=code
&username={AD user}
&password={AD password}
&grant_type=password
resource=https%3A%2F%2Fgraph.microsoft.com%2F

Try change the password on the Azure portal and the token authentication succeeds up until the time the password is synced again from AD (password write back is enabled); indicating the sync interfering with the password in a way so as to fail cloud authentication on AAD. Are there any considerations needed on the password sync for the AAD cloud authentication to be effective?

A:
We currently use an AAD instance with Federated user sign (via ADFS) and password sync enabled on AD Connect to sync the AD and AAD user accounts. The login on the portal redirects to the ADFS sts and correctly authenticates the directory users with the AD passwords.

Resource Owner Password Grant flow does not work well for federated users.
It only really works for cloud-only users with no MFA and with a non-expired password.


text:
Q: How to disable a set of input methods (languages) on win 10 I use different app in different language (English and Hungarian) So I enabled English and Hungarian input languages, and keyboard-layouts. Alt + Shift and Ctrl + Shift can change between these input styles.
But I don't want to use the English input language with Hungarian keyboard. (The selected in the image below.)

I want to disable this option permanently. How can it be done?
I want to use the same keyboard layout than the input language.
(I don't know what the aim of using different layout than the input language.)
(My problem is that sometime windows switches to this unwanted option ((because windows)) and I type several unwanted character (because of the wrong layout) and I despairingly switching between input languages and keyboards pressing Alt + Shift and Ctrl + Shift several times which is extremely annoying.)

A: I find the solution:
Go Settings -> Time & language -> Region & language
Click on an language from the list at the bottom of the window. Click Options then add or remove Keyboards.


text:
Q: There is few rules and regulations.
Is it a grammatically correct sentence? There is few rules and regulations.
Is it a grammatically correct sentence? I mean whether it be IS or ARE

A: As @Varun Nair says in the comment, it should be

There are a few rules and regulations.

"A few rules and regulations" is plural, so you have to use "are".
You should also say a few rather than few in this context, probably. "A few" means "a number of" or "some." "Few" by itself means "not many." I assume the former is what you mean, unless your goal is to point out how small the number of rules and regulations is.


text:
Q: Deep Learning an Imbalanced data set I have two data sets that looks like this:
DATASET 1
Training (Class 0: 8982, Class 1: 380)
Testing (Class 0: 574, Class 1: 12)

DATASET 2
Training (Class 0: 8982, Class 1: 380)
Testing (Class 0: 574, Class 1: 8)

I am trying to build a deep feedforward neural net in Tensorflow. I get accuracies in the 90s and AUC scores in the 80s. Of course, the data set is heavily imbalanced so those metrics are useless. My emphasis is on getting a good recall value and I do not want to oversample the Class 1. I have toyed with the complexity of the model to no avail, the best model predicted only 25% of the positive class correctly.
My question is, considering the distribution of these data sets, is it a futile move to build models without getting more data(I can't get more data) or there's a way around getting to work with data that is this much imbalanced.
Thanks!

A: Question
Can I use tensorflow to learn imbalance classification with a ratio of about 30:1
Answer
Yes, and I have.  Specifically Tensorflow provides the ability to feed in a weight matrix.  Look at tf.losses.sigmoid_cross_entropy, there is a weights parameter.  You can feed in a matrix that matches Y in shape and for each value of Y provide the relative weight that training example should have.
One way to find the correct weights is to start different balances and run your training and then look at your confusion matrix and a run down of precision vs accuracy for each class.  Once you get both classes to have about the same precision to accuracy ratio then they are balanced.
Example Implementation
Here is an example implementation that converts a Y into a weight matrix that has performed very well for me
def weightMatrix( matrix , most=0.9 ) :
    b = np.maximum( np.minimum( most , matrix.mean(0) ) , 1. - most )
    a = 1./( b * 2. )
    weights = a * ( matrix + ( 1 - matrix ) * b / ( 1 - b ) )
    return weights

The most parameter represents the largest fractional difference to consider.  0.9 equates to  .1:.9 = 1:9 , where as .5 equates to 1:1.  Values below .5 don't work.

A: You might be interested to have a look at this question and its answer. Its scope is a priori more restricted than yours, as it addresses specifically weights for classification, but it seems very relevant to your case.
Also, AUC is definitely not irrelevant: it is actually independent of your data imbalance.


text:
Q: How to stop specific amount of threads I would like to stop/kill N thread when I receive a socket event.
I don't find any way to do that with my current app structure.
Here is the code to start threads :
for i in range(news_viewers):
    t = threading.Thread(target=bot, args=(i + 1,))
    t.daemon = True
    t.name = "Viewer"
    t.start()

When I receive the event I would like to kill/stop N thread named Viewer on my list :
for i in range(number_of_threads_to_kill):
    #number_of_threads_to_kill is received by sockerIO
    for t in threading.enumerate():
        if 'Viewer' in t.getName():
            #I NEED TO CLOSE N THREAD HERE
            print('CLOSE THIS THREAD')

I can't find a way to do it, I tried many things but none of them worked.
threading.enumerate() return this :
.., <Thread(Viewer, started daemon 41868)>, <Thread(Viewer, started daemon 53872)>, <Thread(Viewer, started daemon 54748)>, <Thread(Viewer, started daemon 50028)>,...

Can someone help me to setup that ?

A: I finally found a way to close thread.
When I start a thread I add the id of the thread in threads_ids array  :
global stop_ids, threads_ids
for i in range(news_viewers):
    tid = random.randint(1, 1000)
    threads_ids.append(tid)
    t = threading.Thread(target=bot, args=(tid,))
    t.daemon = True
    t.name = "Viewer"
    t.start()

When I want to close a Thread I add the N first id on stop_ids array :
global stop_ids, threads_ids
n = threads_ids[:number_of_thread_to_close]
stop_ids = stop_ids + n

On my bot function I check every N second if the id of the current thread is on stop_ids :
def bot(id):
    global stop_ids
    ...
    q = True
    while q:
        if id in stop_ids:
            stop_ids.remove(id)
            driver.quit()
            q = False
            break
    ...


text:
Q: (React-table) Bold font for only the first row with a set condition that is true I am working with react-table, and I wanted to bold only the first row which has the word('test') in it (next rows which have the word 'test' won't be bolded, after the first one is bolded)

 const makeCellBold = (value: {} | null | undefined, original: any) => {
   return <Typography fontWeight={original.DummyTestString.includes('test') ? '500'
: 'inherit'}>{value}</Typography>;
 };

 return [
    {
      Header: 'header1',
      accessor: 'accessor1',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },
    {
      id: 'row',
      Header: 'header2',
      accessor: 'accessor2',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },

 {
      id: 'row',
      Header: 'header3',
      accessor: 'accessor3',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },

]

I tried to add a counter or a boolean value which get triggered after the first bolded row, but it did not work (either none of the rows get bolded, or all rows with 'test' in them get bolded, and that's not what I want


text:
Q: Get low stock from a C# dll database which generate million rows automatically I have database (C#, dll) which contains only one table, generates million rows automatically.
I can only get one row at once. The table's columns are : int ItemID, string category, string model, string Brand).
Two items are same if they have same category, brand, model). I want to find out all types of items that are low in stock, where low is that  there are two or less items of that type left.
This is the code I wrote for this, but it took 2 or 3 hours to execute, it is not give me correct results. How can I solve this?
   public DataTable getLowStock()
   {
       DataTable dt = new DataTable();
       object[,] arr=new object[1000000,4];
       int  index=0;
       int rows;
       rows = db.NumRows;
       int[] IdArray;
       IdArray = db.GetItemIDList(0, rows - 1);

       string Category, Brand, Model, Condition, Location, Notes;
       DateTime ReceivedDate, LastUpdated;
       int Weight;
       double PurchasePrice, SellingPrice;

       for (int a = 0; a < IdArray.Length; a++)
       {
           Console.WriteLine(a);

           db.GetItemRecord(IdArray[a], out Category, out Brand, out Model,
                            out ReceivedDate, out Weight, out Condition, out Location,
                            out PurchasePrice, out SellingPrice, out Notes, out LastUpdated);

           if (a == 0)
           {
               arr[0, 0] = Category;
               arr[0, 1] = Brand;
               arr[0, 2] = Model;
               arr[0, 3] =  1;
               index++;

           }
           else
           {

               for (int i = 0; i < index; i++)
               {

                   if ( ( arr[i,2].ToString()==Model)&& (arr[i,1].ToString()==Brand) &&   (arr[i,0].ToString()==Category ) )
                   {

                       arr[i, 3] = (Int32)arr[i, 3] + 1;
                   }
               }

               arr[index,0]=Category;
               arr[index,1]=Brand;
               arr[index,2]=Model;
               arr[index, 3] = 1;

               index++;
           }

       }

        dt.Columns.Add("Category", typeof(string));
        dt.Columns.Add("Model", typeof(string));
        dt.Columns.Add("Brand", typeof(string));
        dt.Columns.Add("count", typeof(int));

        for (int i = 0; i < index; i++) {
           Console.WriteLine("i="+i);

       if((int)arr[i,3]<3){
           dt.Rows.Add(arr[i,0].ToString(),arr[i,2].ToString(),arr[i,1].ToString(),(int)arr[i,3]);
       }
       }
       return dt;
   }

A: Surely the best way to do this is with an actual database? Then you can do the query in SQL, which will execute about 1000 times faster than querying an in-memory datatable.

A: Instead of fetching the whole table I suggest you execute a sql aggregation and fetch only the aggregates:
SELECT category, model, brand, COUNT(*)
FROM table
GROUP BY category, model, brand
HAVING COUNT(*) >= 2

Then, your code is very slow for several reasons, but the main one is that it is quadratic.
So 1 million squared makes one thousand billion operations, which is quite slow.
If you must do the aggregation yourself you have to use a fitting container, like a set or a hash table, not an array. This way you will perform in O(n) (with a good hash table)  or O(n log n) ( with a set), instead of 0(n^2).


text:
Q: Join two select statement from one table i have a table named attendance with 2 attributes (id, remarks). i want to display the tally of absence or late per id from the attendance table.
Attendance Table
|ID         | Remarks       |
=============================
|1          | Absent        |
|1          | Late          |
|2          | Absent        |
|2          | Absent        |
|3          | Late          |

Sample Output
|ID         | Absent   | Late    |
==================================
|1          | 1        | 1       |
|2          | 2        |         |
|3          |          | 1       |

currently, i can only output 2 columns, (ID and Absent) or (ID and Late) using this code:
SELECT id, count(remarks) AS Absent
FROM attendance
WHERE remarks = 'Absent'
GROUP BY id;

i can't display absent and late column simultaneously.. please help. thanks.

A: This is basically a PIVOT. If you do not have access to a PIVOT function then, you can replicate it with an aggregate function and a CASE statement:
select id,
  sum(case when remarks = 'Absent' then 1 else 0 end) Absent,
  sum(case when remarks = 'Late' then 1 else 0 end) Late
from attendance
group by id

See SQL Fiddle with Demo
Or you can use COUNT():
select id,
  count(case when remarks = 'Absent' then 1 else null end) Absent,
  count(case when remarks = 'Late' then 1 else null end) Late
from attendance
group by id;

See SQL Fiddle with Demo

A: Use a SUM(CASE) construct to separate the Absent and Late.  For each one, the CASE returns a 1 or 0 if the value is matched, and then those are added up via the aggregate SUM() giving the total number. The concept at work here is known as a pivot table.
SELECT
  id,
  SUM(CASE WHEN Remarks = 'Absent' THEN 1 ELSE 0 END) AS Absent,
  SUM(CASE WHEN Remarks = 'Late' THEN 1 ELSE 0 END) AS Late
FROM
  attendance
GROUP BY id

A: try:
 SELECT id,
     Sum (Case remarks When 'Absent' Then 1 End) Absent,
     Sum (Case remarks When 'Late' Then 1 End) Late
 FROM attendance
 GROUP BY id;


text:
Q: Deseasonalizing a time series using a Wiener-Kolmogorov filter I am trying to eliminate seasonality from a time series using  Wiener-Kolmogorov filter, I am following the methodology explained in here this paper about signal extraction which is the same followed in this paper.
Following the paper I am able to reproduce figures 12 and 13 using the following MATLAB code:
clear
clc
close all

data = [
1955    32058   1960    37043   1965    42306   1970    46228   1975    53859   1980    61087   1985    65886   1990    83175
1955.25 34034   1960.25 39429   1965.25 44524   1970.25 48922   1975.25 55667   1980.25 59936   1985.25 66822   1990.25 85015
1955.5  34878   1960.5  39365   1965.5  45346   1970.5  50435   1975.5  56462   1980.5  62511   1985.5  70092   1990.5  88774
1955.75 36166   1960.75 40898   1965.75 46317   1970.75 52288   1975.75 58592   1980.75 63651   1985.75 73942   1990.75 90563
1956    32614   1961    37850   1966    43296   1971    47254   1976    53509   1981    60104   1986    69431   1991    82077
1956.25 34360   1961.25 40292   1966.25 46064   1971.25 50353   1976.25 55260   1981.25 60409   1986.25 71929   1991.25 82356
1956.5  34666   1961.5  40352   1966.5  45710   1971.5  52035   1976.5  57050   1981.5  62403   1986.5  75874   1991.5  86445
1956.75 36465   1961.75 41705   1966.75 46480   1971.75 54497   1976.75 59847   1981.75 64486   1986.75 78388   1991.75 89037
1957    32767   1962    38438   1967    43327   1972    50173   1977    53426   1982    59964   1987    72642   1992    80846
1957.25 35241   1962.25 41410   1967.25 46217   1972.25 53405   1977.25 54469   1982.25 60271   1987.25 74897   1992.25 82650
1957.5  35598   1962.5  41143   1967.5  47378   1972.5  55138   1977.5  56523   1982.5  63352   1987.5  80127   1992.5  86941
1957.75 37398   1962.75 42934   1967.75 49063   1972.75 58036   1977.75 60474   1982.75 66265   1987.75 83568   1992.75 89509
1958    33964   1963    39559   1968    46489   1973    54685   1978    56839   1983    62549   1988    78377   1993    82982
1958.25 35816   1963.25 42967   1968.25 46729   1973.25 56166   1978.25 57523   1983.25 63135   1988.25 80349   1993.25 84341
1958.5  36324   1963.5  43707   1968.5  48066   1973.5  57861   1978.5  60163   1983.5  66658   1988.5  86593   1993.5  89489
1958.75 38510   1963.75 44641   1968.75 49925   1973.75 59903   1978.75 62384   1983.75 68858   1988.75 89272   1993.75 92461
1959    34901   1964    41500   1969    45467   1974    53065   1979    58697   1984    63958   1989    82052   1994    85825
1959.25 37756   1964.25 44122   1969.25 47682   1974.25 55198   1979.25 62282   1984.25 65077   1989.25 84045   1994.25 86606
1959.5  37927   1964.5  44597   1969.5  48494   1974.5  57026   1979.5  61533   1984.5  66738   1989.5  88490   1994.5  91575
1959.75 40329   1964.75 45825   1969.75 50723   1974.75 60028   1979.75 64700   1984.75 70713   1989.75 90819   1994.75 94364];

data = [data(:,1:2:end) data(:,2:2:end)];
data = [data(1:end/2)' data(end/2+1:end)'];
n = length(data(:,2));
coeff = [ones(n,1) [1:n]']\log(data(:,2));
y = log(data(:,2))-(coeff(1)+coeff(2)*[1:n])';

cutoffint = 10;
seqnml = 2*pi*(0:n-1)/n;
tmp = seqnml'*[1:10];
alpha = [mean(y) y'*cos(tmp)*2/n];
beta = [0 y'*sin(tmp)*2/n];
seqcutoffint = 2*pi*[1:cutoffint]/n;
seqnml = 0:n-1;
tmp = seqcutoffint'*seqnml;
x = alpha(2:end)*cos(tmp) + beta(2:end)*sin(tmp);
x = x+alpha(1);

figure;
subplot(2,1,1);
plot(data(:,1),y)
hold on
plot(data(:,1),x,'r')
subplot(2,1,2);
plot(data(:,1),data(:,2))
hold on
plot(data(:,1),exp(x+(coeff(1)+coeff(2)*[1:n]))','r')

How to get the coefficients of a Wiener-Kolmogorov filter in order to remove seasonality from a time series?


text:
Q: Laptop touchpad enable/disable problems Whenever I use my external mouse with my laptop, I physically disable the touchpad by pressing a button. Ubuntu detects this switch correctly, and will display an overlay that shows the current state of the touchpad (enabled or disabled).
However, I do not enable it again before shutting down the system. When I reboot, the touchpad is physically enabled by default, but Ubuntu remembers it as disabled.
Ubuntu loads with the system thinking "touchpad disabled", so I cannot move the pointer. When I physically disable it, the system thinks it's enabled, but of course I cannot do anything with it either.
Is there a way to make the system forget the touchpad state on shutdown and then have it detect that properly on boot? I think this is strange and even idiotic behaviour, the system should not rely on some file on the hard disk to detect whether the touchpad is enabled. Persisting such state by default is useless in my opinion.
There are other people that had similar problems, but they used software. I use only the default system settings. I know that it is possible to make the state of the touchpad depend on the external mouse being plugged in or not, but my external mouse has a very small connector that is designed to stay plugged in at all times. Very handy as it doesn't get lost and I don't have to pull it out and push it in all the time.


text:
Q: Annotating django QuerySet with values from related table I have a model Page with 2 related models PageScoreHistory and PageImageHistory, where both history models have page field as a ForeignKey to Page and have a date field. The problem I am having, is that when I get a list of PageImageHistory QuerySet, I want to be able to retrieve the score the page had at the time the image was taken. For an individual PageImageHistory object, I can do this easily:
pih = PageImageHistory.objects.get(id=123)
score = pih.page.pagescorehistory_set.filter(datetime__lte=pih.captured).latest('datetime')

But for a QuerySet, I would like to avoid running a query for each member of the set. Is there a wayo to do this is a sane fashion, without actually looping through all members of the set?

A: It's hard without seeing your models, but does this do what you want?
PageImageHistory.objects.filter(
    page__pagescorehistory__datetime__lte=x.captured
).annotate(Max('page__pagescorehistory__datetime')


text:
Q: How to get httpd -S running in Ubuntu? I have /etc/apache2 and i included my Fedora httpd.conf virtual host files and wanted to check the details. But i get this. How to get it working?
# httpd -S
No command 'httpd' found, did you mean:
 Command 'dhttpd' from package 'dhttpd' (universe)
 Command 'xttpd' from package 'xtide' (universe)
 Command 'thttpd' from package 'thttpd' (universe)
httpd: command not found

A: The apache controlling script on Ubuntu is apachectl, just use:
apachectl -S

A: on Ubutu you can do
apache2 -S


text:
Q: Django group items by bucket I have a table bucket_items with columns bucket_id and item_id i want to group item_ids by bucket_id, using
ItemBucket.objects.values('bucket_id', 'item_id') this returns list of dictionary containing bucket_id and item_id, what i want is a list of dictionary with bucket id as key and list of item_ids as value something like
[{1: [1,2,3]}, {3: [7,3,2]}]

A: Using values_list will be better here instead of values, which returns tuples instead of dicts. So you can do something like
final_dict = dict()
for (bucket_id, item_id) in ItemBucket.objects.values_list('bucket_id', 'item_id'):
    final_dict.setdefault(bucket_id, []).append(item_id)
final_list = [{bucket_id: final_dict[bucket_id]} for bucket_id in final_dict]


text:
Q: Exception occurred applying plugin request[id:'org.jetbrains.kotlin.jvm', version:'1.3.40-eap-40'] An exception occurred applying plugin request [id: 'org.jetbrains.kotlin.jvm', version: '1.3.40-eap-40']
> Failed to apply plugin [id 'org.jetbrains.kotlin.jvm']
  > Cannot add extension with name 'kotlin', as there is an extension already registered with that name.

This error occurs in my build.gradle.kts file
Did you happen to see this error in a Kotlin Cocoapods project built from the samples provided on Kotlin/Native GitHub?

A: This error occurs because in the build.gradle.kts, there are conflicting plugin imports. Like seen below:

You can't have kotlin 'Jim' plugin and 'multi-platform plugin' together, so remove the kotlin("jvm") version "1.3.31" and build your gradle project.
Also, when you remove this will be accompanied by few more errors in the dependencies section. So comment out everything from dependencies and the two compile tasks below as well and build it. It should work!


text:
Q: How to move a-entities relative to center of the viewport [with object3D.position.set(x, y, z) ] I'm using a-frame to create a scene with a box that moves according to a sine function, but the box doesn't show up inside the viewport.
I already tried to update the box position by changing the "position" attribute and resetting the box.object3D.position.
HTML file
<a-scene log="hello scene">
<a-assets>
  <img id="boxTexture" src="https://i.imgur.com/mYmmbrp.jpg">
</a-assets>

<a-box src="#boxTexture" position="0 0 -5" rotation="0 45 45" scale="0.5 0.5 0.5">
  <!-- <a-animation attribute="position" to="0 2.2 -5" direction="alternate" dur="2000"
    repeat="indefinite"></a-animation> -->
  <a-animation attribute="scale" begin="mouseenter" dur="300" to="2.3 2.3 2.3"></a-animation>
  <a-animation attribute="scale" begin="mouseleave" dur="300" to="0.5 0.5 0.5"></a-animation>
  <a-animation attribute="rotation" begin="click" dur="2000" to="360 405 45"></a-animation>
</a-box>

<a-camera>
  <a-cursor></a-cursor>
</a-camera>

JavaScript file
// low frequency oscillator
function lfo(amp, freq, phase) {
  var date = new Date();
  var millis = 0.001 * date.getMilliseconds();
  var value = amp * Math.sin(millis * freq + phase);
  return value;
}

var boxes = document.querySelectorAll('a-box');

function moveBoxes() {
  // loop through all the boxes in the document
  for (var i = 0; i < boxes.length; i++) {
    let x = lfo(1, 1, 0);
    let y = lfo(1, 1, 0.2);
    let z = lfo(1, 1, 0.7);
    boxes[i].object3D.position.set(x, y, z);
    //boxes[i].setAttribute("position", x+" "+y+" "+z);
  }
}

I'd except to see the box either on center of the scene or at least at the upper-left corner, but it's neither.

A: The 2D viewport does not map to the 3D positions within the 3D scene.
The A-Frame mouse cursor maps mouse clicks to in-3D clicks. I'm not sure, but you might be able to use this sort of method to convert 2D X/Y coordinate to 3D coordinate at your specified distance: https://github.com/aframevr/aframe/blob/master/src/components/cursor.js#L213
But otherwise, I would just make something a child of the camera.
<a-entity camera>
  <a-box move-sin-wave-or-whatever-animation position="0 0 -1"></a-box>
</a-entity>


text:
Q: Kolmogorov's superposition theorem for non-continuous functions I'm trying to think about Kolmogorov's superposition theorem. This theorem states that, for each $n ≥ 2$ there exist
continuous functions $ϕ_q : [0, 1] → R, q = 0, ..., 2n$ and constants $λ_p ∈ R, p = 1, ..., n$ such
that the following statement is true: for each continuous function $f : [0, 1]^n → R$ there exists a
continuous function $g : [0, 1] → R$ such that
$$f(x_1, ..., x_n) = \sum_{q=0}^{2n} g(\sum_{p=1}^n \lambda_p \phi_q(x_p))$$
That is, any continuous function of $n$ variables can be written as a combination of sums and compositions of continuous functions of one variable.
Would a theorem like this apply if we dropped the assumption that $f$ is continuous, and the restrictions that $g,\phi_q$ be continuous?


text:
Q: c# Extension method Im trying to test my extension method that converts a list of strings in a string comma separated:
public static class Extensions
{
      public static string ToCommaString<T>(this IList<T> input)
      {
        StringBuilder sb = new StringBuilder();
        foreach (T value in input)
        {
            sb.Append(value);
            sb.Append(",");
        }
        return sb.ToString();
      }
      public void TestExtension()
      {
        IList test=new List<string>();
        //test.ToCommaString doesnt appear
      }
}

The issue is that in the method TestExtension i cant use ToCommaString method.
Do you know what's happening?
Could i make available for all my web application this extension method registering in web.config or something similar?
Thanks in advance.
Best regards.
Jose

A: You're declaring your list to be the wrong type (non-generic):
IList test=new List<string>();

It should be
IList<String> test=new List<string>();


text:
Q: Compute an integral using Cauchy's integral formula I am revising complex analysis and have come across this example which I want to solve.

Example: Compute the integral
  $$
 \int_\gamma \frac{e^{2z} + \sin z}{z - \pi} \,\text{d}z
$$
  where $\gamma$ is the circle $|z-2|=2$ traversed counter-clockwise.

I think that it needs to be solved using Cauchy's integral formula, however I am struggling to apply the formula to get a solution.  I would appreciate any hints and tips on how to get to the answer.

A:
$$\int_\gamma \frac{e^{2z} + \sin z}{z - \pi} \,\text{d}z$$

Here is the formula $f(z)=\frac{1}{2\pi i}\displaystyle\int_\gamma \frac{f(z)}{z-z_0}$

Let us denote $f(z)=e^{2z}+\sin z$ so $f(\pi)\cdot 2 \pi i=\displaystyle\int_\gamma \frac{e^{2z} + \sin z}{z - \pi} \,\text{d}z$
In our case $z_0=\pi$ now $f(\pi)=e^{2\pi}+\sin(\pi)=e^{2\pi}$
So the final answer is $e^{2\pi}\cdot 2\pi i$

A: As you said you apply Cauchy's Integral Formula
with $a = \pi$ and $f(z)= e^{2z} + \sin z$ to get that
$2\pi i f(\pi) $ is equal to your integral. (Check the conditions are fulfilled though.)
As $\sin \pi = 0$ this yields exactly what your answer says.


text:
Q: Hibernate Criteria: nested exception is org.hibernate.QueryException: could not resolve property: I'm trying get all data from isssue table that matches with projectname and Issue Id. I'm getting following error. please help me.
Tables
Project
ProjectID
ProjectName
Issue
issueID
identifier
sourceStatus
title
severity
description
Project.java
@Entity
    @Table(name="project")
    public class Project implements Serializable {

        private static final long serialVersionUID = 2457316470957669814L;
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        @Column(name="ProjectId")
        private Integer projectId;

        @Column(name="projectname")
        private String projectName;

        @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy = "project")
        private List<Issue> issue;

        //getters and setters
    }

Issue.java
@Entity
@Table(name="issue")
public class Issue implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="Id")
    private Integer Id;

    @Column(name="identifier")
    private String identifier;

    @Column(name="sourcestatus")
    private String sourceStatus;

    @Column(name="severity")
    private Integer severity;

    @Column(name="title")
    private String title;

    @Column(name="description")
    private String description;

    @ManyToOne
    @JoinColumn(name ="ProjectId")
    private Project project;

//getters and setters
  }

IssueDAOImpl.java
public List<Issue> getAllIssue(String identifier,String projectName) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Issue.class);
    criteria.createAlias("Project", "Prj");
    criteria.add(Restrictions.eq("identifier",identifier));
    criteria.add(Restrictions.eq("Prj.projectName",projectName));

    List<Issue> list=criteria.list();
    return list;
}

CONSOLE
SEVERE: Servlet.service() for servlet [dcm] in context with path [/SearchTool] threw exception [Request processing failed; nested exception is org.hibernate.QueryException: could not resolve property: Project of: com.dcm.search.bean.Issue] with root cause
org.hibernate.QueryException: could not resolve property: Project of: com.dcm.search.bean.Issue

A: Change criteria.createAlias("Project", "Prj") to criteria.createAlias("project", "Prj"). The property for which you are trying to create an alias is project, so should go as the first argument of createAlias. Project is the class name.

A: You have called the Hibernate property "ProjectId", not "Project".
criteria.createAlias("Project", "Prj");

This should be:
criteria.createAlias("ProjectId", "Prj");


text:
Q: Confirm box inside other confirm I have asp button myButton with OnClientClick properties which return jquery myConfirm() function.
I have function like this:
function myConfirm(){
    if(confirm("accept")==true){
        confirm("second message");
        return true;
    }
    else {
        otherFunc();
        return false;
    }
}

I have a problem, because the second confirm box does not fire. After myButton click jquery fire first confirmation box with OK and Cancel, when I click OK Ii would like to fire second confirm box with second message. How to make two level of box confirmation in jquery?


text:
Q: Get Asterisk events inside web application I'm developing a contact center with Laravel framework, I'm using Asterisk 13 to manage call system.
Each operator is assigned an extension to use a SIP software (Zoiper) in order to answer customer calls.
What I want is a convenient API to interact with asterisk server, for example when the operator receive a customer call, the caller id being inserted in a text field.
I've been experimenting with PHPARI But it lacks proper documentation.

A: ARI is very new inteface.
If you want more documentation, try with AMI event model.

A: I have worked with PAMI and it satisfied my needs.
The documentation is not great too and some events are not processed with this library thus you may have to make some changes but the overall structure is good.
If nothing meets your expectation you may want to create your own parser, after all AMI will return a well formed string and use can parse that string for your needs.


text:
Q: Can I use "exclude" with #import directive when I encounter C4192 warning? I have the following IDL:
import "oaidl.idl";
import "ocidl.idl";

[uuid(MyLibUuid), version(1.0)]
library MyLibrary
{
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");
[object, uuid("MyInterfaceUuid"), nonextensible]
interface IMyInterface : IUnknown {
        HRESULT MyMethod( [in] IStream* stream );
    };
}

which is compiled into a .tlb file and imported from another project:
#import "PathToTypeLib.tlb" raw_interfaces_only

and when this is compiled Visual Studio emits the following output:
warning C4192: automatically excluding 'IStream'
    while importing type library 'PathToTypeLib.tlb'
warning C4192: automatically excluding 'ISequentialStream'
    while importing type library 'PathToTypeLib.tlb'

Okay, the problem is because those to importlib directives caused IStream and ISequentialStream defined inside the typelib - MSDN explains it and says I have to either use include or no_auto_exclude with #import.
If I use either no_auto_exclude or include( "IStream", "ISequentialStream" ) I now have two IStream definitions - one in global namespace and another in typelib namespace and so my code that tries to call MyMethod doesn't compile - the compiler says
error C2664: 'MyLibrary::MyInterface::MyMethod' :
   cannot convert parameter 1 from 'IStream *' to 'MyLibrary::IStream *'
   Types pointed to are unrelated; conversion requires reinterpret_cast,
   C-style cast or function-style cast

so it looks like I instead have to use exclude( "IStream", "ISequentialStream" ) - this way it compiles fine and looks working.
Is using exclude actually the right solution?

A: This would work well if IStream itself was on a type library, such as stdole2.tlb you reference from your IDL/TLB.
Unfortunately it is not and what takes place is that ID: compiler needs to put put your IMyInterface onto library block and since IStream is referenced, compiler puts it onto type library as well. Hence, the duplicated declaration hurting you once you import the type library back. I don't think you can have it as IStream there without taking your own IStream interface onto the type library.
The workaround I use is to avoid using IStream on method parameters, and to use IUnknown there instead. Caller and callee would cast/QI the pointers if/when appropriate. This way it is safe with #import and works out in general.
[uuid(MyLibUuid), version(1.0)]
library MyLibrary
{
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");
[object, uuid("MyInterfaceUuid"), nonextensible]
interface IMyInterface : IUnknown {
        HRESULT MyMethod( [in] IUnknown* pStreamUnkown ); // Instead of IStream
    };
}

Caller:
CComPtr<IStream> pStream;
pMyInterface->MyMethod(pStream);

Callee:
STDMETHOD(MyMethod)(IUnkown* pStreamUnknown)
{
    CComQIPtr<IStream> pStream = pStreamUnknown;

Callee assuming no marshaling (least overhead):
STDMETHOD(MyMethod)(IUnkown* pStreamUnknown)
{
    ATLASSERT((IUnknown*) (IStream*) CComQIPtr<IStream>(pStreamUnknown) ==
      pStreamUnknown);
    const CComPtr<IStream>& pStream =
      reinterpret_cast<const CComPtr<IStream>&>(pStreamUnknown);


text:
Q: Power Query Table.TransformRows won't return table In the M language documentation for Table.TransformRows, it lists the type signature as Table.TransformRows(table as table, transform as function) as list
followed by the slightly cryptic comment

If the return type of the transform function is specified, then the result will be a table with that row type.

However, whenever I define my function, Power Query always returns me a list instead of a table.
For instance, this query:
    func = (row) as record => [B = Number.ToText(row[a])] as record,
    #"firstTable"= Table.FromRecords({
            [a = 1],
            [a = 2],
            [a = 3],
            [a = 4],
            [a = 5]}),
    #"myTable" = Table.TransformRows(#"firstTable",func)
in
  #"myTable"

returns a table.
I had wondered if I needed to create a record type which specifies the type of each record entry, but if I try
myType = type [B = text],
func = (row) as record => [B = Number.ToText(row[a])] as myType

then it tells me that my type identifier is invalid on the second line. Finally, I tried to set the function return type using
myType = type [B = text],
func1 = (row) as record => [B = Number.ToText(row[a])] as myType,
funcType = Type.ForFunction([ReturnType = myType, Parameters = [X = type number]], 1),
func = Value.ReplaceType(func1,funcType)

but Table.TransformRows still returns a list.
I am aware that I am able to use Table.FromRecords or Table.FromRows to turn the result of Table.TransformRows into a table, but I am currently experiencing some performance issues with these functions and was trying to cut them out to see if this would fix those issues

A: typing inline

returns a table. I had wondered if I needed to create a record type which specifies the type of each record entry

// you had this
record_list = { [ a = 1 ], [ a = 2 ], [ a = 3 ], [ a = 4 ], [ a = 5 ] },
firstTable = Table.FromRecords(
    record_list
)

Which ends up as a column of type any. To fix that:
// declare the type
firstTable = Table.FromRecords(
    record_list,
    type table[a = text]
)

Whenever a function takes the parameter columns as any you can use any of these formats

*

*"Name"

*`{ "Name1", "Name2" }

*type table[ Name1 = text, Name2 = number ]
Invalid type Identifier

then it tells me that my type identifier is invalid on the second line

The as operator only works on primitive data types.
If it were to work, this would mean assert the record is a myType, then the function return asserts the type is record, which is mixed types. The function already has a final assert, so you don't need one on your inner calls.
func = (row) as record => [B = Number.ToText(row[a])] as something

Replacing Function Types does not change behavior

Finally, I tried to set the function return type using ... Value.ReplaceType

Using Value.ReplaceType on a function does not modify the actual types or behavior. That's just changing the metadata.

Ben Gribaudo: /part18-Custom-Type-Systems As type ascription can only change information about a function, not the function's behavior at the language level, ascribing a type onto a function that specifies different argument or return assertions has no effect on the behavior of the function. The mashup engine always uses the type assertions specified when the function was originally defined, even if another type is later ascribed onto it.

Check out Ben's Power Query series. It's high quality. It goes into far more detail than other places.
Performance

I am aware that I am able to use Table.FromRecords or Table.FromRows to turn the result of Table.TransformRows into a table, but I am currently experiencing some performance issues

Missing column data-types can cause issues. But you really should try the query diagnostics, it will tell you what steps are taking the most time.
Based on your example, you might want transform column instead of rows.
Also make sure your query is folding!

Example using Table.TransformRows with typing
let
    // sample data, list of records like: [ Number = 0 ]
    numberRecords = List.Transform( {0..10}, each [Number = _] ),
    Source = Table.FromRecords(
        numberRecords,
        type table[Number = number]
    ),

    transform_SquareNumbers = (source as table) =>
        let
            rows = Table.TransformRows(
                source, (row) as record =>
                    [
                        Number = Number.Power(
                            row[Number], 2
                        )
                    ]
            ),
            result = Table.FromRecords(rows),
            source_type = Value.Type(source)
        in
            Value.ReplaceType(result, source_type),

    FinalTable = transform_SquareNumbers(Source)
in
    FinalTable


text:
Q: binary search function not searching Hi I'm trying to get my code to work with a binary search function but I can't search anything. Every time I attempt to search for a name from the string I keep getting the "invalid input" from my main function. Please let me know if there's anything else I could do differently! I've been stumped for some time now. Any help will be appreciated!
#include <iostream>
#include <string>
using namespace std;

int binarySearch(string[], int, string);
void selectionSort(string[], int);
string getValue();

string getValue()
{
    string input;
    cout << "Enter the name you would like to search for: ";
    getline(cin, input);
    return input;
}

int main(){
    const int NUM_NAMES = 20;

    string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim", "Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill",
     "Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean", "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
      "Pike, Gordon", "Holland, Beth"
    }; // Insert your code to complete this program

    string value;
    int nameSearch;

    selectionSort(names, NUM_NAMES);

    value = getValue();

    nameSearch = binarySearch(names, NUM_NAMES, value);

    if (nameSearch == -1)
        cout << "invalid input.\n";
    else
        cout << names[nameSearch] << " has been found! #" << nameSearch << ".\n";

    return 0;
}

//input to find names in the string

void selectionSort(string array[], int size)
{
    int startScan, minIndex;
    string minValue;

    for (int startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = array[startScan];
        for (int index = 0; index < size; index++)
        {
            minValue = array[index];
            minIndex = index;
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}

int binarySearch(string array[], int size, string value)
{
    int first = 0,                      // First array element
        last = size - 1,                // Last array element
        middle,                         // Midpoint of search
        position = -1;                  // Position of search value
    bool found = false;                 // Flag

    while (!found && first <= last)
    {
        middle = (first + last) / 2;    // Calculate midpoint
        if (array[middle] == value)     // If value is found at mid
        {
            found = true;
            position = middle;
        }
        else if (array[middle] > value) // If value is in lower half
            last = middle - 1;
        else
            first = middle + 1;         // If value is in upper half
    }
    return position;
}

A: If you print out the names array before and after sorting via your selectionSort function you can check if it appears to be working:
#include <iostream>
#include <string>

void printArray(const std::string[], int);
void selectionSort(std::string[], int);
std::string getValue();
int binarySearch(const std::string[], int, const std::string &);

int main() {
  const int NUM_NAMES = 20;
  std::string names[NUM_NAMES] =
      {"Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim",
       "Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill",
       "Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean",
       "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee",
       "Harrison, Rose", "Setzer, Cathy", "Pike, Gordon", "Holland, Beth"};

  std::cout << "Before Sorting:\n";
  printArray(names, NUM_NAMES);
  selectionSort(names, NUM_NAMES);
  std::cout << "After Sorting:\n";
  printArray(names, NUM_NAMES);

  std::string value = getValue();
  int value_index = binarySearch(names, NUM_NAMES, value);
  if (value_index == -1) {
    std::cout << "Error: Could not find \"" << value << "\" in array.\n";
  } else {
    std::cout << names[value_index] << " has been found at index: "
              << value_index << " \n";
  }

  return 0;
}

void printArray(const std::string array[], int size) {
  if (size < 1) {
    std::cout << "[]";
    return;
  }
  std::cout << '[';
  for (int i = 0; i < size - 1; i++) {
    std::cout << '"' << array[i] << '"' << ", ";
  }
  std::cout << '"' << array[size - 1] << '"';
  std::cout << "]\n";
}

void selectionSort(std::string array[], int size) {
  for (int j = 0; j < size - 1; j++) {
    int min = j;
    for (int k = j + 1; k < size; k++) {
      if (array[k].compare(array[min]) < 0) {
        min = k;
      }
    }
    std::string temp = array[j];
    array[j] = array[min];
    array[min] = temp;
  }
}

std::string getValue() {
  std::string input;
  std::cout << "Enter the name you would like to search for: ";
  getline(std::cin, input);
  return input;
}

int binarySearch(const std::string array[],
                 int size,
                 const std::string &value) {
  int lo = 0, hi = size - 1;
  while (lo <= hi) {
    int mi = lo + (hi - lo) / 2;
    if (array[mi] < value) {
      lo = mi + 1;
    } else if (array[mi] > value) {
      hi = mi - 1;
    } else {
      return mi;
    }
  }
  return -1;
}

Example Usage 1:
Before Sorting:
["Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim", "Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill", "Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean", "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee", "Harrison, Rose", "Setzer, Cathy", "Pike, Gordon", "Holland, Beth"]
After Sorting:
["Allen, Jim", "Allison, Jeff", "Collins, Bill", "Griffin, Jim", "Harrison, Rose", "Holland, Beth", "James, Jean", "Javens, Renee", "Johnson, Jill", "Looney, Joe", "Pike, Gordon", "Pore, Bob", "Rose, Geri", "Rutherford, Greg", "Setzer, Cathy", "Smith, Bart", "Stamey, Marty", "Taylor, Terri", "Weaver, Jim", "Wolfe, Bill"]
Enter the name you would like to search for: Griffin, Jim
Griffin, Jim has been found at index: 3 .

Example Usage 2:
Before Sorting:
["Collins, Bill", "Smith, Bart", "Allen, Jim", "Griffin, Jim", "Stamey, Marty", "Rose, Geri", "Taylor, Terri", "Johnson, Jill", "Allison, Jeff", "Looney, Joe", "Wolfe, Bill", "James, Jean", "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", "Javens, Renee", "Harrison, Rose", "Setzer, Cathy", "Pike, Gordon", "Holland, Beth"]
After Sorting:
["Allen, Jim", "Allison, Jeff", "Collins, Bill", "Griffin, Jim", "Harrison, Rose", "Holland, Beth", "James, Jean", "Javens, Renee", "Johnson, Jill", "Looney, Joe", "Pike, Gordon", "Pore, Bob", "Rose, Geri", "Rutherford, Greg", "Setzer, Cathy", "Smith, Bart", "Stamey, Marty", "Taylor, Terri", "Weaver, Jim", "Wolfe, Bill"]
Enter the name you would like to search for: sdgfdsfgsdfg
Error: Could not find "sdgfdsfgsdfg" in array.


text:
Q: Can't use a locally modified Angular module inside another project I'm getting the following error when I ng serve (and I've already tried to clear cache, reinstall all modules and reboot the server)
Error: ../../../../angular/ngx-charts-master/ngx-charts-master/dist/swimlane/ngx-charts/lib/ngx-charts.module.d.ts:1:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the dependency which declares NgxChartsModule has not been processed correctly by ngcc.

The full contextual background is that I've modified the source and posted a pull request but I don't know if/when the maintainers will accept it and I want to use the modified module in the meantime at least.
Of course I've tested the changes by using them through the internal demo app (with a couple of trivial, ad hoc changes) and it's all working fine. Then I build the dist with the
ng build @swimlane/ngx-charts

and it produced its output inside the dist folder /dist/swimlane/ngx-charts/ from which I'm trying to import as shown above, at the beginning
Further trying...
I've rewritten the import as
import { NgxChartsModule } from '../../../../../../angular/ngx-charts-master/ngx-charts-master/dist/swimlane/ngx-charts';

I deleted the standard entry in package.json and installed the module from my local folder
"@swimlane/ngx-charts": "file:../../../../angular/ngx-charts-master/ngx-charts-master/dist/swimlane/ngx-charts",

Then I followed the instruction to install also the dev dependencies
"d3-array": "^2.9.1",
"d3-brush": "^2.1.0",
"d3-color": "^2.0.0",
"d3-format": "^2.0.0",
"d3-hierarchy": "^2.0.0",
"d3-interpolate": "^2.0.1",
"d3-scale": "^3.2.3",
"d3-selection": "^2.0.0",
"d3-shape": "^2.0.0",
"d3-time-format": "^3.0.0",
"d3-transition": "^2.0.0"

(copied from the project json in the internal lib of the module repository) but ng serve still fails with
Error: ../../../../angular/ngx-charts-master/ngx-charts-master/dist/swimlane/ngx-charts/lib/area-chart/area-chart.component.d.ts:2:29 - error TS7016: Could not find a declaration file for module 'd3-shape'. 'F:/Appl/angular/ngx-charts-master/ngx-charts-master/dist/swimlane/ngx-charts/node_modules/d3-shape/dist/d3-shape.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/d3-shape` if it exists or add a new declaration (.d.ts) file containing `declare module 'd3-shape';`

2 import { CurveLinear } from 'd3-shape';
                              ~~~~~~~~~~

Error: ./src/main.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):

Note
I didn't mention, but now I suspect these warnings from the npm run build:lib --prod were relevant to the question
√ Compiling TypeScript sources through NGC
√ Bundling to FESM2015
/ Bundling to UMDWARNING: No name was provided for external module 'd3-selection' in output.globals – guessing 'd3Selection'
WARNING: No name was provided for external module 'd3-brush' in output.globals – guessing 'd3Brush'
WARNING: No name was provided for external module 'd3-scale' in output.globals – guessing 'd3Scale'
WARNING: No name was provided for external module 'd3-shape' in output.globals – guessing 'd3Shape'
WARNING: No name was provided for external module 'd3-array' in output.globals – guessing 'd3Array'
WARNING: No name was provided for external module 'd3-interpolate' in output.globals – guessing 'd3Interpolate'
WARNING: No name was provided for external module 'd3-format' in output.globals – guessing 'd3Format'
WARNING: No name was provided for external module 'd3-color' in output.globals – guessing 'd3_color'
WARNING: No name was provided for external module 'd3-hierarchy' in output.globals – guessing 'd3Hierarchy'
WARNING: No name was provided for external module 'd3-time-format' in output.globals – guessing 'd3TimeFormat'
√ Bundling to UMD
√ Minifying UMD bundle
√ Writing package metadata
i Built @swimlane/ngx-charts

------------------------------------------------------------------------------
Built Angular Package
 - from: F:\Appl\angular\ngx-charts-master\ngx-charts-master\projects\swimlane\ngx-charts
 - to:   F:\Appl\angular\ngx-charts-master\ngx-charts-master\dist\swimlane\ngx-charts
------------------------------------------------------------------------------

A: Tried almost everything... finally I'm importing the source and it looks like it wants the project folder inside the root directory and not from a path outside it, so I copied the project folder from the module repository under the root of my app and pointed to it
import { NgxChartsModule } from '../projects/swimlane/ngx-charts/src/lib/ngx-charts.module';

At least, now my ng serve is running fine (so I'm happy enough with this solution/workaround)
compiler options
I forgot to share the settings I had to update in tsconfig.json
"strict": false,
"noImplicitReturns": false,

and below
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": false,
    "strictInputAccessModifiers": false,
    "strictTemplates": false
  }

Anyway, as noted in my comment below, I haven't (yet) released my modified module to the users but the standard one with percentageFormatting to zero decimal places (that seems fair enough)


text:
Q: Similar Encrypt code in javascript as in C# I use some remote api, they use such C# code:
SHA256Managed sha256Managed = new SHA256Managed();
byte[] passwordSaltBytes = Encoding.Unicode.GetBytes("zda");

byte[] hash = sha256Managed.ComputeHash(passwordSaltBytes);

string result = Convert.ToBase64String(hash);

Console.WriteLine("result = " + result); // result = NUbWRkT8QfzmDt/2kWaikNOZUXIDt7KKRghv0rTGIp4=

I need to get the same result in my javascript frontend code. Does somebody can help with such problem?

A: The answer is:
var utf8arr = CryptoJS.enc.Utf16LE.parse("zda");
var hash = CryptoJS.SHA256(utf8arr);
var base64 = CryptoJS.enc.Base64.stringify(hash);
console.log(base64);

A: Not quite obvious, but Unicode in C# is using UTF-16LE enconding.
So you can use CryptoJS to achieve the same result:
var utf16 = CryptoJS.enc.Utf16LE.parse("zda");
var hash = CryptoJS.SHA256(utf16);
var base64 = CryptoJS.enc.Base64.stringify(hash);
console.log(base64);


text:
Q: DataInputStream not Receiving Data After Flushing DataOutputStream So, I'm fairly new to sockets and data streams... And I am absolutely baffled by this issue I'm having.  I've searched for hours trying to find a solution, assuming that other people might have had the same issue I'm having, but I've found absolutely nothing helpful so far.
I'm writing a very simple multithreaded server/client program that is supposed to open a serverSocket, and accept connections from clients, storing them in a simple arraylist (I'll change the storage process once I actually get messages to send), and then a message handler thread parses the list, and checks if a user has written to the server.  If the user has written something, the program then displays the resulting message to the console.  My program successfully writes to the server socket through the DataOutputStream, but when I attempt to read from the corresponding DataInputStream on the server side, it says the stream is empty, and my program will continue to loop.  I've checked that the DataOutputStream receives the data through DataOutputStream.size(), and that the DataInputStream I am attempting to read data from corresponds to the correct DataOutputStream I mentioned before.
User Code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

public class User {
    private String hashID;
    private Socket connection;
    private static int hashVal = 0;
    DataInputStream consoleInputStream;
    String consoleInput = "";

    public User(Socket conn) throws SocketException {
        hashID = hashUserKey();
        connection = conn;
        connection.setSoTimeout(1500);
        consoleInputStream = new DataInputStream(System.in);
    }

    private static String hashUserKey() { //placeholder for now
        hashVal++;
        return("Guest" + hashVal);
    }

    public Socket getSocket() {
        return this.connection;
    }

    public String getID() {
        return this.hashID;
    }

    public boolean disconnect() {
        try {
            consoleInputStream.close();
            connection.close();
            return true;
        } catch (IOException e) {
            System.err.println(hashID + " was unable to successfully disconnect");
            return false;
        }
    }

    public void startConnection() {
        new Thread() {
            @Override
            public void run() {

                while(!connection.isClosed()) {

                    try {
                        consoleInput = consoleInputStream.readLine();
                        if(consoleInput != null || consoleInput != "") {
                            writeToServer(consoleInput);
                        }
                    } catch (IOException e) {
                        System.err.println("Was not able to read console input");
                    }
                }
                System.out.println("You were disconnected, have a nice day!");
                return;
            }
        }.start();

    }

    private boolean writeToServer(String toWrite) {
        try {
            String msg = hashID + ">>>: " + toWrite;
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            outStream.writeUTF(toWrite + "\r\n");
            outStream.flush();
            consoleInput = "";
            System.out.println(msg + "\t was written to " + connection.getInetAddress() + ":" + connection.getPort());
            return true;
        } catch (IOException e) {
            System.err.println(hashID + " was unable to write to server");
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        User t = (User) o;
        if(t.hashID == this.hashID) {
            return true;
        }
        return false;
    }

}

Server Code:
import java.net.*;
import java.io.*;
import java.util.*;

public class TestServer {

        private static ServerSocket server;
        private static TestLogger logger;
        private static Thread serverHandlerThread;
        private static Thread messageHandlerThread;
        private static ArrayList<User> users;
        private static volatile boolean hasBeenStopped = false;

        public static boolean startServer(int port) {
            logger = new TestLogger();
            logger.log("Attempting to create default shutdown behavior for server");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        if(!hasBeenStopped) {
                            logger.warn("Server was shut down without running stopServer(), running by default");
                            stopServer();
                        }
                    }
                }
            );
            logger.log("Shutdown behaivor created. Now attempting to set up user database"/*TODO create a real database*/);
            users = new ArrayList<User>();
            logger.log("Attempting to start server");

            try {
                server = new ServerSocket(port);
                logger.log("Server successfully started at " + server.getInetAddress() + ":" + server.getLocalPort() +", now attempting to start user connection handler");
                serverHandlerThread = new Thread() {
                    @Override
                    public void run() {
                        this.setName("serverHandlerThread");
                        while(!server.isClosed()) {
                            try {
                                Socket temp = server.accept();
                                logger.log("Connection accepted from " + temp.getInetAddress());
                                System.out.println("Connection accepted from " + temp.getInetAddress());
                                startUserConnection(new User(temp));
                            } catch (SocketException e) {
                                logger.warn("Server was closed while in accept phase");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        logger.log(this.getName() + " was stopped, server socket was closed successfully");
                        return;
                    }
                };

                serverHandlerThread.start();
                logger.log("Server thread successfully started, listening for connections on: " + server.getInetAddress().toString() + ":" + port);

                logger.log("Attempting to start message handler thread to read user inputs");
                messageHandlerThread = new Thread() {
                    @Override
                    public void run() {
                        this.setName("messageHandlerThread");
                        while(!server.isClosed()) {
                            if(users.isEmpty()) {
                                continue;
                            }
                            for(int i = 0; i < users.size(); i++) {
                                User temp = users.get(i);
                                try {
                                    System.out.println(new DataInputStream(temp.getSocket().getInputStream()).readUTF());
                                } catch (IOException e) {
                                    System.err.println("Nothing to read from client: " + temp.getID());
                                }
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                };

                messageHandlerThread.start();
                return true;
            } catch (IOException e) {
                logger.error("Could not bind server socket to port.");
                return false;
            }

        }

        public static boolean stopServer() {
            logger.log("Started shut down process");
            if(serverHandlerThread == null || !serverHandlerThread.isAlive()) {
                logger.warn("Thread has not been started yet or has already been killed");
                return false;
            }
            else {
                stopAllUserConnections();

                try {
                    server.close();
                    hasBeenStopped = true;
                    while(serverHandlerThread.isAlive()) {

                    }
                    logger.log("Server was successfully shut down");
                    return true;
                } catch (IOException e) {
                    logger.error("Could not close server socket");
                    return false;
                }

            }
        }

        private static void startUserConnection(User user) {
            logger.log("Connected new user from " + user.getSocket().getInetAddress());
            users.add(user);
            System.out.println(user.getID() + " was added to list");
            user.startConnection();
        }

        private static boolean stopUserConnection(User user) {
            logger.log("Attempting to disconnect user, address: " + user.getSocket().getInetAddress());
            for(User u : users) {
                if(u.equals(user)) {
                    u.disconnect();
                    return true;
                }
            }
            logger.warn("Could not find user with address: " + user.getSocket().getInetAddress());
            return false;
        }

        private static boolean stopAllUserConnections() {
            logger.log("Attempting to disconnect all users from the server");
            if(users.isEmpty()) {
                logger.warn("No users available to disconnect");
                return false;
            }
            for(User u : users) {
                u.disconnect();
            }
            users.clear();
            return true;
        }

        public static void main(String args[]) {
            startServer(*the_port*);
            Client c = new Client();
            c.connect("0.0.0.0", *the_port*);
        }
}

Client Code:
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public boolean connect(String serverName, int port) {
        try {
            System.out.println("Attempting to connect");
            Socket sock = new Socket(serverName, port);
            System.out.println("Connected");
            return true;
        } catch (UnknownHostException e) {
            System.err.println("Could not resolve " + serverName + ":" + port);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

So as I said above, this works fine up until I attempt to read the data written to the server.  No matter what I do, the server's call to readUTF() on the socket always throws an IOException and checking the bytes ready to read by using DataInputStream.available() returns 0 as well.  My sample output from my most recent run is as follows:
Attempting to connect
Connected
Connection accepted from *the_address*
Guest1 was added to list
Nothing to read from client: Guest1
Nothing to read from client: Guest1
Nothing to read from client: Guest1
test
Guest1>>>: test  was written to *the_address:another_port*
Nothing to read from client: Guest1
Nothing to read from client: Guest1
Nothing to read from client: Guest1

I know my code may be terribly optimized, and I'll work on fixing that later, but right now, all I want to know is why my DataInputStream is empty after flushing the corresponding DataOutputStream, and how I can successfully send UTF data between them.


text:
Q: im not able to convert my mysql query into elasticsearch query I'm a beginner in Elasticsearch. I recently changed my search db from MySQL to Elasticsearch but I am not able to convert one of my queries. The query is given below.
select * from table
where (col1 = "a" and col2 = "b")
or (col1 = "c" and col2 = "d")
and col3 = "z";

A: Its all about coming the must and should filters together to workout such queries.
Following query is elasticsearch query for your SQL statement.
GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "col3": {
              "value": "z"
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                    {
                      "term": {
                        "col1": {
                          "value": "a"
                        }
                      }
                    },
                    {
                      "term": {
                        "col2": {
                          "value": "b"
                        }
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "term": {
                        "col1": {
                          "value": "c"
                        }
                      }
                    },
                    {
                      "term": {
                        "col2": {
                          "value": "d"
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}


text:
Q: Can many independent weak predictors (with low corr. with the target) act together and result in high accuracy in a linear model? Is it even possible? The question just came to my mind. I notice that generally succesfull models include at least some predictors that somewhat correlate to the target. But is it completelly necessary? Is it possible to succesfully predict the target using many predictors with very low correlation (e.g. corr < 0.1)

A: Yes, this is possible
This is actually a common phenomenon in regression analysis.  Broadly speaking, if predictors are not too correlated amongst themselves (so that they are not duplicating information too much), they will tend to add information to the regression even if they are individually adding only a small amount of information.  With a sufficient number of (individually) weak predictors you can make a prediction of the response variable that is highly accurate.  The overall accuracy is somewhat complicated --- in linear regression it depends on the full correlation matrix of the predictors and their individual correlations with the response variable (see O'Neill 2019 for a geometric analysis).
As an extreme example of this phenomenon, it is possible to have a set of explanatory variables that are weak predictors individually, but they are collectively perfect predictors of the response variable.  For example, suppose we take some large number of predictors $m$ and we set:
$$x_1,...,x_m \sim \text{IID N}(0, \sigma^2)
\quad \quad \quad \quad \quad y \equiv \sum_{k=1}^m x_i.$$
In this case, the vector $\mathbf{x} = (x_1,...,x_m)$ perfectly predicts the value $y$ even though individually we have correlation values:
$$\mathbb{Corr}(y, x_k) = \frac{1}{\sqrt{m}}.$$
If we take $m$ to be large then these individual correlation values for the predictors are small, even though the vector of predictors perfectly determines the response.  (Taking $m > 100$ is enough to get $\mathbb{Corr}(y, x_k) < 0.1$ as desired in your question.)


text:
Q: Does a motor's stall current change with applied voltage? In other words, if the load is great enough, will a 110V, 18A rated motor being run at 5V stall at the same current as if it were run at 110V? I'm asking because I'm currently working with a treadmill, which at its lowest speed (I read ~6V across the motor free-running) has enough torque to move a large amount of weight. I measured the motor's resistance to be 0.9 Ohm, so at its lowest speed free-running the current draw is around I=V/R = 6.7A? Or is that the stall current?
Would powering the motor on its own with a 5V supply be the same as the onboard controller providing 5V to the motor through PWM 120V?
I guess I'm just surprised a motor can provide so much torque with such little voltage. So what determines a motor's current?

A: Some motor basics.
A motor's stall current is determined by the resistance of the coil. (quoted at the nominal operating voltage). If the shaft is clamped so it cannot rotate then the 'motor' will act like any other resistor and follow Ohm's law - so yes, the stall current will increase with increasing applied voltage.
Once the rotor starts to rotate it will induce a back emf so the voltage 'seen' across the rotor will be reduced. The net current through the motor will be reduced.
Increasing the applied voltage will increase the speed (how much depends on the motor). With increasing speed comes increasing loss (friction, windage etc.) so there will be a corresponding increase in current.
Applying a load (torque) to the output shaft slows the rotation speed and reduces the back emf. This in turn  will increase the motor current. Applying too much torque may reduce the shaft speed to 0 and this is once again back to a stall.


text:
Q: Increasing a value each time a function passes through a for loop I am trying to make a for loop that returns response.json[i] from an API, with i increasing by 1 each time through the loop.
Example:
import requests
import json

def get_url():
    url = "https://bing-news-search1.p.rapidapi.com/news/search"

    querystring = {"q":"bitcoin","count":"20","textFormat":"Raw","safeSearch":"Off"}

    headers = {
        'x-bingapis-sdk': "true",
        'x-rapidapi-host': "bing-news-search1.p.rapidapi.com",
        'x-rapidapi-key': "api_key"
        }

    response = requests.request("GET", url, headers=headers, params=querystring)
    print(response.json()["value"][i]["url"]) # Here is where I need i to increase each time
for i in range(10):
    get_url()

My goal is for get_url() to run 10 times, each time printing the response associated with the increasing i value. Sorry if this is worded poorly, I am a total beginner and 100% self taught. Thanks in advance!

A: Add i as an argument to get_url:
def get_url(i):

and then add it to your get_url call in your for loop:
for i in range(10):
    get_url(i)


text:
Q: Why store the old frame pointer when go to next stack frame I study the x86 assembly recently, and not understand why we have to do push ebp
when entering a new function.
From the survey, I can see the need for ebp is because that it can easily access the arguments of function call and the local variables in this new callee.
But I don't know why we have to store the old frame pointer when go to the new stack frame?
Is that because doing so will make stack trace easier for debugging?
The following is my test code:
foobar:
.LFB0:
    .cfi_startproc
    push ebp                 #Why do this here??
    ....
    ....
    mov ebp, esp

Thanks in advance

A: You don't even have to use a frame pointer, the calling convention doesn't mandate that and optimized code frequently doesn't. What the calling convention does prescribe though is that some registers are callee-saved, that is they must be preserved for the caller. This normally includes ebp. This requirement may be fulfilled by pushing/popping it.
As a side effect, if you do use frame pointers and you do know the structure of the caller, you may use it to access its frame. This is however not typically used.


text:
Q: Como funciona o ciclo de vida e a visibilidade do objeto Flask.g? No Flask há um objeto chamado g ou Flask.g que segundo a documentação é usado para armazenamento de dados. E este objeto é usado quando se atribui algo para ele.
Por exemplo:
def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

Acima em g.db é guardada uma instancia de acesso a base de dados. Entretanto, eu tenho algumas dúvidas em relação ao escopo de visibilidade e o ciclo de vida deste objeto g durante o seu uso.
Dúvidas

*

*O objeto g é visível somente no escopo da requisição e ele é
liberado da memória assim que a requisição é concluída?

*O objeto g é visível entre Blueprints?

*O ciclo de vida de g é para todo o contexto da aplicação?

A: *

*O objeto g é visível somente no escopo da requisição e ele é
liberado da memória assim que a requisição é concluída?

Sim.

*O objeto g é visível entre Blueprints?

Sim.  Ele existe enquanto se estiver na mesma requisição - então se em um método de view, você chamar via Python, como uma função, uma função que funcione como view em outro blueprint, ela vera o mesmo "g".
No entanto, naturalmente cada requisição acessa apenas um blueprint - onde está configurada a view que respondeu àquela requisição. Uma outra requisição que chame uma função de view em outro blueprint vai "enxergar" um outro objeto "g", diferente do da primeira. E isso é assim ,mesmo que sejam requisições assíncronas feitas quase ao mesmo tempo, e sejam processadas ao mesmo tempo no servidor: requisições diferentes vão ver diferentes objetos de contexto g.

*O ciclo de vida de g é para todo o contexto da aplicação?

O "g" é acessível em qualquer parte e qualquer função da aplicação - mas, de novo, cada requisição vai "ver" um objeto diferente ao fazer "flask.g".
No começo do Flask, o flask.g era simplesmente uma variável do tipo thread.local - hoje, com mais formas de atender requisições simultâneas em produção do que simplesmente uma em cada thread, os servidores de aplicação tem que cuidar para que todo o código relacionado a uma requisição veja uma cópia de "g".
A documentação oficial está aqui: http://flask.pocoo.org/docs/1.0/appcontext/#storing-data
O que causa estranheza sobre o "g" é que de fato não é assim que funcionam variáveis normais - mas é exatamente assim que funcionam os objetos do tipo thread.local.  Criei aqui um pequeno script que demonstra como os atributos dentro de um objeto do tipo threading.local são únicos em cada thread:
import threading
import time

def worker(number, pause):
    time.sleep(0.1)
    espaco.teste = number
    print(f"thread {number}: Valor de espaco.teste {espaco.teste}")
    time.sleep(pause)
    print(f"thread {number}: Valor de espaco.teste {espaco.teste}")

def main():
    global espaco
    espaco = threading.local()
    espaco.teste = 0
    t1 = threading.Thread(target=worker, args=(1, 1.0))
    t2 = threading.Thread(target=worker, args=(2, 0.5))
    print(f"thread princial. Espaco.teste: {espaco.teste}")
    t1.start()
    t2.start()
    time.sleep(0.2)
    print(f"thread principal. Espaco.teste: {espaco.teste}")

    t1.join()
    t2.join()

main()

A saída desse script fica assim:
(env) [gwidion@village tmp01]$ python3 bla10.py
thread principal. Espaco.teste: 0
thread 1: Valor de espaco.teste 1
thread 2: Valor de espaco.teste 2
thread principal. Espaco.teste: 0
thread 2: Valor de espaco.teste 2
thread 1: Valor de espaco.teste 1


text:
Q: SQL imports missing tables I am doing the export from Magento database on one instalation via phpMyAdmin, and I have tried exporting it in .sql and in tar.gz.
When I import that database in another instalation, I get no errors but there are tables missing, so I have only half of the tables and I see that after letter L (log_visitors table) there are no tables.
Its very strange, could someone give me idea what is it about?

A: On my version of phpMyAdmin, there is a checkbox with the following text on the Import page:
Allow the interruption of an import in case the script detects it is close to the PHP timeout limit. (This might be good way to import large files, however it can break transactions.)
Make sure that checkbox is unchecked (by default it is checked), else it may be causing your problem.

A: So we turned on the "enclose in transaction" and "disable foreign keys" checkfields on phpMyAdmin while exporting, and also seperated export in two .sql files. It worked.
Note that the problem wasnt standard php timeout or standard phpMyadmin limitations on uploading big files, as we previousuly also tried bigdumb and ssh commands for import and it didnt worked.

A: As @Willem stated, you could have that option checked when you import the sql file.
But if you're still not be able to import it after unchecking that option, this means that the file you are importing is too big.
In this case you can use the mysql command line utility, if you have SSH access to your server or you can try bigdump, a php script that let's you import a database splitting the SQL query in chunks!
Hope it helps :)


text:
Q: How to batch delete foreign language in subtitle I have some sample like this:
2
00:01:32,288 --> 00:01:33,208
¬O¥LÌ¶Ü¡H
How are you?

3
00:01:36,768 --> 00:01:39,648
€Ñ°Ú¡A¥LÌ¥ŽºâŽN³o»ò°µ¶Ü¡H
âŽN³o»ò°µ¶Ü¡H
I am fine
And you ?

--------------------Here is my solution but it's incomplete
#!/usr/bin/perl -w
$lineIndex = 0;
while($line=<>){
    $lineIndex++;   #line index start from 1
    $content{$lineIndex}=$line;  #copy to content
    for($i = 0; $i < length ($line); $i++){
        $char = substr $line,$i,1;
        if($char =~ /\W/){
            #print $char;
            $count{$lineIndex}++; #how many special char this line
        }
    }
}
# if line contains more than 14 special char,then skip
print "\n";
for $i (keys %count){
    if($count{$i} > 14){       #<----------------see here
        delete $content{$i};#delete from content
    }
}

for $j (sort keys %content){ #output
    print $content{$j};
}

my solution has this problem:
���O�J�b�յۺ��X is miss match, because its length <= 14
if change threshold to small number eg.6 string like 00:01:33,208 will be matched, thus delete from content
Is there a good way to check char in utf-8 ?

A: Here's a much simpler solution:
while($line = <>) {
    print $line unless $line =~ /[^\x00-\x7e]/;
}

The character set [\x00-\x7e] covers all basic ASCII characters (including control characters).

A: #!/usr/bin/perl -w
$lineIndex = 0;
$flag = 1;
while($line=<>){
    $line = join('',$line);
    $lineIndex++;
    if($line =~ /\d\d:\d\d:\d\d,\d\d\d/){
    print $line;
    next;
    }
    for($i = 0; $i < length ($line); $i++){
        $char = substr $line,$i,1;
        if($char !~ /[\w ,.;!?'\-\r\n]/){
            $flag = 0;
        last;
        }else{
        $flag = 1;
        }
    }
    if($flag == 1){
       print $line;
    }
}


text:
Q: Exercise question on transitivity on embedding one space into another. For the following question:

Let $(X,T)$, $(Y,U)$, and $(Z,V)$ be topological spaces such that there is an embedding of $X$ in $Y$ and an embedding of $Y$ in $Z$.   Prove that there is an embedding of $X$ in $Z$.

I would like to know if my approach is correct. Forgive me if I am insisting on being pedantic in writing out all the details.  I am hoping if I got the details correct.
Since $X$ is an embedding in $Y$, then for every open subset $P$ of $X$ and some open $Q\in U$, $Q\subset Y$, (can I shorten this to "an open $Q\in (Y,U)$" instead?), there exists a homeomorphic mapping $f:X\rightarrow f(P)$ where $f(P)=f(X)\cap Q$.
Similarly, $Y$ is an embedding in $Z$, for every open subset $W$ of $Y$ and some open $M\in V$, $M\subset Z$. there exists a homeomorphic mapping $g:Y\rightarrow g(W)$ where $g(W)=g(Y)\cap M.$  So in particular, we can let the open subset $W=f(P)$, then $g\circ f:X\rightarrow g(f(P))\subset g(f(X)),$ where $g(W)=g(f(P))=g(f(X)\cap Q))=g(f(X))\cap g(Q)=g(Y)\cap M.$  Hence we have $X$ is an embedding in $Z$.  Thank you in advance.

A: As X embeds into Y, there is a homeomorphism f:X -> f(X).
As Y embeds into Z, there is a homeomorphism g:Y -> g(Z).
Show that h, the restriction of g to f(X),
is a homeomorphism h:f(X) -> h(f(X)).
Conclude h$\circ$f:X -> h(f(X)) is a homeomorphism,
that X embeds into Z.