text:
Q: dynamic arrays c++ Access violation writing location What is wrong with my code ? I have the error like this.
Unhandled exception at 0x00d21673 in mnozenie_macierzy.exe : 0xC0000005: Access violation writing location 0xcdcdcdcd.
It create the first array and the half to the second.  The program multiplies arrays.
Sorry for my English if It isn't correct. I hope you understand me.
#include <iostream>
#include <time.h>

using namespace std;

void losowa_tablica(int **tab1, int **tab2, int a, int b, int c, int d)
{
    int i, j;
    for(i=0; i<a; i++)
    {
        cout << endl;
        for(j=0; j<b; j++)
        {
            tab1[i][j]=rand();
            cout << "tab1[" << i << "][" << j << "] : \t" << tab1[i][j] << "\t";
        }
    }
    cout << endl;
    for(i=0; i<c; i++)
    {
        cout << endl;
        for(j=0; j<d; j++)
        {
            tab2[i][j]=rand();
            cout << "tab2[" << i << "][" << j << "] : \t" << tab2[i][j] << "\t";
        }
    }
    cout << endl << endl;
}
int **mnozenie(int **tab1, int **tab2, int a, int b, int c, int d)
{
    int g, suma, i, j;
    int **mac=new int*[a];
    for(int i=0; i<d; i++)
        mac[i]=new int[d];
    for(i=0; i<a; i++)
        for(j=0; j<d; j++)
        {
            g=b-1, suma=0;
            do
            {
            suma+=tab1[i][g]*tab2[g][j];
            g--;
            }while(g!=0);
            mac[i][j]=suma;
        }
    return mac;
}

int main()
{
    int a,b,c,d;
    cout << "Podaj liczbe wierszy pierwszej macierzy: " << endl;
    cin >> a;
    cout << "Podaj liczbe kolumn pierwszej macierzy: " << endl;
    cin >> b;
    cout << "Podaj liczbe wierszy drugiej macierzy: " << endl;
    cin >> c;
    cout << "Podaj liczbe kolumn drugiej macierzy: " << endl;
    cin >> d;
    int **tab1=new int*[a];
    for(int i=0; i<b; i++)
        tab1[i]=new int[b];
    int **tab2=new int*[c];
    for(int i=0; i<d; i++)
        tab2[i]=new int[d];
    losowa_tablica(tab1, tab2, a, b, c, d);
    if ( b==c )
    {
        cout << "Mnozenie wykonalne" << endl;
        int **mno=mnozenie(tab1, tab2, a, b, c, d);
    }
    else cout << "Mnozenie niewykonalne" << endl;
    system("pause");
}

A: Your code yields undefined behavior:
int **tab1=new int*[a]; // allocating an array of 'a' elements
for(int i=0; i<b; i++)  // if b > a then the next line will eventually yield UB
    tab1[i]=new int[b];

int **tab2=new int*[c]; // allocating an array of 'c' elements
for(int i=0; i<d; i++)  // if d > c then the next line will eventually yield UB
    tab2[i]=new int[d];

int **mac=new int*[a];  // allocating an array of 'a' elements
for(int i=0; i<d; i++)  // if d > a then the next line will eventually yield UB
    mac[i]=new int[d];

In practice, the above code will most likely perform a memory access violation at some point.


text:
Q: Question about an Intel USB Host Controller power supplied per USB port I had a general question regarding the Intel(R) 82801FB/FBM USB Universal Host Controller (ICH6). The ICH6 has five USB Host controllers in it, with (I'm assuming) two physical USB ports per controller.
My Question is, does the ICH6 or any Intel SouthBridge supply up to 500mA per physical USB port, or does it share the 500mA per Host controller between the two USB ports on each controller?

A: If you read the document that you linked in, you'll find that the ICH6 itself does not supply the current for the USB port at all, as there's no pin for that on the chip. Instead, an external circuit is used for that. This is a pretty standard way to implement power to USB host ports.
There are several ways to implement the USB power supply, the simplest way is to connect it directly or through a PTC to +5V, like in Raspberry Pi:

This way you may draw from the USB port as much as the power supply (or the PTC) allows, and a short circuit will likely disrupt the operation of the host.
Or a special USB load switch IC may be used, which can limit the current to some fixed or configurable value and/or may be used to completely switch off the power to that port, like the SY6280 in Marsboard:

There are also USB load switch ICs that are able to indicate overcurrent situation back to the host, like the LM3526 in an LPC17xx board:

So, how much current you may draw from your USB ports without getting into trouble, and what happens if you draw too much, totally depends on the circuit used to power your ports (and sometimes the software configuration as well), outside your SouthBridge. You may examine your board and try to trace the USB power lines to see what ICs are there (they are usually very close to connectors), and then reading the data sheets might give you some clue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to take a subset of an object using an interface? Suppose I have this class and interface
class User {
    name: string;
    age: number;
    isAdmin: boolean;
}

interface IUser {
    name: string;
    age: number;
}

And then I get this json object from somewhere
const data = {
    name: "John",
    age: 25,
    isAdmin: true
}

I want to subset data using IUser and remove the isAdmin property like this
let user = subset<IUser>(data);
// user is now { name: "John", age: 25 }
// can safely insert user in the db

My question is how do I implement that function in TypeScript?
function subset<T>(obj: object) {
    // keep all properties of obj that are in T
    // keep, all optional properties in T
    // remove any properties out of T
}

A: There's no way to do that which is better than:
function subset(obj: IUser) {
    return {
        name: obj.name,
        age: obj.age
    }
}

The typescript interfaces don't exist at runtime (which is when subset is invoked) so you cannot use the IUser interface to know which properties are needed and which aren't.
You can use a class which does "survive" the compilation process but:
class IUser {
    name: string;
    age: number;
}

Compiles to:
var IUser = (function () {
    function IUser() {
    }
    return IUser;
}());

As you can see, the properties aren't part of the compiled output, as the class members are only added to the instance and not to the class, so even a class won't help you.
You can use decorator and metadata (more on that here) but that sounds like an overkill for your scenario.
Another option for a more generic subset function is:
function subset<T>(obj: T, ...keys: (keyof T)[]) {
    const result = {} as T;

    keys.forEach(key => result[key] = obj[key]);
    return result;
}
let user1 = subset(data, "name", "age");
let user2 = subset(data, "name", "ag"); // error: Argument of type '"ag"' is not assignable to parameter of type '"name" | "age" | "isAdmin"'


text:
Q: alphabetical array in user given amount of columns I have this assignment that makes me have to put a set of counties in a user given amount of columns, it doesn't matter about rows, it just needs to be in a certain amount of columns and needs to be in alphabetical order going across like this, i don't understand how to put the list into that user given amount of columns,
import java.util.Scanner;
public class Program {

    public static void main(String[] args) {
        String [] counties = {"Arkansas\t", "Ashley\t", "Baxter\t", "Benton\t", "Boone\t", "Bradley\t", "Calhoun\t",
                "Carroll\t", "Chicot\t", "Clark\t", "Clay\t", "Cleburne\t", "Cleveland", "Columbia\t", "Conway\t",
                "Craighead", "Crawford\t", "Crittenden", "Cross\t", "Dallas\t", "Desha\t", "Drew\t", "Faulkner\t",
                "Franklin\t", "Fulton\t", "Garland\t", "Grant\t", "Greene\t", "Hempstead", "Hot Spring", "Howard\t",
                "Independence", "Izard\t", "Jackson\t", "Jefferson", "Johnson\t", "Lafayette", "Lawrence\t", "Lee\t",
                "Lincoln\t", "Little River", "Logan\t", "Lonoke\t", "Madison\t", "Marion\t", "Miller\t", "Mississippi",
                "Monroe\t", "Montgomery", "Nevada\t", "Newton\t", "Ouachita\t", "Perry\t", "Phillips\t", "Pike\t",
                "Poinsett\t", "Polk\t", "Pope\t", "Prairie\t", "Pulaski\t", "Randolph\t", "Saline\t", "Scott\t", "Searcy\t",
                "Sebastian", "Sevier\t", "Sharp\t", "St. Francis", "Stone\t", "Union\t", "Van Buren", "Washington",
                "White\t", "Woodruff\t", "Yell"};

        Scanner col = new Scanner(System.in);
        double x = 0;
        x = col.nextInt();
        for(int c = 0; c < counties.length; c++) {

            for(int p = 0; p < x; p++) {

                System.out.println(counties[c]);
            }
        }
    }
}


text:
Q: Where to find "delegate" and "datasource" method documentation for NSTableView? I'm looking for Apple documentation regarding the "delegate" and "datasource" methods for NSTableView.  They don't appear in the NSTableView Class Reference for some reason.  Any idea where I can look?  Here's an example of one of them:
- (void)tableView:(NSTableView *)tableView
   setObjectValue:(id)object
   forTableColumn:(NSTableColumn *)tableColumn
              row:(NSInteger)row;

EDIT: It appears they appear in the NSTableView.h file with comments, though that's a pain to browse through.  I'd prefer a more user-friendly doc format, if it's available.  :)

A: The NSTableViewDataSource Protocol Reference and NSTableViewDelegate Protocol Reference contain what you're looking for. There are a number of links to these from the NSTableView Class Reference as well.

A: This is a common problem. For some reason, Apple documentation does not have a standardize way of linking to pages describing the delegate methods. In some cases, the delegate methods are included as a subheading in the class itself. In others, there are links to the delegate page in the sidebar. Sometimes the links are buried in the text. It's very frustrating.
Just a tip, the delegates are almost always referred and linked to in the "Overview" section of each class document page. If you can't find them in a logical place, look there.
If you need to search for the delegate methods, the protocol is almost always named in a standardized way with the class name followed by "delegate" or "datasource e.g. UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource. You should follow that standard when naming delegates in your own code.

A: Keep in mind that if you see a method some place in Xcode, and you want to know what it does, just hold command+option and double click on the method. That will take you to the documentation for that method.
Ultimately, that will lead you here.


text:
Q: Using join probability distribution Say I'm given a probability distribution of two random variables $A$ and $B$. What does it mean to calculate the join probability distribution of $3^{(A-B)}$?
The distribution is in fact discrete.

A: The problem does not specify whether $A$ and $B$ have discrete distribution, continuous distribution, or perhaps something more complicated. We deal with the continuous case.
Let $W=3^{A-B}$.  To find the density function of $W$, one approach is to find the cumulative distribution function $F_W(w)$ of $W$, and then differentiate. It is clear that $F_W(w)=0$ if $w\le 0$. So assume $w\gt 0$. We have
$$F_W(w)=\Pr(W\le w)=\Pr(3^{A-B}\le w)= \Pr\left(A-B\le \frac{\log w}{\log 3}\right).$$
At this point we cannot provide a detailed solution without some specific information about the joint distribution function of $A$ and $B$. But the calculation will involve an integration.
We will be integrating the joint density function $f(x,y)$ of $A$ and $B$ over the region where $x-y \le \frac{\log w}{\log 3}$. This is the region above a certain line with slope $1$, namely $y=x-\frac{\log w}{\log 3}$.

A: If $A$ and $B$ are integer-valued, then $C=3^{A-B}$ has values in the set $\{3^n\mid n\in\mathbb Z\}$ and, for every $n$ in $\mathbb Z$,
$$
\mathbb P(C=3^n)=\mathbb P(A-B=n)=\sum_{k\in\mathbb Z}p_{A,B}(n+k,k),
$$
where $p_{A,B}$ describes the joint distribution of $(A,B)$, that is, for every integers $i$ and $j$,
$$
p_{A,B}(i,j)=\mathbb P(A=i,B=j).
$$
Edit: Assume for example that $A$ and $B$ are independent Bernoulli random variables with respective parameters $a$ and $b$. This means that $\mathbb P(A=1)=a$, $\mathbb P(A=0)=1-a$, $\mathbb P(B=1)=b$, $\mathbb P(B=0)=1-b$, and finally that $\mathbb P(A=i,B=j)=\mathbb P(A=i)\mathbb P(B=j)$ for every $i$ and $j$.
Then $A-B$ takes values in $\{-1,0,1\}$ hence $C$ takes values in $\{\frac13,1,3\}$. To compute the distribution of $C$, first note that $\mathbb P(C=\frac13)=\mathbb P(A-B=-1)=\mathbb P(A=0,B=1)=(1-a)b$. Likewise,  $\mathbb P(C=3)=\mathbb P(A-B=1)=\mathbb P(A=1,B=0)=a(1-b)$. Finally,  $\mathbb P(C=1)=\mathbb P(A-B=0)=\mathbb P(A=1,B=1)+\mathbb P(A=0,B=0)=ab+(1-a)(1-b)$.
Edit: Continuing on the example,
$$
\mathbb E(C)=\tfrac13\cdot\mathbb P(C=\tfrac13)+1\cdot\mathbb P(C=1)+3\cdot\mathbb P(C=3),
$$
hence
$$
\mathbb E(C)=\tfrac13(1-a)b+ab+(1-a)(1-b)+3a(1-b)=(1+2a)(1-\tfrac23b).
$$


text:
Q: From Github to Existing Android project I am new to android development, so sorry if the question is not clear.
I want to use the widget "number-picker" it can be found on Github in this link. I know there is a way to import the git project to eclipse, but what I would like to do is to add it to my project that is already exist. I have tried manually add the classes and all included folders to that widget to my project, the problem is  there is no xml file that explains how to add this number-picker element to the activity.
Here is how I did it:
1. added the Scroller and the NumberPicker classes to the src folder under the project package.
2. added the drawable xmls, valuse and images.
3. added the jar file to Android Dependencies folder.
4. have added this to the activity xml file:
<com.example.mathgame.NumberPicker
android:id="@+id/numberPicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

and this to the main activity class:
package com.example.mathgame;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import com.example.mathgame.NumberPicker;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final NumberPicker np = (NumberPicker) findViewById(R.id.numberPicker);
        np.setMaxValue(24);
        np.setMinValue(1);
        np.setFocusable(true);

        np.setFocusableInTouchMode(true);

    }

}

when I run the app this is my exception from the logCat:
12-14 20:23:26.283: E/AndroidRuntime(29792): FATAL EXCEPTION: main
12-14 20:23:26.283: E/AndroidRuntime(29792): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mathgame/com.example.mathgame.MainActivity}: java.lang.ClassCastException: android.widget.NumberPicker cannot be cast to com.example.mathgame.NumberPicker

I would like to know what is the wright way to work with imported github projects and what should I do to fix this one. Thanks!!!

I found why the app crashed. it was because of number_picker.xml file, I have changed to com.example.mathgame.NumberPicker in some places. Now the app starts but the number picker looks odd (I have the button and some element near it). Here how it looks now:
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageButton android:id="@+id/np_increment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?attr/numberPickerUpButtonStyle"
        android:contentDescription="@string/np_number_picker_increment_button" />

    <view class="com.example.mathgame.NumberPicker$CustomEditText"
        android:id="@+id/np_numberpicker_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?attr/numberPickerInputTextStyle" />

    <ImageButton android:id="@+id/np_decrement"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?attr/numberPickerDownButtonStyle"
        android:contentDescription="@string/np_number_picker_decrement_button" />

</merge>

A: It's a library project.So you can add this project directally in your android proect.
Just Import a Library project.
Then goto the project properties->android->scroll down
add library project.
After all use this library classes for create object.


text:
Q: How to Sum amount of same role records? I want to get amount of same role in one sum. When I fetch a records of agent details introduced by some agent (11150000001). It will return lot of agents records with different role(1000,2000,3000,4000,5000,6000).
From that I need to get the agents business amount total. Now I'm getting it. But If there is some agent in same role I want to get that same role agent's amount in single amount, but I'm getting separately.
  //get all employee under one employee
            $rank1=''; $rank2='';$rank3='';$rank4='';$rank5='';$rank6='';
               $get_employee="SELECT emp_code,intro_code FROM emp_details WHERE intro_code='".$emp_code."'";
               $exe_employee=mysql_query($get_employee);

               while($fetch_emp=mysql_fetch_assoc($exe_employee))
               {
                     $total_amount1=0;
                     $role='';
                   $employee_code=$fetch_emp['emp_code'];
                   //echo $employee_code."
";
                   $get_premium="SELECT emp_code,user_role,premium_amount FROM business_details WHERE emp_code='".$employee_code."'";
                  //echo $get_premium."
";
                   $exe_premium=mysql_query($get_premium);

                   while($fetch_amount=mysql_fetch_array($exe_premium))
                   {
                      $total_amount1 +=$fetch_amount['premium_amount'];
                      $role=$fetch_amount['user_role'];
                   }
              }
      echo $role."-".$total_amount1."
";
       // Role-Amount
       // 5000-75000
        //  5000-105000
        //3000-15000

In the above image I'm getting 10,500 in rank 5, but I want to get the 75000+10500 in rank 5 column.
Below is my table structure:

A: The entire block of code than be replaced by a single SQL query. You want to create a pivot table.
Lets start by a relatively simple query that fetches the total premium_amount of all the employee-role combinations:
SELECT emp_code,
       user_role,
       SUM(premium_amount) AS total_amount
FROM business_details
GROUP BY emp_code, user_role;

This would yield something like this:
emp_code    | user_role | total_amount
-----------------------------------
15040000001 | 3000      |  15000
15040000001 | 5000      | 180000
11130000001 | 4000      |  30000
11130000001 | 1000      |   5000

This already contains all the information you want in your table, but not in the correct layout. Instead of using PHP to reformat this into the rows/columns you want for your table, SQL can do it for us.
Instead of grouping by user_role, we're going to specify the different values user_role can take as different columns:
SELECT emp_code,
       SUM(CASE WHEN user_role=1000 THEN premium_amount ELSE 0 END) AS rank1,
       SUM(CASE WHEN user_role=2000 THEN premium_amount ELSE 0 END) AS rank2,
       SUM(CASE WHEN user_role=3000 THEN premium_amount ELSE 0 END) AS rank3,
       SUM(CASE WHEN user_role=4000 THEN premium_amount ELSE 0 END) AS rank4,
       SUM(CASE WHEN user_role=5000 THEN premium_amount ELSE 0 END) AS rank5,
       SUM(CASE WHEN user_role=5000 THEN premium_amount ELSE 0 END) AS rank6
FROM business_details
GROUP BY emp_code;

The result would be:
emp_code    | rank1 | rank2 | rank3 | rank4 | rank5  | rank6
------------------------------------------------------------
15040000001 |     0 |     0 | 15000 |     0 | 180000 |     0
11130000001 |  5000 |     0 |     0 | 30000 |      0 |     0

Bonus advise
The PHP code you've posted contains a glaring security flaw that leaves your database (or probably your entire system) wide open to anyone. SQL injection is not fun to have in your web application! I've written about it in a previous answer.

A: Try this...
 $get_premium="SELECT emp_code,user_role,premium_amount,SUM(premium_amount) FROM business_details WHERE emp_code='".$employee_code."' group by user_role" ;


text:
Q: Check the count of records from the source file and the loaded target I have some source file suppose mydata.csv and my target table.I want to validate the record count whether it's same between the source file and the target table .The target table is in hive.
I have gone through this Link
I want something like
if [ eval target_count_command -eq count_from_csv ]
then
echo "File loaded fine"
else
"LOad Again"
fi

A: The easiest way to count records would be wc -l. If you have a variable with the number of CSV lines that should be referenced as "$count_from_csv" (with the quotes). You shouldn't need to use eval in this case; instead you'll want to run the command to count the target number of rows using "$(target_count_command).


text:
Q: Old school schema.ini question Anyone know how to specify a custom record delimiter in a schema.ini file? I need to import some data for an old system, and the source file uses pipes (|) as field delimieters and tilda's (~) as row delimiters. I've managed to get the field delimiters configured. Row delimiters anyone?
The current schema.ini file...

[sourcefile.txt]
ColNameHeader=false
Format=Delimited(|)
CharacterSet=ANSI
Col1=F1 text
Col2=F2 text
Col3=F3 text
Col4=F4 text
Col5=F5 text
...

Oh, and yes, it has to be done this way. I can't work around it by importing it through some other means...

A: no chance: see the grammar of ODBC text driver text files, especially these 2 lines:
delimited-text-line ::=
   blank-line |
   delimited-data [delimiter delimited-data]... end-of-line
end-of-line ::= <CR> | <LF> | <CR><LF>

ie. no setting for a custom row separator. also, no string anywhere related in the dll ...

A: If you have access to a copy of SQL Server, you might want to try the BCP utility which also handles row terminators.
https://learn.microsoft.com/en-us/sql/relational-databases/import-export/specify-field-and-row-terminators-sql-server
Back in the day these "old school" formats were relied on to provide consistency of format between different systems (Unix, DOS/Windows etc)


text:
Q: JavaScript Using the DOM methods and properties Hey guys i have some code here that is supposed to create HTML elements on the page that will display today date next to ID='today' How do use a textnode to write out to the ID? Thanks for any help! Here is my Full code:
HTML:

ToDo List - Date:

    <input type="button" id="additem" value="Add Item">

    <input type="button" id="sortitems" value="Sort and Display Items">

Javascript:
 var $ = function (id){
return document.getElementById(id);
   }

  var TodaysDate = function () {
  var myDate = new Date();

  var myMonth = myDate.getMonth() + 1;
  var myDay = myDate.getDate();
  var myYear = myDate.getFullYear();

  var myResponse = myMonth + "/" + myDay + "/" + myYear;

  var myPara = document.createElement("p");
  var myP = document.getElementById('today');
  myP.appendChild(myPara);

  var myText = document.createTextNode(myResponse);
  myPara.appendChild(myText);

  }
  window.onload = function ()
  {
   $("today").onload = TodaysDate;
   $("sortitems").onclick = sortItem;
   $("additems").onclick = addItem;
  }

A: Span onload? Onload is not triggered for a span. Other object do have a load event for example: windows/frames, body, link, script and images
Change
 $("today").onload = TodaysDate;

To
 TodaysDate();

and
var myPara = document.createElement("p");
var myP = document.getElementById('today');
myP.appendChild(myPara);
var myText = document.createTextNode(myResponse);
myPara.appendChild(myText);

To
var myPara = document.createElement("p");
var myText = document.createTextNode(myResponse);
myPara.appendChild(myText);

var myP = $('today');
myP.appendChild(myPara);

A: Try replacing this line:
$("today").onload = TodaysDate;

with this line:
TodaysDate();

because the SPAN tag does not support the onload event (see this answer).
Try it out here.


text:
Q: Including PDF pages from URL Does anyone know a way of including an external PDF document from a URL? When using pdfpages the following will not work:
\includepdf[pages=-]{http://www.mydomain.com/myfile.pdf}

My reason for asking is that I would like to avoid putting PDF files in my git repository.

A: The package pdfpages isn't capable of downloading pdf files. But you may write a command yourself that first downloads the requested files (e.g. using wget) and imports them afterwards in the known manner.
EDIT: See also the package download:
http://mirror.ctan.org/macros/latex/contrib/download/download.pdf
Using this it seems to be rather easy to create the necessary command as the command \download[filename]{url} does anything for you.

A: you can use ConTeXt, then it is possible:
\starttext
\insertpages[http://mirror.ctan.org/macros/latex/contrib/download/download.pdf][n=2][width=18cm]
\stoptext

for the first two pages.


text:
Q: storing 10 students information in a struct ,debug assertion failed error I wrote this but it keeps giving a debug assertion failed error after entering age.
I tried everything I knew and checked with online examples too but couldn't figure out what's wrong.
#include <stdlib.h>
#include <stdio.h>

struct student
{
    char name[50];
    float age;
    float grade[2];
    float gpa;

};

int main() {
    struct student s[10];
    int i;

    for (i = 0; i < 10; i++) {
        printf("please enter the %d student's name\n", i + 1);
        scanf_s(" %s ", &s[i].name, 20);
        printf("please enter the student's age\n");
        scanf_s("%f", &s[i].age);
        printf("please enter the physics score\n");
        scanf_s("%.2f", &s[i].grade[0]);
        printf("please enter the maths score\n");
        scanf_s("%.2f", &s[i].grade[1]);
        s[i].gpa = (s[i].grade[0] + s[i].grade[1]) / 2;
    }
    printf(" name\t\t age\t physics\tmaths\tgpa\n");
    printf("_____________________________________________________________________");
    for (i = 0; i < 10; i++) {
        printf("%s\t %f\t %.2f\t%.2f\t%.2f\n", s[i].name, s[i].age, s[i].grade[0], s[i].grade[1], s[i].gpa);
    }
    return 0;
}

A: I assume you're using Microsoft Visual Studio. You need to tell us such details.
You're misusing scanf_s and the compiler warned you about this. These warnings should be considered as errors.
Forget scanf_s and use scanf instead. To be able to do so, you need to put this at the very top of your source code:
#define _CRT_SECURE_NO_WARNINGS

Furthermore replace "%.2f" with "%f" and remember that scanf is not printf, some of the format specifiers as %s and %d are the same, whereas others are not. Also replace scanf(" %s ", &s[i].name); with scanf("%s", s[i].name);
Be aware that you cannot enter a name containing spaces with scanf and %s, use "%[^\n]" instead of %s (but that's an advanced topic), don't bother for the moment.
Anyway scanf is absolutely not suited for interative user input in real world programs, for small test programs it's OK.

A: #include <stdlib.h>
#include <stdio.h>

struct student
{
    char name[50];
    float age;
    float grade[2];
    float gpa;

};

int main() {
    struct student s[10];
    int i;

    for (i = 0; i < 10; i++) {
        printf("please enter the %d student's name\n", i + 1);
        scanf("%s", &s[i].name[0]);
        printf("please enter the student's age\n");
        scanf("%f", &s[i].age);
        printf("please enter the physics score\n");
        scanf("%f", &s[i].grade[0]);
        printf("please enter the maths score\n");
        scanf("%f", &s[i].grade[1]);
        s[i].gpa = (s[i].grade[0] + s[i].grade[1]) / 2;
    }
    printf(" name\t\t age\t physics\tmaths\tgpa\n");
    printf("_____________________________________________________________________");
    for (i = 0; i < 10; i++) {
        printf("%s\t %f\t %.2f\t%.2f\t%.2f\n", s[i].name, s[i].age, s[i].grade[0], s[i].grade[1], s[i].gpa);
    }
    return 0;
}

The code i just shared here is working how i believe you want it to.
Changes i made:
Used scanf instead of scanf_s;
Retired the spaces between the quotation marks on the first scanf();
Added [0] after &s[i].name in order to provide the scanf() function with a single address;
Also replaced %.2f with %f, the function scanf() doesn't allow it;


text:
Q: Issues with two forms submission in django one after another I'm working on forget password page in which the user first have to answer the question for enabling the textfields for creating new password.
Here, I have two forms, One for security question and second for password and confirm password.
Following is my forms.py
from django import forms
from .models import SecurityQuestions

class PasswordForm(forms.Form):
    password = forms.CharField(disabled=True, widget=forms.PasswordInput(attrs={'placeholder':'New Password'}))
    password_confirm = forms.CharField(disabled=True, widget=forms.PasswordInput(attrs={'placeholder':'Re-enter Password'}))

    def clean(self, *args,**kwargs):
        password = self.cleaned_data.get('password')
        password_confirm = self.cleaned_data.get('password_confirm')

        if password and password_confirm:
            if password != password_confirm:
                raise forms.ValidationError('Password Mismatch')
        return super(PasswordForm, self).clean(*args, **kwargs)

class PasswordVerificationForm(forms.Form):
    question = forms.ModelChoiceField(queryset=SecurityQuestions.objects.all(), empty_label=None, widget=forms.Select(attrs={'class':'form-control','id': 'sectxt'}))
    answer = forms.CharField(label='answer', widget=forms.TextInput(attrs={'placeholder':'Answer','id': 'anstxt'}))

Following is my views.py
from django.shortcuts import render, redirect
from .forms import PasswordForm, PasswordVerificationForm
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password
from .models import SecurityQuestions
from django.contrib import messages

@login_required
@csrf_exempt
def password_reset(request):
    form = PasswordForm(request.POST or None)
    form1 = PasswordVerificationForm(request.POST or None)
    if request.method == 'POST':
        if request.POST.get("verify", False):
            question = request.POST.get('question')
            answer = request.POST.get('answer')
            print("question",question)
            print("answer",answer)
            check = SecurityQuestions.objects.get(id=question) #id=1
            print(check.answer)
            if check.answer == answer:
                messages.success(request, 'Enter Your New Password', 'alert-success')
                form.fields['password'].disabled = False
                form.fields['password_confirm'].disabled = False
            else:
                redirect('/')
                messages.error(request, 'Incorrect Answer', 'alert-danger')
        if request.POST.get("create", False):
            if form.is_valid():
                print("For Changing Password...")
                password = form.cleaned_data.get('password')
                request.user.password = make_password(password)
                request.user.save()
                return redirect('/')
    else:
        form = PasswordForm()
        form1 = PasswordVerificationForm()
    return render(request,"forget_password.html", {"form": form, "form1":form1})

Following is my forget_password.html

Forgot Password

                                <form method="post">

                                  {{ form1.question | add_class:'form-control' }}

                                        {{ form1.answer | add_class:'form-control' }}

                                 {% if messages %}
                                    {% for message in messages %}

                                            ×
                                            {{ message }}

                                    {% endfor %}
                                {% endif %}
                            <input type="submit" name = "verify" formmethod="post" style="visibility: hidden;">

                        </form>
                        <form method="post">

                                        {{ form.password | add_class:'form-control' }}

                                        {{ form.password_confirm | add_class:'form-control' }}

                                        Cancel
                                        <button class="login-btn" type="submit" formmethod="post" name="create">Create</button>

                            </form>

If I enter the security answer first, based on the condition, if true, it enables the textfields for password and password_confirm.
But it's not creating the new password.
However, if I change the disabled = False in PasswordForm then it creating the new password successfully.
I want to know why it's not executing the code after the first form executes successfully.
Thanks!

A: You really should chain this into 2 urls, rather then trying 2 forms in one page. You can only submit one form and this is the problem you're facing. Once you have submitted the security question, you instantiate the form again with fields disabled:
form = PasswordForm(request.POST or None)

And now they do not get enabled, because the submit button called 'verify' from form1 is no longer present, so the code in that branch is not executed.
Let's say url is /password_reset/ -  a rough outline (untested):
@login_required
@csrf_exempt
def security_question(request):
    form = PasswordVerificationForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
             token = generate_strong_token()  # Implement: generate a strong token, url safe
             request.session["password_reset_token"] = token
             return redirect(f'/password_reset/{token}/')
    else:
        return render(...)

@login_required
@csrf_exempt
def change_password(request, **kwargs):
    form = PasswordForm(request.POST)
    token = request.session.get('password_reset_token')
    if token == kwargs['token']:
        if request.method == 'POST' and form.is_valid():
            del request.session['password_reset_token']

            # handle password change and redirect to wherever
        else:
            return render(...)
    else:
        raise SecurityError('Invalid token')

Your urls would be something like:
urlpatterns = [
    re_path('password_reset/(?P<token>[0-9A-F]{32})/', change_password)
    path('password_reset/', security_question)
]


text:
Q: What is meaning of 'sustainability is a style statement'? Source
I also wonder why they call 'sustainability' a 'statement.'

A: There has been a pretty big movement in reduce/reuse/recycle (i.e. The Green Movement) for quite some time. The article is essentially meaning that it is now fashionable to wear clothes that embrace the environment. So, clothes made from used water bottles are now becoming "in style" (popular) to wear for example. So, by wearing those clothes, you are also stating that you care about the environment.


text:
Q: Interfaces, static classes problem I am currently moving all my Game code to another package so that I can simply reuse it when I create another similar game.
I am having some problems with this though.
public interface Sprite {
...
}

abstract class AbstractSprite implements Sprite {
...
}

public interface Builder<T> {
    public T build();
}

class GameObjectImpl extends AbstractSprite {
    public static class GameObjectBuilder implements Builder<GameObjectImpl> {
    ...
    }
}

I am using a Builder Pattern to create my GameObjectImpl objects.  However, the client (the person using my game engine) will only have access to the Sprite interface.
How can I get the client to create GameObjectImpl using builder and only having access to the Sprite Interface?

A: You could add one more publicly visible class in the same package called Builders:
public final class Builders {

    public static Builder<? extends Sprite> newGameObjectBuilder() {
        return new GameObjectImpl.GameObjectBuilder();
    }

}

A: Why does Builder need to be an interface? Why not just make a builder-like factory? It seems like you want to tie the interface to this particular implementation.
public final class SpriteBuilder {
  private final Foo foo;
  private int property = 0;

  public SpriteBuilder(Foo importantMandatoryValue) {
    this.foo = importantMandatoryValue;
  }

  public SpriteBuilder setProperty(int theProperty) {
    this.property = property;
    return this;
  }

  public Sprite build() {
    return new GameObjectImpl(foo, property);
  }
}

You might call SpriteBuilder a GameObjectImplFactory... and make a similar class for each one of your Sprite implementations. You just have to make sure they will only return the Sprite type.
In your example, you would actually say something like public class GameObjectImplFactory implements Builder<Sprite>.
Hope this helps and makes sense :-).

A: I don't think you would want to make the Builder class generic... instead Builder.build() should be returning a Sprite object.  Right now the build() method is returning T which in your case is a GameObjectImpl


text:
Q: Pick image and crop image became low quality iOS I can pick the image from gallery and then crop the image but it becomes too low quality.
CGRect value=  AVMakeRectWithAspectRatioInsideRect(imageView.image.size, imageView.frame);
UIGraphicsBeginImageContext(imageView.image.size);
[imageView.image drawInRect:CGRectMake(0,0, value.size.width, value.size.height)];
UIImage *img= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Please any one help me figure out this issue.

A: You need to create your context with UIGraphicsBeginImageContextWithOptions, and pass In a scale of 0. The call UIGraphicsBeginImageContext does not allow for retina images.

A: Here is what I am doing in my one project:
   //*************** This one creates blury image so used contextWith options *****************************//

   // UIGraphicsBeginImageContext(CGSizeMake(signView.bounds.size.width, signView.bounds.size.height));

    UIGraphicsBeginImageContextWithOptions(signView.bounds.size, signView.opaque, 0.0);

    [signView.layer renderInContext: UIGraphicsGetCurrentContext()];
    // UIImage *imgMySignature = UIGraphicsGetImageFromCurrentImageContext();
    signView.img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

Here I am rendering image from UIView. signView is object of UIView.
Main concern is, use UIGraphicsBeginImageContextWithOptions instead of UIGraphicsBeginImageContext.


text:
Q: Specific response from MsSQL DB I am sending barcodes to a MsSQL DB using GET request via a Raspbery Pi using Python3
I have a second Pi which scans a barcode and send it to the same MsSQL DB. Now I need to get a message from the database if the barcodes have matched or not
Is it possible for a MsSQL engineer to input this "MATCH" or "NO-MATCH" in the response? SO that I can just use
requests.response(" ")

And get a "MATCH" or "NO-MATCH" message in the response?


text:
Q: Jenkins Pipeline env.JAVA_HOME differs from sh printenv Jenkins 2.2024.2
Kubernetes Plugin 1.22.0
The env.JAVA_HOME variable is getting set to a different value than what sh 'printenv' shows. I had thought env was a reflection of the environment. I also can't find where env.JAVA_HOME is set. It doesn't reflect the value in the Global JDK configurations. I also grepped the Jenkins Master root directory for openjdk and only found the correct value.
bash-4.4# grep openjdk *
config.xml:      <home>/usr/local/openjdk-8/jre</home>

Here's a pipeline demonstrating the behavior.
pipeline {
    agent {
        kubernetes { label 'java8-mvn3' }
    }

    stages {
        stage('test') {
            steps {
                container ('java8-mvn3') {
                    echo env.JAVA_HOME
                    echo "++++++++++++++++++++++++++"
                    sh 'printenv | grep JAVA_HOME'
                }
            }
        }
    }
}

** OUTPUT **
[Pipeline] echo
/usr/lib/jvm/java-1.8-openjdk
[Pipeline] echo
++++++++++++++++++++++++++
[Pipeline] sh
+ printenv
+ grep JAVA_HOME
JAVA_HOME=/usr/local/openjdk-8

A: As per man page : http://man7.org/linux/man-pages/man1/printenv.1.html

   NOTE: your shell may have its own version of printenv, which usually
   supersedes the version described here.  Please refer to your shell's
   documentation for details about the options it supports.

So you many need to go with specific shell with something like sh '''#!/bin/bash -c ...
Or as an another option export the one needed at global / stage definition environment level

A: The JAVA_HOME environment variable is set based on the Jenkins Master's environment. While the printenv shows the environment variables of the slave container.


text:
Q: Drupal hook_menu() not working I've tried the simplest examples of using hook_menu() posted here and on other Drupal forms and noting seems to work. My code, in: /sites/themes/mytheme/mymodule.module, is as follows:
<?php
function helloworld_menu() {
    $items = array();
    $items['hello'] = array(
        'title' => 'Hello world!',
        'type' => MENU_CALLBACK,
        'page callback' => 'helloworld_page',
        'access callback' => TRUE,
    );
    return $items;
}

function helloworld_page() {
    return 'Hello world !';
}

When I navigate to www.mydomain.com/hello I get a 404 error. I've tried enabling and disabling the module along with clearing the cache numerous times with no luck still. Here is some additional information about my environment:

*

*Running Drupal Commerce version 7.22

*I've enabled clean URLS and pathauto module

The end goal I'm trying to achieve is adding products to the cart with a link. I already have that part working so that I can pass product ID's into a function and add them to cart. I would be replacing helloworld_page() with my function and then changing $items['hello'] to $items['cart/add/%/%'], having two wildcards (product ID and quantity).

A: For a hook declaration like hook_menu, the function name should be like <your_module_name_here>_menu
This is where you are going wrong.
Your module name is mymodule.module so your hook_menu should be called, mymodule_menu
<?php
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['hello'] = array(
        'title' => 'Hello world!',
        'type' => MENU_CALLBACK,
        'page callback' => 'helloworld_page',
        'access callback' => TRUE,
    );
    return $items;
}

function helloworld_page() {
    return 'Hello world !';
}

Please correct the function name and clear your cache and try again.
ALso i noticed you put the module in an unconventional location.
Please move it to /sites/all/modules/custom/mymodule folder ( both mymodule.info and mymodule.module files ).


text:
Q: Schedule a future post to a Facebook group I'm trying to post a link to a facebook group:
$post_url = '/' . $my_group_id . '/feed';
$post_params = array('link' => $link, 'message' => $message)
$postResult = $facebook->api($post_url, 'post', $post_params);

This works great. Now I try to schedule this post to some future time.
So I add the parameter:
'scheduled_publish_time' => strtotime($schedule),

And now I get one of two errors. If I don't add anything more, I get
"(#100) You cannot specify a scheduled publish time on a published post"
And if I add the parameter:
'published' => false

then I get
"(#200) Unpublished posts must be posted to a page as the page itself."
However, this is a group, not a page, and to the best of my knowledge I cannot "post as the group itself", or can I?

A: I believe that based on the current design (as per 27-Oct-2013), I doubt there is any schedule for posting to group. The schedule is for page only.


text:
Q: .map with typescript, where to insert the interface? Trying a couple of things out with React, NextJS and Typescript.  I  am running into a problem where I keep getting the "x does not exist on type 'boolean | any[]'. Property 'x' does not exist on type 'false'.ts(2339)" error.  I just don't know where to put the interface to show it what types this is using.  Can anyone help me out?  Here is the offending code!
Articles.js
import React, { FunctionComponent } from 'react'; // we need this to make JSX compile
import useFetch from '../hooks/fetch'
type artProps = {
    title: string,
    author: string,
    date: number
}
type article = {
    title: string,
    author: string,
    date: number
}

export const Articles: FunctionComponent<{artProps}> = () => {
    const url = 'http://localhost:4000/kb'

    const data = useFetch(url)
    console.log(data)
    return (

            {data.map(articles) => {
                return (

                    {console.log(article)}

{article.title}

{article.body}

                )
            })}
            {/* {artProps.map(artProp => {
                return (

{artProp.title}

{artProp.author}

                )
            })
            } */}

    )
}
export default Articles

The hook
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const useFetch = (url) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log('fetch')
        axios.get(url)
            .then(res => {
                if (res.data) {
                    setData(res.data)
                    setLoading(false)
                }
            })
    }
        , []);

    return [data, loading];
};

export default useFetch

A: import React, { useState, useEffect } from 'react';
import axios from 'axios';

const useFetch = <T>(url: string): [T, boolean] => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log('fetch')
        axios.get(url)
            .then((res: any) => {
                if (res.data) {
                    setData(res.data)
                    setLoading(false)
                }
            })
    }
        , []);

    return [data, loading];
};

export default useFetch

Now add this to the parent component...
useFetch<ArrayTypeHere>(url)

now .map will infer the correct type and no need for annotations or type casting.


text:
Q: Can't drag element, by clicking on the slotted text (Vanilla JS) I created a draggable Web-Component with a slot:

const DragItemTemplate = document.createElement("template");
DragItemTemplate.innerHTML =
  `<style>` +
    `div{` +
      `background: gray;` +
      `width: 200px;` +
      `height: 50px;` +
      `padding: 5px;` +
      `margin: 5px;` +
      `cursor: move;` +
      `display: flex;` +
      `align-items: center;` +
      `justify-content: center;` +
    `}` +
  `</style>` +
  `<div draggable="true">` +
    `<slot></slot>` +
  `</div>`;

class DragItem extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({mode: "open"});
    this.shadowRoot.appendChild(DragItemTemplate.content.cloneNode(true));
  }
}

window.customElements.define("drag-item", DragItem);
<!DOCTYPE html>

  <drag-item></drag-item>
  <drag-item>Slotted Text</drag-item>

When I start dragging the component by clicking into the component (not the text) everything works as it should. But when I try to drag it by clicking on the text (slot) it doesn't work.
What could I do to make the whole component (including the text) draggable?

A: Set slot { pointer-events:none } so nothing in the <slot> triggers a mouse event, and thus your <div draggable captures the drag

<drag-item></drag-item>
<drag-item>Slotted Text</drag-item>
<drag-item>
Slotted Text
</drag-item>


text:
Q: How to find the best matching key in a PHP array I have an associative array in php. the keys are integers. how do i find the nearest key to any integer input?

A: a simple, but brute force method:
$distance = 1000000;  // initialize distance as "far away"
foreach ($array as $idx => $value)
   if (abs ($idx - $target_index) < $distance)
   {
      $distance = abs ($idx - $target_index);
      $best_idx = $idx;
   }

A: If the array keys are in order, you can use a more efficient algorithm (which may or may not make an appreciable difference depending on what this is for and how big the arrays are):
$arr = [2 => 'a', 4 => 'b', 7 => 'c'];
$input = 5;

if (isset($arr[$input])) {
    return $input;
}

foreach ($arr as $key => $value) {
    if ($key > $input) {
        if (prev($arr) === FALSE) {
            // If the input is smaller than the first key
            return $key;
        }
        $prevKey = key($arr);

        if (abs($key - $input) < abs($prevKey - $input)) {
            return $key;
        } else {
            return $prevKey;
        }
    }


text:
Q: Replace double-quote within a value attribute of an xml file in VB I have the following node in my xml file which is an export of another program.
I'll have to edit the xml file within my application so I can import it on a proper way.
The node:
<field name="memo" value="24-06-2004 Lorem ipsum dolor "sit" amit"/>

Eventually it has to become something like this
<field name="memo" value="24-06-2004 Lorem ipsum dolor "sit" amit"/>

Or
<field name="memo" value="24-06-2004 Lorem ipsum dolor 'sit' amit"/>

A: ResultString = Regex.Replace(SubjectString, _
    "(?<=         # Assert that this matches before the current position:" & chr(10) & _
    " ^           # Start of string                                      " & chr(10) & _
    " [^""]*""    # Match any number of non-quotes, then one quote       " & chr(10) & _
    " (?>[^""]*"" # Match pairs of quotes,                               " & chr(10) & _
    "    [^""]*"" # optional non-quotes in-between                       " & chr(10) & _
    " )*          # any number of times.                                 " & chr(10) & _
    " [^""]*      # Match any number of non-quotes                       " & chr(10) & _
    ")            # End of lookbehind assertion                          " & chr(10) & _
    """           # MATCH ONE QUOTE                                      " & chr(10) & _
    "(?!          # Assert that the following cannot match here:         " & chr(10) & _
    " \s+         #  Whitespace                                          " & chr(10) & _
    " \w+=        #  An identifier like value=                           " & chr(10) & _
    "|            # or                                                   " & chr(10) & _
    " \s*         #  optional whitespace                                 " & chr(10) & _
    " [/?]?       #  followed by either / or ? or nothing                " & chr(10) & _
    " >           #  followed by >                                       " & chr(10) & _
    ")            # End of lookahead assertion.                          " & chr(10) & _
    "|            # OR do the same in the other direction:               " & chr(10) & _
    "(?<!\w+=)""(?=[^""]*""(?>[^""]*""[^""]*"")*[^""]*$)", _
    """, RegexOptions.IgnorePatternWhitespace)


text:
Q: Sort and select from a complex nested dictionary using heapq I have the following nested dictionary:
a={'2020-12-08':
        {'navi.o_efx': {'coint_value': 0.923033, 'hl_value': 0.475025},
        'stm.n_efx': {'coint_value': 0.915424, 'hl_value': 0.294162},
        'kioo.o_efx': {'coint_value': 0.92575, 'hl_value': 0.369817}},
   '2020-09-24':
        {'navi.o_qrvo.o': {'coint_value': 0.919749, 'hl_value': 0.215322},
        'qrvo.o_efx': {'coint_value': 0.976447, 'hl_value': 0.11208},
        'navi.o_stm.n': {'coint_value': 0.974414, 'hl_value': 0.168408},
        'qrvo.o_stm.n': {'coint_value': 0.964797, 'hl_value': 0.14407},
        'stm.n_efx': {'coint_value': 0.935519, 'hl_value': 0.166952}},
   '2020-11-01':
       {'qrvo.o_stm.n': {'coint_value': 0.95096, 'hl_value': 0.104152}}
   }

I wanted to use heapq to sort on the basis of 'hl_value' and chose the smallest 2 sub-dictionaries for a particular date. For example, the final output should be as below:
a={'2020-12-08':
        {'stm.n_efx': {'coint_value': 0.915424, 'hl_value': 0.294162},
        'kioo.o_efx': {'coint_value': 0.92575, 'hl_value': 0.369817}},
   '2020-09-24':
        {'qrvo.o_efx': {'coint_value': 0.976447, 'hl_value': 0.11208},
        'qrvo.o_stm.n': {'coint_value': 0.964797, 'hl_value': 0.14407}},
   '2020-11-01':
       {'qrvo.o_stm.n': {'coint_value': 0.95096, 'hl_value': 0.104152}}
   }

I tried using the below code, but doesn't seem to work :
for k, v in a.items():
    for i_k, i_v in v.items():
        a[k][i_k] = dict(heapq.nsmallest(2, i_v.items(), key=i_v['hl_value']))

A: Here using heapq.nsmallest:
import heapq

a = {
    '2020-12-08':
        {
            'navi.o_efx': {'coint_value': 0.923033, 'hl_value': 0.475025},
            'stm.n_efx': {'coint_value': 0.915424, 'hl_value': 0.294162},
            'kioo.o_efx': {'coint_value': 0.92575, 'hl_value': 0.369817}
        },
   '2020-09-24':
        {
            'navi.o_qrvo.o': {'coint_value': 0.919749, 'hl_value': 0.215322},
            'qrvo.o_efx': {'coint_value': 0.976447, 'hl_value': 0.11208},
            'navi.o_stm.n': {'coint_value': 0.974414, 'hl_value': 0.168408},
            'qrvo.o_stm.n': {'coint_value': 0.964797, 'hl_value': 0.14407},
            'stm.n_efx': {'coint_value': 0.935519, 'hl_value': 0.166952}
        },
   '2020-11-01':
        {
            'qrvo.o_stm.n': {'coint_value': 0.95096, 'hl_value': 0.104152}
        }
}

for key in a:
    result = heapq.nsmallest(2, a[key].items(), key=lambda value: value[1]['hl_value'])
    a[key] = dict(result)

print(a)

Output
{'2020-12-08': {'stm.n_efx': {'coint_value': 0.915424, 'hl_value': 0.294162}, 'kioo.o_efx': {'coint_value': 0.92575, 'hl_value': 0.369817}}, '2020-09-24': {'qrvo.o_efx': {'coint_value': 0.976447, 'hl_value': 0.11208}, 'qrvo.o_stm.n': {'coint_value': 0.964797, 'hl_value': 0.14407}}, '2020-11-01': {'qrvo.o_stm.n': {'coint_value': 0.95096, 'hl_value': 0.104152}}}

Output (pretty printed via print(json.dumps(a, indent=4))):
{
    "2020-12-08": {
        "stm.n_efx": {
            "coint_value": 0.915424,
            "hl_value": 0.294162
        },
        "kioo.o_efx": {
            "coint_value": 0.92575,
            "hl_value": 0.369817
        }
    },
    "2020-09-24": {
        "qrvo.o_efx": {
            "coint_value": 0.976447,
            "hl_value": 0.11208
        },
        "qrvo.o_stm.n": {
            "coint_value": 0.964797,
            "hl_value": 0.14407
        }
    },
    "2020-11-01": {
        "qrvo.o_stm.n": {
            "coint_value": 0.95096,
            "hl_value": 0.104152
        }
    }
}


text:
Q: Custom authentication and parameter checking in Flask I am currently refactoring a Flask app I wrote about two years ago and I suspect having done a few things not as elegantly and clean as it would have been possible using the library. I would therefore ask for some advice on how to improve upon the status quo:

*

*The app provides a number of API-Endpoints each reachable via a route of the form /<category>/<endpoint> where <category> is one of 10 distinct categories.

*For each <category> I created a distinct Python module <category>.py, placed it an api/ subdirectory and a distinct flask.Blueprint (actually a subclass thereof, see later in the text) and registered that with the main app = Flask(__name__).

*Each module <category>.py contains a number of functions that serve as endpoints for the respective category and that are each decorated with a route-Decorator.

So far so good.
Each endpoint function accepts a number of parameters that may either be passed as parameters of a GET-request or as part of a parameter field in the JSON-payload of a POST-request. So before calling the respective endpoint function it is checked whether or not the correct number of parameters with the correct names are provided.
Also, the app needs to check whether or not the client is allowed to call a certain function. To do this, the environment variable SSL_CLIENT_CERT that was set by the webserver (lighttpd over FCGI in my case) is read and its fingerprint compared to some internal permission file.
Since I did not quite know where to put the logic to do the above I subclassed flask.Blueprint and wrote my own (modified) route decorator (custom_route). This decorator now either returns a custom made error response (flask.Response object) or a custom-made success response (thereby calling the endpoint function with the parameters passed from the client).
So a module category_xy.py looks something like this:
category_xy = CustomBlueprint('category_xy', __name__)

@category_xy.custom_route('/category_xy/some_endpoint',
                          auth_required=True,
                          methods=['GET', 'POST'])
def some_endpoint(foo, bar):
    # do stuff
    return '123'

With CustomBlueprint defined in a separate file as (partly pseudoish-code):
from flask import Blueprint, Response, g, request
from functools import wraps

class CustomBlueprint(Blueprint):
    def custom_route(self, rule, **options):
        def decorator(f):

            # don't pass the custom parameter 'auth_required' on to
            # self.route
            modified_options = dict(options)
            if 'auth_required' in modified_options:
                del modified_options['auth_required']

            @self.route(rule, **modified_options)
            @wraps(f)
            def wrapper():
                # do some authentication checks...
                if not authenticiated():
                    return Response(...)

                # check if correct paramters have been passed
                if not correct_paramters():
                    return Response(...)

                # extract parameter values from either GET or POST request
                arg_values = get_arg_values(request)

                # call the decorated function with these parameters
                result = f(*arg_values)

                return Response(result, ...)
            return wrapper
        return decorator

This works but it does not feel clean at all and I think that there should be a better and cleaner way of doing this. Putting all this logic in a custom decorator feels quite wrong.
Could somebody more experienced with Flask provide some thoughts and/or best practice?

A: As a start you can switch to Pluggable Views — API that allows you to write your view functions as classes:
from flask import Blueprint, Response, render_template
from flask.views import View

from models import db, CategoryXY # Let`s have here a database model

category_blueprint = Blueprint('category_xy', __name__)

class CategoryXYView(View):
    def get_list(self):
        items = db.session.query(CategoryXY).all()
        return render_template('category_xy_list.html', items=items)

    def get_one(self, item_id):
        item = db.session.query(CategoryXY).first()
        if item is None:
            return Response(status=404)
        return render_template('category_xy_edit.html', item=item)

    def dispatch_request(self, item_id):
        """Required method which handles incoming requests"""
        if item_id is None:
            return self.get_list()
        return self.get_one(item_id)

category_xy_view = CategoryXYView.as_view('category_xy')
category_blueprint.add_url_rule(
    'category_xy',
    view_func=category_xy_view,
    defaults={'item_id': None}
)
category_blueprint.add_url_rule(
    'category_xy/<item_id>',
    view_func=category_xy_view
)

It becomes really helpful when you have base view class with common methods (database objects handling, validation, authorization checking) and "category" classes are inherited from it:
class BaseView(View):
    model = None
    edit_template = None
    list_template = None

    def get_one(self, item_id):
        item = db.session.query(self.model).filter_by(id=item_id).first()
        if item is None:
            return Response(status=404)
        return render_template(self.edit_template, item=item)

    def get_list(self):
        items = db.session.query(self.model).all()
        return render_template(self.list_template, items=items)

    def dispatch_request(self, item_id):
        if item_id is None:
            return self.get_list()
        return self.get_one(item_id)

class CategoryXYView(BaseView):
    model = CategoryXY
    edit_template = 'category_xy_edit.html'
    list_template = 'category_xy_list.html'

category_xy_view = CategoryXYView.as_view('category_xy')
category_blueprint.add_url_rule(
    'category_xy',
    view_func=category_xy_view,
    defaults={'item_id': None}
)
category_blueprint.add_url_rule(
    'category_xy/<item_id>',
    view_func=category_xy_view
)

If one of categories has extended functionality you can just override one of the common methods:
class CategoryXXView(BaseView):
    model = CategoryXX
    edit_template = 'category_xx_edit.html'
    list_template = 'category_xx_list.html'

    def get_one(self, item_id):
        item = db.session.query(self.model).first()
        if item is None:
            return Response(status=404)
        xy_items = db.session.query(CategoryXY).all()
        return render_template(self.edit_template, item=item, xy_items=xy_items)

In order to automate routes generation you can write a metaclass for BaseView. Routes for every new class will be generated after class definition:
class ViewMeta(type):
    def __new__(mcs, name, bases, attributes):
        cls = type(name, bases, attributes)

        if cls.route is not None:
            view_function = cls.as_view(cls.route)
            category_blueprint.add_url_rule(
                cls.route,
                view_func=view_function,
                defaults={'item_id': None}
            )
            category_blueprint.add_url_rule(
                '{}/<item_id>'.format(cls.route),
                view_func=view_function
            )
        return cls

class BaseView(View):
    __metaclass__ = ViewMeta
    route = None
    model = None
    # Other common attributes

class CategoryXYView(BaseView):
    route = 'category_xy'
    model = CategoryXY


text:
Q: Use PaginatorHelper in Cells CakePhp 3 Hi I'm trying to use Paginator within a Cell the Paginator works rigth but the PaginatorHelper in the Template of the cell just doesn't work.
I'm using CakePhp 3.5
Here is my code
src/View/Cell/FinderCell.php
namespace App\View\Cell;
use Cake\View\Cell;
use Cake\Datasource\Paginator;
class FinderCell extends Cell {

    public function display() {
        $this->loadModel('Pokemon');
        $paginador = new Paginator();

        $pokemons = $paginador->paginate(
            $this->Pokemon->find()
        );

        $this->set(compact('pokemons'));
    }
}

src/Template/Cell/Finder/display.ctp
<?php
foreach ($pokemons as $pokemon) :
 ?>

    <?php echo $this->Html->image($pokemon->pokemon_image) ?>

<?php endforeach; ?>

        <?= $this->Paginator->prev('<< Anterior') ?>
        <?= $this->Paginator->numbers() ?>
        <?= $this->Paginator->next('Siguiente >>') ?>

<?= $this->Paginator->counter() ?>

I get this

A: If you want to use the helper, then you need to populate either the request object with the pagination parameters, which is what the paginator component would normally do for you:
// ...

$this->request = $this->request->withParam(
    'paging',
    $paginator->getPagingParams() + (array)$this->request->getParam('paging')
);

$this->set(compact('pokemons'));

or the paginator helper, which in turn sets the parameters on the request object:
// ...

$pagingParams = $paginator->getPagingParams();

$this->set(compact('pokemons', 'pagingParams'));

$this->Paginator->options(['paging' => $pagingParams]);

See also

*

*API > \Cake\Datasource\PaginatorInterface::getPagingParams()

*API > \Cake\View\Helper\PaginatorHelper::options()


text:
Q: How should I approach solving this floor function? Prove that for all $n \in \Bbb Z, \lfloor\sqrt {(n)}+ \sqrt {(n+1)} \rfloor = \lfloor \sqrt{4n+2}\rfloor$.
There must be some algebraic substitution?

A: Hint: for non-negative $n$, note that
$$
(\sqrt n + \sqrt{n+1})^2 = 2n + 1 + 2\sqrt{n^2 + n}
$$
and that $n^2 \leq n^2 + n < (n+1)^2$


text:
Q: use lzw with httpurlconnection in android we are trying to minimise the json data footprint for our android native application but, from the android developer pages we can see that by default android uses gzip compression
http://developer.android.com/reference/java/net/HttpURLConnection.html
However we were looking as to how to reduce the footprint further using lzw etc. since the json files we  send over are huge. If there is any way to get the same compression level in gzip that is also fine.
We are looking at the following method for customising the compression algorithm
http://twistbyte.com/applications/receive-compressed-json-with-android-app
If there is any android port for any such library please let us know.


text:
Q: Using a MySQL query with PHP I am creating a social network in which you can follow someone or be friends with them. The data you are able to see depends on the type of relationship you have with a user. Right now I have two tables to work with. Posts and Relationships.
Posts:
| user_id | post_id | story |
-----------------------------
|  1      |  1      | text. |
-----------------------------

Relationships:
| rel_id  | user_1  | user_2| status |
--------------------------------------
|  1      |  1      |   2   |    3   |
--------------------------------------

I also have a users table but I don't think that is important here. SO, basically I want to select all of the posts from users that I am friends with or following. User_2 is always the recipient of the relationship. The numbers 1, 2 and 3 represent the "status" of the relationship. 1 being you are following the recipient, 3 being you are friends, and 4 being you are following the recipient (the only difference is that you also have a pending friend request). I set up a SELECT QUERY but it is not working right.
$query=" SELECT * FROM posts LEFT JOIN relationships ON (posts.user_id=
relationships.user_2 AND relationships.user_1 = $user_id AND relationships.status = 4
OR 3 OR 1)";

It selects all the posts ever, twice. Why is that? I want it to only select the posts where the user posting the post is in a relationship with me, with a status of 1, 3, or 4. What might I be doing wrong? What are other ways to do this?
Thanks in advance!

A: That's not how OR works. Perhaps you should try IN.
... relationships.status IN (4, 3, 1) ...

As for the duplication, use DISTINCT.

A: Your OR in the WHERE clause condition is not in the correct syntax. try something like this:
SELECT  *
FROM    posts a
            LEFT JOIN relationships b
                ON a.user_id = b.user_2
WHERE   b.user_1 = $user_id AND
        b.status IN (1,3,4)

I suggest that you use PDO or MYSQLi extensions.
In PDO, it could look like this:
<?php
$stmt = $dbh->prepare("SELECT   *
                      FROM  posts a
                           LEFT JOIN relationships b
                                ON a.user_id = b.user_2
                     WHERE  b.user_1 = ? AND
                            b.status IN (1,3,4)");

$stmt->bindParam(1, $user_id);
$stmt->execute();

?>

Remember to always filter your inputs especially it is used querying your database.


text:
Q: Postal delivery robot using ubergraph clojure I am currently working on a route planning robot that will deliver parcels around an office. The office is set up as a graph with weighted edges using ubegraph.
I have a recursive function that can plan the route for a journey between any amount of rooms. However I'm now trying to add 'parcels' to the robot and I'm unsure if the way I'm going about it is correct.
(defn journey [start end]
  (alg/pprint-path (alg/shortest-path all-edges {:start-node start, :end-node end, :cost-attr :weight})))

   (defn fullpath [& stops]
  (doall (map (fn [a b] (journey a b)) stops (rest stops) )))

Above is the recursive function that at the moment takes in a set of stops and then rights out the route using journey. My idea is that instead of stops I pass in the robot to full path and robot will contain parcels and stops.
;;passed into fullpath to plan journey of robot
(def robot [parcels ;;needs to contain a set of parcels
            stops]) ;;stops are all of the end's gathered from parcel

The parcels will come from another structure.
    ;;passed into robot
(def parcel [start
             end
             delivered])

Is this a viable way of doing it or will it be impossible?
Any help greatly appreciated.


text:
Q: FormRequest that renders JS content in scrapy shell I'm trying to scrape content from this page with the following form data:
I need the County: set to Prince George's and DateOfFilingFrom set to 01-01-2000 so I do the following:
% scrapy shell
In [1]: from scrapy.http import FormRequest

In [2]: request = FormRequest(url='https://registers.maryland.gov/RowNetWeb/Estates/frmEstateSearch2.aspx', formdata={'DateOfFilingFrom': '01-01-2000', 'County:': "Prince George's"})

In [3]: response

In [4]:

But it's not working(response is None) plus, the next page looks like the following which is loaded dynamically, I need to know how to be able to access each of the links shown below with the following inspection(as far as I know this might be done using Splash however, I'm not sure how to combine a SplashRequest within a FormRequest and do it all from within scrapy shell for testing purposes. I need to know what I'm doing wrong and how to render the next page(the one that results from the FormRequest shown below)

A: The request you're sending is missing a couple of fields, which is probably why you don't get a response back. The fields you fill in also don't correspond to the fields they are expecting in the request. A good way to deal with this is using scrapy's from_response (doc), which can populate some fields for you already based on the information in the form.
For this website the following worked for me (using scrapy shell):
>>> url = "https://registers.maryland.gov/RowNetWeb/Estates/frmEstateSearch2.aspx"
>>> fetch(url)
>>> from scrapy import FormRequest
>>> req = FormRequest.from_response(
...             response,
...             formxpath="//form[@id='form1']", # specify the form on the current page
...             formdata={
...               'cboCountyId': '16',  # the county you select is converted to a number
...               'DateOfFilingFrom': '01-01-2001',
...               'cboPartyType': 'Decedent',
...               'cmdSearch': 'Search'
...             },
...             clickdata={'type': 'submit'},
...       )
>>> fetch(req)


text:
Q: Errors while using Interfaces.C.Strings.Char_Array_Access I am working on a C-ADA binding project where I need to pass a String declared in ADA side to C functions. In one of the ADA function, I declared a bounded char array as:
Str_C : Interfaces.C.Char_Array(1..23) := (others => Interfaces.C.nul);

And declared a vector of type Char_Array_Access as:
Ptr1 : Interfaces.C.Strings.Char_Array_Access := Str_C'Access;

But the compiler fails to compile at the above mentioned vector initialization and says "prefix of "Access" attribute must be aliased"
(I didn't aliased the char_array previously because char_array type is already and aliased array of char).
OK, let's add aliased keyword to the char array declaration as:
Str_C : aliased Interfaces.C.Char_Array(1..23) := (others => Interfaces.C.nul);

but it still fails with an error on the vector line as:

and a warning on the char array declaration line as:

Don't know what is going wrong here. Any help would be appreciated!

A: It is about the explict subtype constraints 1..23 on the left side, the subtype bounds on Str_C's type char_array, I think. The (private) pointer type chars_ptr is to unconstrained objects without bounds, reflecting C's char* (which knows no bounds). So, declare the object like this:
Str_C : aliased Interfaces.C.char_array  := (1..23 => Interfaces.C.nul);

Ptr1 : Interfaces.
    C.Strings.chars_ptr := Interfaces.C.Strings.To_Chars_Ptr(Str_C'access);

To_Chars_Ptr does the necessary pointer conversion. The declarations actually reflect the compiler's diagnosis.
It might be worth considering To_Ada, To_C, and Convention identifiers, together with a language feature: Ada passes arrays to C functions as C pointers. This is documented in LRM Annex B.3 (see Implementation Advice). So, you could store Ada strings, if you liked, on the Ada side.
Since the problem seems to also involve accessibility of pointed-to objects (e.g., of an array declared within a subprogram), here are some ways around that. See LRM 3.10.2 for details. The important question to ask is: "Do the objects exist when pointers to them could still be passed around?" Making sure that objects exist after a subprogram is done, say, can be achieved by allocating the arrays in the subprogram, as opposed to declaring them as variables on the stack. (Stack variables will essentially be gone after the call). Or, if you really know what you are doing, you can force the compiler to ignore that a pointer may outlive its object by using 'Unchecked_Access and not 'Access.
Ptr2 : Interfaces.C.Strings.chars_ptr :=   -- DANGER AHEAD!
  Interfaces.C.Strings.To_Chars_Ptr(Str_C'UNCHECKED_ACCESS);

Ptr3 : Interfaces.C.Strings.Chars_Ptr := Interfaces.C.Strings.To_Chars_Ptr
  (new Interfaces.C.char_array'(1..23 => Interfaces.C.nul));

Ptr4 : Interfaces.C.Strings.Chars_Ptr :=
  Interfaces.C.Strings.New_Char_Array((1..23 => Interfaces.C.nul));

A: The function New-String is the perfect tool for what you want to do :
with Interfaces.C.Strings; use Interfaces.C.Strings;

procedure Main_Ada is

Nom : constant chars_Ptr := New_string("Charles Dupont");
...


text:
Q: Centering initial row of sidebar Menu I've used this tutorial http://tympanus.net/codrops/2013/07/30/google-nexus-website-menu/ to create a Sidebar in my _Layout code. I'm trying to have the sidebar the li -> a -> "Test Sidebar" element to be on centered. May I ask how do I do that responsively. I can set it with a margin value but that's not very ideal.
_Layout.cshtml code

            Menu

                            <input placeholder="Search" type="search" class="gn-search">
                            Search

                            Popular

Settings

About us

Test Sidebar

     @RenderBody()

Codepen http://codepen.io/anon/pen/LNjYJd

A: some step u need to follow for your solution.
1 - Remove float:left from .gn-menu-main > li and add to .gn-menu-main li.gn-trigger.
2 - Replace display:block to display:inline-block
3 - Add text-align:center and font-size:0 (font size to set margen) to .gn-menu-main
4 - And give font:size according to your design li 13px to .gn-menu-main > li
Try by follow these steps may help you here is fiddle


text:
Q: i3wm: How to move windows between monitors? In a multiple monitor set-up with i3, how do you move windows between monitors using keybindings?

A: For windows and workspaces, you need to define a binding in your i3 config. Note: windows are called "containers", and monitors are called "outputs".
For moving windows:
move container to output left|right|down|up|current|primary|<output>
This is what I use in my i3 config:
# move focused window between monitors
bindsym $mod+Shift+greater move container to output right
bindsym $mod+Shift+less move container to output left

Note, you can also set a keybinding to send things to a specific monitor.
Moving focus between monitors works just like with one monitor. The focus will jump once you reach the "edge" of one monitor. The default binding is $mod+<arrow direction>. See also: moving workspaces between monitors.


text:
Q: 10.7.3 - Screensaver turns on while I'm in the middle of typing/mouse activity Has anyone seen this?  Let's say I set my screen saver to activate after 5 minutes.  Well I can be typing and using the mouse almost continuously for a period of time (5 minutes?  I'm not exactly sure) and all of the sudden the screen saver turns on.  If I'm in the middle of typing the screen saver then goes away almost instantly but I lose a few key strokes.
Is there an option I need to set to say don't turn on the screen saver until 5 minutes of inactivity?  Or is this a bug?

A: According to Apple Support:

If you use a screen saver, it starts automatically after your computer
  is inactive for a time. You can also choose a shortcut so your
  screen saver starts when you move the pointer to a corner of the
  screen.

*

*Choose Apple menu > System Preferences, click Desktop & Screen Saver, and then click Screen Saver.

*Open the Screen Saver pane of Desktop & Screen Saver preferences

*Click Hot Corners. Choose Start Screen Saver or Disable Screen Saver from the pop-up menu for a corner you want to use; and
  then click OK. To use the Command (⌘), Control
  (^), Option (⌥), or Shift (⇧) key
  together with a hot corner, press the key while the pop-up menu is
  open. For example, if you press the Shift key, the Start Screen Saver
  command changes to ⇧-Start Screen Saver.
To deactivate the screen saver and return to the desktop, press any
  key or move the mouse.

Additional screensaver configuration options for Lion are listed in this Apple Support KB.
This issue could definitely be a bug, but you could also check your screensaver configuration to determine whether you've turned on hot corners - it's possible that your mouse pointer may have triggered the screensaver. You can also choose to disable screensavers completely to avoid this issue.

A: I am having the same issue so can confirm it is a bug. I've disabled my hot corners just to make sure I'm not accidentally hitting them. I had my screensaver set to 30 mins, and it seems to happen every 30 mins.  So it seems that the computer thinks I'm away, even though I'm using it. This is reproducable by dragging the slider from 30 mins to 5 mins, the screensaver comes on automatically before I even release the mouse (from sliding the setting from 30 mins to 5 mins)
This is one strange bug.


text:
Q: create UUIDs for unique key-value pairs while preserving dict integrity I have a list of dicts
[{'fruit': 'apple', 'color' : 'green', 'UUID':''}, {'fruit': 'guava', 'color': 'green','UUID':''}, {'fruit': 'pear', 'color': 'green','UUID':''},{'fruit':'banana','color':'yellow'}]
and I'm trying to create UUIDs by color. For example, I'd want apple, guava, and pear, which all have the key-value pair 'color' : 'green' to share a UUID, while 'banana', which has the key-value pair 'color' : 'yellow' to have its own UUID.
It seems like I'd want to do some sort of groupby-esque operation on the list of dicts and then apply the UUID generator. Is this the right way to think about it? Or is there a smarter/easier/generally less dumb way of doing this? I'm having a hard time visualizing this, and any help would be appreciated.

A: uuidmap = {}
for d in L:
  if d['color'] not in uuidmap:
    uuidmap[d['color']] = generateUUID()
  d['UUID'] = uuidmap[d['color']]


text:
Q: Using a selection sort to sort an array in python. How can I optimize? Working on this challenge on HackerRank and got this code to pass 10 out of 15 test cases. It is failing due to timeout error which is HackerRank's way of telling you that the algorithm is not optimized. How can I optimize this code to run on larger input data?
The goal is to figure out the minimum number of swaps necessary to sort an unsorted array.
Update: Each element in the array is distinct.
def minimum_swaps(arr):
"""Returns the minimum number of swaps to re-oder array in ascending order."""

    swaps = 0
    for val in range(len(arr) - 1, 0, -1):

        # Index of max value
        max_pos = 0
        for index in range(1, val + 1):

            if arr[index] > arr[max_pos]:
                max_pos = index

        # Skip if value is already in sorted position
        if max_pos == val:
            continue

        arr[val], arr[max_pos] = arr[max_pos], arr[val]
        swaps += 1

    return swaps

A: Look at the code. It has 2 nested loops:

*

*The outer loop iterates over the positions val.

*The inner loop finds the index of the value that should be at the index val, i.e., max_pos.

It takes a lot of time just to find the index. Instead, I will compute the index of each value and store it in a dict.
index_of = {value: index for index, value in enumerate(arr)}

(note that because all values in arr are distinct, there should be no duplicated keys)
And also prepare a sorted version of the array: that way it's easier to find the maximum value instead of having to loop over the array.
sorted_arr = sorted(arr)

Then do the rest similar to the original code: for each index visited, use sorted_arr to get the max, use index_of to get its current index, if it's out-of-place then swap. Remember to update the index_of dict while swapping too.
The algorithm takes O(n) operations (including dict indexing/modifying), plus sorting cost of n elements (which is about O(n log n)).

Note: If the array arr only contains integers in a small range, it may be faster to make index_of an array instead of a dict.

A: The short answer is: implement merge sort. The bubble sort algorithm you are using has a O(n^2) running time, while merge sort has a O(log_2(n)) running time.


text:
Q: Get line-based output from pipe in real-time I want to read line by line output of the tcpdump subprocess in (near) real-time but I need the option to assess whether the pipe is empty (therefore the queue). The thread waits 0.5 seconds, gets all queued lines of output, processes it (e.g. mean distribution of packets over 0.5 seconds) and returns something.
Minimal non-working example:
millis = lambda: int(round(time.time() * 1000))
def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        print(millis())
        print(line)
        queue.put(line)
    out.close()

def infiniteloop1():
    p = Popen( [ 'sudo', 'tcpdump', '-i', 'wlan0', '-nn', '-s0', '-q', '-l', '-p', '-S' ], stdout=subprocess.PIPE, stderr=STDOUT)
    q = Queue()
    t = Thread(target=enqueue_output, args=(p.stdout, q))
    t.daemon = True # thread dies with the program
    t.start()

    while True:
        while True:
            # read line without blocking
            try:
                row = q.get_nowait() # or q.get(timeout=.1)
            except Empty:
                print('empty')
                break
            else:
                pass
        time.sleep(0.5)
thread1 = threading.Thread(target=infiniteloop1)
thread1.daemon = True
thread1.start()

The output while capturing a continuous stream of packages:
[...]
1552905183422
10:33:03.334167 IP 192.168.1.2.36189 > a.b.c.d.443: tcp 437
1552905183422
10:33:03.357215 IP a.b.c.d.443 > 192.168.1.2.36189: tcp 0
1552905183423
10:33:03.385145 IP 192.168.1.2.36189 > a.b.c.d.443: tcp 437
empty
empty
1552905184438
10:33:03.408408 IP a.b.c.d.443 > 192.168.1.2.36189: tcp 0
1552905184439
10:33:03.428045 IP 192.168.1.2.36189 > a.b.c.d.443: tcp 437
1552905184439
10:33:03.451235 IP a.b.c.d.443 > 192.168.1.2.36189: tcp 0
[...]

Notice the two consecutive "empty". The last packet before the first "empty" was captured 10:33:03.385145 by tcpdump and delivered to queue at 1552905183423 which took 38 ms. Between the two "emptys" no packets are delivered into the queue. The first package after the second "empty" was captured at 10:33:03.408408 and delivered 1552905184438, it was delivered 1 second after the previous packet but captured between the "emptys". Why is it not delivered between the "emptys"? This is not rarely happening but every second burst of poping the queue results in no packages being delivered, why is that?

A:
The first package after the second "empty" was captured at
  10:33:03.408408 and delivered 1552905184438, it was delivered 1 second
  after the previous packet but captured between the "emptys".

Given your code, the system time stamps are only calculated and printed if that iterator in for line in iter(out.readline, b'') returns a new item, so this is where the delay seems to be coming from.
I suspect stdio buffering to be the culprit. On Linux (i.e. libc/glibc), if the STDOUT descriptor refers to a TTY, line buffering is enabled. If it refers to something else (e.g. a pipe), the STDOUT descriptor is fully buffered; your process needs to fill 4096 bytes (default on Linux) before the write system call is invoked.
Very roughly calculated, based on the output you show here, your subprocess seems to generate ~65 bytes every ~0.025 seconds. Given a 4kB buffer, it would take ~1.625 seconds to fill it up and trigger the flush/write.
Reading from that subprocess.PIPE and sending the output to your main process' stdout takes a a lot less, hence you see the bursts with tcpdump output, that is ~25ms apart being printed (received from the stdout iterator) within a few microseconds, and your program subsequently waiting until the next 4kB are flushed.
If you have the possibility the install 3rd party packages (and use Python >= 2.7), you might want to look at pexpect. Childs of that package connect to a PTY, making the system treat them like interactive programs, hence their stdout descriptor is line-buffered.


text:
Q: Need to have a GMap without initializing to a specific location I am trying to implement a google map that is bound to an input field.
But i need the input field not to have an initial value, and the map to be initially set to a certain city.
Is that possible?
the input field has id "gmap-address".

    <input name="gmap-address" class="form-control" type="text" id="gmap-address" style="font-size:2em;height:3em;"/>

<input name="gmap-lat" type="text" id="gmap-lat"/>
<input name="gmap-long" type="text" id="gmap-long"/>
<input name="us9-city" type="text" id="us9-city"/>
<input name="us9-state" type="text" id="us9-state"/>
<input name="us9-zip" type="text" id="us9-zip"/>
<input name="us9-street1" type="text" id="us9-street1"/>

A: Looking at your code, the input field does not have any value initially.
As for getting the map to initially be set to a certain city: You can do this when you initiate the map like so:
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });
  }

For specifying the center of the map, you will need to use latitude,longitude coordinates. If you really need to use the name of a city, you can do so by first using the Geocoding API to geocode the city, then you can set the center of the map to the coordinates returned by the geocoder. I have demonstrated how this can be done in the following JSFiddle using Houston, TX as the city the map is initially set to:
https://jsfiddle.net/3qoub0nv/1/
I hope this helps!


text:
Q: How to query list of users and hours they worked today in microsoft team foundation server, tfs? In Team Foundation Server (TFS), currently I am able to query the work items (bugs, tasks) by @CurrentIterationPath and status (closed etc.). But I am in need of fetching all users who worked today and the number of hours they logged. Could anyone out there help please?
I am using tfs 2015.

A: CAVEAT what you ask is a bad practice and I always advise against. TFS is not a time entry tool: it is designed to support development team in being agile not to support accounting! If you need that there are tools that extend/integrate with TFS, designed for that purpose.
That said, there is no OOB report, query or API that will extract similar information.
A possibility is to use an Excel Pivot Table that reorder the export of a WIQL query. See here and here for Excel integration with TFS.
Another path is to write a SSRS custom report but I doubt it offers all data you asked for and it is a non trivial exercise IMHO.


text:
Q: pandas - draw a distribution of a column The DataFrame is as the following:

And I'd like to draw a distribution of population of the groupby geo_name, but when I use the following command:
df.hist(column='population')

The histogram is not each bar for geo_name's population:

For example, there should be two top bars from (Ont.) and (Que.), but there is only one bar which is much higher than others.
What's the matter? How to resolve it?

A: I think you're looking for a bar chart of populations, one bar per province, with provinces arranged along the horizontal axis. If so, try this:
df['population'].plot(kind='bar')


text:
Q: Compare Range between tables in Oracle SQL I have two tables CENTER and RANGE_CENTER. Based on the CENTER_ID from table 1 I need to find its corresponding ID.
Eg if Centreid is 2000 then it should display a100.Same way for all the records in table 1.
I am finding it difficult to write the query.
Could you please guide me on this.
DEPT    Center_Id
10  2000
10  2001
20  3001
20  2580

CENTER_FROM     CENTER_TO   ALLOCATION_ID
1999              2499       a100
2500              2999       b234
3000              3499       c199

Thanks

A: You can join the tables so the center_id from one table is between the center_from and center_to from the other table.
select c.dept,c.center_id,rc.allocation_id
from center c
join range_center rc on c.center_id between rc.center_from and rc.center_to

A: If you don't like joins, then you can use correlated subquery:
SELECT c.DEPT, c.Center_Id,
       ( SELECT ALLOCATION_ID FROM RANGE_CENTER r
         WHERE c.Center_Id BETWEEN r.CENTER_FROM AND r.CENTER_TO
       ) As ALLOCATION_ID
FROM CENTER c


text:
Q: ContentResolver Query on DocumentContract Lists all files disregarding selection Im trying to get all files from a directory which have a certain MIME Type - i want all images.
I had used some example code where you use MediaStore as URI but it later turned out difficult to filter that for the chosen directory because the URIs returned in the resultset have a different format than the URI i supplied...
So instead i found this example code https://github.com/googlesamples/android-DirectorySelection
it queries the DocumentContract on the selected subtree and now needs filtering for the desired MIME Type.
the problem is: no matter what i supply as selection argument it will always list all files/directories found in that directory.
i even tried "1=2" as selection and this still listed everything.
any ideas what im doing wrong??
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
                uri,
                DocumentsContract.getTreeDocumentId(uri)
            )
        val childCursor = contentResolver.query(
            childrenUri,
            arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME, COLUMN_MIME_TYPE),
            "$COLUMN_MIME_TYPE=?",
            Array(1){MimeTypeMap.getSingleton().getExtensionFromMimeType("jpg")},
            null
        )
        Log.i("ADDFOLDER", "files: ${childCursor.count}")
        try {
            while (childCursor.moveToNext()) {
                Log.d(
                    TAG, "found child=" + childCursor.getString(0) + ", mime=" + childCursor
                        .getString(1)
                )
            }
        } finally {
            closeQuietly(childCursor)
        }

A: FileSystemProvider doesn't support selection or sort args for children, it's broken.

https://github.com/aosp-mirror/platform_frameworks_base/blob/53a9ccaa926945149b4546c67b50ce1ae88ba777/core/java/com/android/internal/content/FileSystemProvider.java#L285
The base DocumentsProvider strips the selection args for a children query as well, so I wouldn't rely on it ever working. You could use the search documents Uri, which does do filtering, but still ignores the sort order (Edit: and more importantly, is a recursive search, so it'll search within any subfolders.)*

*From: https://www.reddit.com/r/androiddev/comments/b80qqt/weekly_questions_thread_april_01_2019/ek9oew6/


text:
Q: Is it possible and/or safe to use Parse to allow users to transfer money to eachother? In my app, I want users to be able to add money to their account, and send it to other members when certain services are rendered.
Is there a safe and straightforward to do this with Parse.com? If not, is there a third party someone can recommend?

A: Parse actually released something for mobile payment processing. It's called 'Stripe.' http://stripe.com/


text:
Q: Flutter gridview menu on tap function is not working I am trying to create an application in flutter latest version. I would like to create fragments instead of pages. Now in homepage fragment, I tried to make a gridview menu which has 6 menu item. I am stuck at onTap function because I wanted to move another fragment when the menu is tapped. its not working. I am sharing my code. Thanks in advance.
import 'package:flutter/material.dart';
import 'package:folder/fragments/fragment_form.dart';

class HomeFragment extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
        height: MediaQuery.of(context).size.height / 1,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomLeft,
            //stops: [0.1, 0.5, 0.7, 0.9],
            colors: [
              Colors.teal[50],
              Colors.cyan[50],
              Colors.blue[50],
            ],
          ),
        ),
        child: new Center(
          child: new HomepageFragment(),
        )
    );
  }

}

class HomepageFragment extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(20.0),
      child: new GridView.count(
        crossAxisCount: 2,
        children: <Widget>[
          MyMenu(titleText: "Add Complain", iconImage: Icons.add_box, iconColor: Colors.cyan, position: 0),
          MyMenu(titleText: "Log In", iconImage: Icons.account_box, iconColor: Colors.cyan, position: 1),
          MyMenu(titleText: "About App", iconImage: Icons.airplay, iconColor: Colors.cyan, position: 2),
          MyMenu(titleText: "How we Work", iconImage: Icons.alarm_on, iconColor: Colors.cyan, position: 3),
          MyMenu(titleText: "All Complains ", iconImage: Icons.apps, iconColor: Colors.cyan, position: 4),
          MyMenu(titleText: "Privacy", iconImage: Icons.assistant, iconColor: Colors.cyan, position: 5),
        ],
      ),
    );
  }
}

class MyMenu extends StatelessWidget {

  MyMenu({this.titleText, this.iconImage, this.iconColor, this.position});
  final String titleText;
  final IconData iconImage;
  final MaterialColor iconColor;
  final int position;

  _getMenuTem(position){
    switch (position) {
      case 0:
        return new FormFragment();
      case 1:
        return new FormFragment();
      case 2:
        return new FormFragment();
      case 3:
        return new FormFragment();

      default:
        return new Text("Something went wrong");
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Card(
      color: Colors.white,
      margin: EdgeInsets.all(10.0),
      child: InkWell(
        onTap: () => _getMenuTem(position),
        onLongPress: () => _getMenuTem(position),
        splashColor: Colors.green,
        child: new Center(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Icon(
                iconImage,
                size: 100.0,
                color: iconColor,
              ),
              Text(titleText, style: new TextStyle(fontSize: 17, color: Colors.teal[800])),

            ],
          ),
        ),
      ),
    );
  }
}

A: Your _getMenuTem method is returning a Widget so you can't get the beaviour you expected.
TO navigate to a new screen, you need to use the Navigator class:

Example :
Navigator.push(context,MaterialPageRoute(builder: (context) => NewScreen()));

I added a demo using your code as an example:
_getMenuTem(position, context) {
    switch (position) {
      case 0:
        // navigate to specific screen
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FormFragment(),
          ),
        );
        break;
      case 1:
        // navigate to specific screen
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FormFragment(),
          ),
        );
        break;
      case 2:
        // navigate to specific screen
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FormFragment(),
          ),
        );
        break;
      case 3:
        // navigate to specific screen
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FormFragment(),
          ),
        );
        break;
      default:
        return new Text("Something went wrong");
    }
  }


text:
Q: Getting SVG pie chart to only animate once I got this simple SVG pie chart loader (http://css-tricks.com/css-pie-timer/):
http://jsfiddle.net/frank_o/gFnw9/6/
How do I get it to only animate once? Bonus points for helping me remove unnecessary code.
HTML:
<svg width="250" height="250" viewbox="0 0 250 250">
  <path id="loader" transform="translate(125, 125) scale(.84)" />
</svg>

JS:
var $loader = $('#loader'),
    alpha = 0,
    pi = Math.PI,
    time = 5;

function draw() {
  alpha++;
  alpha %= 360;

  var r = ( alpha * pi / 180 ),
    x = Math.sin( r ) * 125,
    y = Math.cos( r ) * - 125,
    mid = ( alpha > 180 ) ? 1 : 0,
    animate = 'M 0 0 v -125 A 125 125 1 '
           + mid + ' 1 '
           +  x  + ' '
           +  y  + ' z';

  loader.setAttribute( 'd', animate );

  setTimeout(draw, time); // Redraw
};

draw.call(this);

A: To get it to animate only once you need to stop calling the setTimeout() once alpha is > 360. Then you need to make sure that the svg circle is fully drawn.
Here is a fiddle : http://jsfiddle.net/gFnw9/12/
var $loader = $('#loader'),
    alpha = 0,
    pi = Math.PI,
    time = 5;

function draw() {
  alpha++;

  var r = ( alpha * pi / 180 ),
    x = Math.sin( r ) * 125,
    y = Math.cos( r ) * - 125,
    mid = ( alpha >= 180 ) ? 1 : 0,
    animate = 'M 0 0 v -125 A 125 125 1 '
           + mid + ' 1 '
           +  x  + ' '
           +  y  + ' z';

    if (alpha < 360){
      setTimeout(draw, time); // Redraw
    }else{
        animate = "M 0 0 v -125 A 125 125 1 1 1 -.1 -125 z";
    }

  loader.setAttribute( 'd', animate );

};

draw.call(this);

A: Well, you definetly don't have to do this with SVG. Check out this great tutorial. it might help.
Tutorial


text:
Q: InfoPath 2013: Parent child InfoPath form I am trying to figure out how to implement Parent and child relationship in InfoPath 2013.
My scenario like this:
Create New Item (via InfoPath) Parent Form (I have Complete)
the Infopath contain the header for instance
ProjectId, ProjectName, and ProjectOwner, and task that need to complete for instance:

*

*Setup username

*Setup Phone

*Setup email account

Then i need to create Child Form (Not sure how)
The information include ProjectId, ProjectName, ProjectOwner retrieve from Parent Infopath Form, then i have series of task including:

*

*Induction Process

*Setting up payment detail

Please advise how i can achieve this in InfoPath 2013. Thank you