text:
Q: List vs Tuple sort performance first of all I realize that this has been covered before. And second my programming experience is extremely limited. However since I was so surprised to see such an increase in performance, and since I also have it relatively well benchmarked I thought that I would share the results.
Basically what I am doing is k-means clustering on a mesh on Rhinoceros with a script in Python (IronPython). Here is a screenshot of the results. And bellow is a benchmark of all the functions in my script.
CYCLE  4
GetProxy =  20.0
GetProxySeed =  10.0
BuildQueue =  0.0
AssignToRegion =  610.0009
SplitRegion =  10.0
RenumberSplitRegions =  30.0
FindAdjacentRegions =  10.0
FindRegionsToCombine =  130.0002
ReCombineRegions =  0.0
RenumberRegions =  0.0
ReGrowSeeds =  110.0002
CYCLE  4 TOOK =  940.0013
AssignToRegionTime Average over all cycles (20)=  613.8351

It can clearly be seen that AssignToRegion is the bottleneck. This is the function that assigns each face in the mesh to a cluster. Bellow is a "pseudo-code" of the steps involved:
It starts with a queue of structure [ [ error value, region index tag, face index] , ...]
equal in length to the number of regions. Then:

1. Pop item of least error.
2. Check if item has already been assigned to a region.
3. If not, append to the region of same tag.
4. Get adjacent faces minus faces already assigned to a region.
5. Update queue with new faces.
5.1. Get error of new faces. This basically compared the face's normal vector to the region's normal vector. The greater the
difference, the greater the error.
5.2. Add tag of last popped face.
5.3. Sort queue.

Repeat until queue is empty.

I got more than x2 increase in performance just by changing each list in the queue [ [ error value, region index tag, face index] , ...], into tuples [ ( error value, region index tag, face index)  , ...] , though I don't really understand why the change is so dramatic.
CYCLE  4
GetProxy =  21.0012
GetProxySeed =  8.0004
BuildQueue =  1.0001
AssignToRegion =  245.014
SplitRegion =  5.0003
RenumberSplitRegions =  32.0019
FindAdjacentRegions =  6.0004
FindRegionsToCombine =  114.0065
ReCombineRegions =  0.0
RenumberRegions =  0.0
ReGrowSeeds =  99.0057
CYCLE  4 TOOK =  553.0317
AssignToRegionTime Average over all cycles (20)=  275.21574

For those curious, bellow is the code of the whole function. The aforementioned change is at the very end.
Other suggestions that might speed things up are more than welcomed!
def AssignToRegion(faceNormals, vertices, faceVertexIndexes, areaFaces, adjacentFaces, regions, queue, assignedIndexes):
    ## queue = [ [error, regionIndex, index], ... ]
    ## OR queue= [ (error, regionIndex, index), ... ]

    ## Container list for the items popped from the priority list.
    assignedIndexes = set(assignedIndexes)
    ## Until the priority queue is not empty, keep popping
    ## the item with least priority from the priority queue.

    while queue :
        mostPriority = queue.pop()
        faceIndex =  mostPriority[2]

        ## If the index of the popped face has already
        ## been assigned skip to the next one.
        if faceIndex not in assignedIndexes:
            regionIndex = mostPriority[1] ## regionIndex is Int
            regions[regionIndex][1].append(faceIndex)
            assignedIndexes.add(faceIndex)
            ## Get the adjacent faces of the popped face
            ## and append them to the priority queue.
            newAdjacentFaces = set(adjacentFaces[faceIndex])
            ## If an adjacent face has already been assigned
            ## to a region, skip it.
            newAdjacentFaces -= assignedIndexes
            ## Append faces to priority queue.
            queue = UpdateQueue( regions[ regionIndex] , faceNormals, areaFaces, queue, newAdjacentFaces)

    return (regions)

def UpdateQueue( region, faceNormals, areaFaces, queue, newFaces ):
    regionIndex = region[0]
    proxyNormal = region[4]

    newFacesErrors = MetricError(regionIndex, newFaces, faceNormals, areaFaces, proxyNormal)
    queue.extend( newFacesErrors )
    ## This appears faster thatn queue.sort
    queue = sorted(queue, reverse = True)
    ## This returns a list queue = [ [error, regionIndex, index] , [...] ]
    return queue

def MetricError(regionIndex, faceIndexes, faceNormals, areaFaces, proxyNormal):
    errors = []

    for index in faceIndexes:
            area = areaFaces[index]
            normal = faceNormals[index]
            normalError = normal - proxyNormal

            ## This can be obtained as an attribute of the vector
            ## and it's much faster.
            # moduleNormalError = (normalError[0] ** 2 + normalError[1] ** 2 + normalError[2] ** 2)
            moduleNormalError = normalError.SquareLength
            error = moduleNormalError * area
            errors.append( [error, regionIndex, index] )
            ## OR
            errors.append( (error, regionIndex, index) )

    ## This returns a list errors = [ [error, regionIndex, index], ... ]
    ## OR errors = [ (error, regionIndex, index), ... ]
    return errors

As suggested by @user2357112, using heapq I get:
AssignToRegionTime average of 20 cycles =  135.80836


text:
Q: What does the word "footlocker" mean in this context? Is this a slang word? I was watching this youtube video from some guy and he uses the word "footlocker" in this sentence:

The reason no one ever shoehorned your shoe and unlaced it is because you got a footlocker.

I only know this meaning for this word:

A trunk for storing personal belongings, especially one kept at the foot of a bed, as in a barracks. (source thefreedictionary.com)

This is the entire video and the part when he says the sentence above is at 03:30: Ice Cube Is Getting Cancelled For This Blackface Reality Show

A: It sounds like he's saying "because you go to Foot Locker". Foot Locker is a chain of shoe stores typically found in malls that mostly sells sneakers.

A: To expand a bit on pboss3010's answer: Here's the fuller context.

REALITY-SHOW GUY: I've never in my life had— You know, they'll come out and give me my shoe. But I've never had anyone actually unlace it, open it, shoe-horn the back, and slide my foot into the shoe.
COMMENTATOR: [...] And you know why no one has ever shoe-horned your shoe and unlaced it? — It's because you go to Foot Locker. You're over there [at Foot Locker] buying casual shoes. [But today] you were buying shoes that require a shoe horn. Ninety-nine percent of my shoes don't require a shoe horn. And I would say that, for most young black men, we wear a lot of sneakers. Or slip-ons. Or slides.

The context here is a reality show where black people get made up to pass as white. The guy in question was impressed that when he went to a shoe store, the salesman unlaced his shoe for him and helped him get it on. The critic is saying, "Dude. You didn't get pampered today because you looked white, you got pampered because that shoe store you were at wasn't a f--king Foot Locker."
Similarly, one might say "Oh, you got a tablecloth and nice silverware? The reason you've never gotten a tablecloth and nice silverware before is because you eat at McDonald's." Same vibe.
And in that sense, yes, "Foot Locker" here is slang, or at least something like a metonym: it's the name of a specific store, being used as a stand-in for an entire class of low-end sneaker stores, in the same way as "McDonald's" might stand in for an entire class of low-end fast-food restaurants.

A: He's talking about the differing levels of service in an expensive shoe store, where the attendant will actually put the shoe on your foot when you want to try it on, as compared to a more every-day store like Foot Locker, where the attendant will just throw the box in your general direction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: what class is the .sendToAll() method found I was following a material, about socket programming in java, and i encountered problem. My server object does not have a .sendToAll() method and .removeConnection() method. Please someone should point me in the right direction. Below is the code.
public class ServerThread extends Thread {
Server server;
Socket socket;

public ServerThread(Server server, Socket socket){
    this.server = server;
    this.socket = socket;

    //start the thread
    start();
}
public void run(){
    try{
        DataInputStream din = new DataInputStream(socket.getInputStream());

        while (true){
            String message = din.readUTF();

            System.out.println("Sendong "+ message);

            server.sendToAll(message);
        }
    }catch(EOFException x){

    }catch (IOException x){
        x.printStackTrace();
    }finally{
        server.removeConnection(socket);
    }

}

A: You need to identify the class that you are using for the server.
Look at the package import for the class.
Then check the API for that server class to see if it defines the API calls you are trying to make.


text:
Q: Storybook component not show I setup Storybook to my project and add stories to my components. In simple components like button or Input stories appear in storybook. When i am creating stories on more advance component i cant see this component in stories. In stories i dont have any errors and i pass all args to component in story. My component looks like this:
  return (
    <Box>
      <Paper>
        {projects.map((project) => {
          return project.timetracking.map((value) => {
            switch (project.strategy) {
              case StrategyEnum.HoursMonthly:
                return (
                  <HoursMonthly comment={value.comment} date={value.date} hours={value.hours} />
                );
              case StrategyEnum.HoursDaily:
                return <HoursDaily comment={value.comment} date={value.date} hours={value.hours} />;
              case StrategyEnum.HoursPerTask:
                return (
                  <HoursPerTask
                    comment={value.comment}
                    date={value.date}
                    hours={value.hours}
                    taskUrl={value.taskUrl}
                  />
                );
              default:
                return <Text>No strategy match</Text>;
            }
          });
        })}
      </Paper>
    </Box>
  );
};

export default TimetrackingRecords;

I write a story to this component and my story look like this:
  title: 'timetracking/Records',
  component: TimetrackingRecords,
} as Meta;

const Template: Story<Organization> = (args) => <TimetrackingRecords {...args} />;

export const Monthly = Template.bind({});

Monthly.args = {
  id: '12jk4l12kj412rjl12jrkeqwpk',
  name: 'Organizacja 1',
  description: 'Nice oragnization 3, very nice',
  projects: [
    {
      id: 'qwklkrqwlqkrlqkrw',
      name: 'Project 1',
      users: [
        { id: 'fdfasfasfs', email: 'test2@test.com', firstName: 'Jan', lastName: 'Kowalski' },
      ],
      strategy: StrategyEnum.HoursMonthly,
      timetracking: [
        {
          id: '5545dasdas54564',
          hours: 3,
          date: '12/12/2022',
          comment: 'simple comment',
          taskUrl: 'https://bebit.atlassian.net/browse/TIM-11',
        },
      ],
    },
  ],
  users: [{ id: 'qwrlqwjrkwqjrlvn', email: 'test@test.com', firstName: 'John', lastName: 'Doe' }],
};

What i am doing wrong? Story not showing any errors. Maybe i have something wrong with configuration or Component.


text:
Q: Is finding the maximum of a polynomial of degree one a linear programming problem? Is the following problem expressible as a linear program
\begin{align}
\textbf{P1} \\
\mathrm{maximize} \; \; \; &\left[\left(a_1x+a_2y,b_1x+b_2y\right)_+ - \left(c_1x+c_2y\right)\right]_+ - \left(c_1x+c_2y\right) +  \left[\left(\alpha_1u+\alpha_2v,\beta_1u+\beta_2v\right)_+ - \left(\gamma_1u+\gamma_2v\right)\right]_+ - \left(\gamma_1u+\gamma_2v\right)  \\
\text{subject to} \\\;\;\;& 0 \le x,y,u,v \le 1
\end{align}
where $(a,b)_+=\max(a,b)$, $(a)_+=\max(a,0)$, and all the constants are nonnegative.
I'm new to linear programming.
The previous problem appeared in my work, and I don't really know how to solve it.
Since, the polynomial is of degree one, I guess it is possible to convert the $(\cdot)_+$ into constraints.
Edit
Is the above problem equivalent to this one
\begin{align}
\textbf{P2}\\
\mathrm{maximize} \;\;\; &p_0 -  \left(c_1x+c_2y\right) + q_0 - \left(\gamma_1u+\gamma_2v\right) \\
\text{subject to} \\
\;\;\; &p_0 \ge 0 \\
\;\;\; &p_0 \ge p_1 - \left(c_1x+c_2y\right) \\
\;\;\; &p_1 \ge a_1x+a_2y \\
\;\;\; &p_1 \ge b_1x+b_2y \\
\;\;\; &\text{similarly for } q_0, q_1
\end{align}
I ask because Michael said that P1 is not an LP.
But P2 looks like an LP.
What am I missing?
As I see it, any combination of $\max$ or $\min$ in the objective function can be 'linearized' like in P2.

A: Your objective is a piecewise linear convex function, and maximization of such cannot be expressed as a linear program. We can, however, use binary variables to accomplish this.
Let me point out that you can break your model apart into the $x,y$ variables and $u,v$ variables, because they are not coupled. Furthermore, the small size of the problem means that you could in theory just enumerate the vertices $x,y,u,v\in\{0,1\}$ and try them all. Thanks to the decoupling, that's just 4 tests for $x,y$, and 4 tests for $u,v$. So there's really no point in going through all the trouble to convert this problem into a mixed-integer problem, which we're about to do. I am going to do so anyway, however, in case this is actually just a simplification of a more complex model.
First of all, let's do some simplification. Note that
$$
\begin{aligned}
&\max\left\{\max\left\{a_1x+a_2y,b_1x+b_2y\right\}-(c_1x+c_2y),0\right\} \\
&\qquad=\max\left\{\max\left\{a_1x+a_2y,b_1x+b_2y\right\},c_1x+c_2y\right\}-(c_1x+c_2y) \\
&\qquad=\max\{a_1x+a_2y,b_1x+b_2y,c_1x+c_2y\}-(c_1x+c_2y)
\end{aligned}
$$
If we repeat this process for the other term, and insert the result into your model, we get this:
$$\begin{array}{ll}
\text{maximize} &\max\{a_1x+a_2y,b_1x+b_2y,c_1x+c_2y\}-2(c_1x+c_2y) \\ & + \max\{\alpha_1u+\alpha_2v,\beta_1u+\beta_2v, \gamma_1u+\gamma_2v\}-2(\gamma_1u+\gamma_2v)  \\ \text{subject to} & 0 \le x,y,u,v \le 1
\end{array}$$
Now let's linearize the objective:
$$\begin{array}{ll}
\text{maximize} &z_1-2(c_1x+c_2y)+z_2-2(\gamma_1u+\gamma_2v)  \\
\text{subject to} & 0 \le x,y,u,v \le 1 \\
& \max\{a_1x+a_2y,b_1x+b_2y,c_1x+c_2y\} \geq z_1 \\
& \max\{\alpha_1u+\alpha_2v,\beta_1u+\beta_2v, \gamma_1u+\gamma_2v\} \geq z_2
\end{array}$$
So the question is this: how to handle an inequality of this form:
$$\max\{x_1,x_2,x_3\}\geq x_4$$
What we do is introduce three binary variables $b_1,b_2,b_3$, and then do this:
$$\begin{gathered}
x_1 + b_1 M \geq x_4, \quad x_2 + b_2 M \geq x_4, \quad x_3 + b_3 M \geq x_4 \\
b_1 + b_2 + b_3 = 2, \quad  b_1,b_2,b_3\in\{0,1\}
\end{gathered}$$
where $M$ is a very large number. When $b_i=1$, the term $+b_i M$ makes the inequality trivial to satisfy (assuming $M$ is large enough). The equation $b_1+b_2+b_3=2$ ensures that exactly two of the values of $b_i$ are one. Here are a couple of things I'll leave you to prove to yourself:

*

*If you use $b_1+b_2+b_3\leq 2$ instead of $b_1+b_2+b_3=2$, this
transformation will still work.

*If other constraints in the problem
ensure that $L\leq x_1,x_2,x_3\leq U$, then choosing any $M\geq U-L$
will be sufficient. In practice, you want $M$ as small as
possible while ensuring equivalence, so this knowledge helps.

Applying this approach to your problem yields the following model:
$$\begin{array}{ll}
\text{maximize} &z_1-2(c_1x+c_2y)+z_2-2(\gamma_1u+\gamma_2v)  \\
\text{subject to} & 0 \le x,y,u,v \le 1 \\
& a_1x+a_2y+b_1 M_1 \geq z_1 \\
& b_1x+b_2y+b_2 M_1 \geq z_1 \\
& c_1x+c_2y+b_3 M_1 \geq z_1 \\
& \alpha_1u+\alpha_2v+b_4 M_2 \geq z_2 \\
& \beta_1u+\beta_2v+b_5 M_2 \geq z_2 \\
& \gamma_1u+\gamma_2v+b_6 M_2 \geq z_2 \\
& b_1+b_2+b_3\leq 2 \\
& b_4+b_5+b_6\leq 2 \\
& b_1,b_2,b_3,b_4,b_5,b_6\in\{0,1\}
\end{array}$$
where $M_1$ and $M_2$ are constants that satisfy
$$M_1\geq \max\{a_1+a_2,b_1+b_2,c_1+c_2\}, \quad
M_2\geq \max\{\alpha_1+\alpha_2,\beta_1+\beta_2,\gamma_1+\gamma_2\}.$$

When I original read this problem, I mis-read the model as a minimization, not a maximization. If it is a minimization, then we do not need the binary variables at all; the problem can, in fact, be converted to an LP. I'm providing the equivalent LP here without derivation.
$$\begin{array}{ll}
\text{minimize} &z_1 - 2(c_1x+c z_2y) + z_2-2(\gamma_1x+\gamma_2y)
 \\ \text{subject to} & 0 \le x,y,u,v \le 1 \\
& a_1x+a_2y \leq z_1 \\
& b_1x+b_2y \leq z_1 \\
&  c_1x+c_2y \leq z_1 \\
& \alpha_1u+\alpha_2v \leq z_2 \\
& \beta_1u+\beta_2v \leq z_2 \\
& \gamma_1u+\gamma_2v \leq z_2
\end{array}$$


text:
Q: LastPass Chrome extension throwing error and preventing click events I'm registering a simple click event like seen below:
$('.block--hero').on('click', '*[data-target-id]', function(e) {
    e.preventDefault();
    e.stopPropagation();
            console.log('clicked');
});

Frequently, but not always, when I click on the interface element, I'll receive the following console error that I've identified as belonging to the LastPass extension for Google Chrome.
Uncaught TypeError: Cannot read property 'location' of undefined onloadwff.js:726
    lp_docinfoFromEvent onloadwff.js:726
    icon_click_handler onloadwff.js:727
    (anonymous function) onloadwff.js:139

When I receive this error, the clicked message wasn't logged to the console. Essentially, the click event returned false.
Normally, I'd just disable the extension and forget about it, but LastPass is a pretty popular extension, and I'd like to somehow guarantee my intended behaviour. Users aren't going to know it's their extension causing the problem - only that the site doesn't work.
Is there a way around this?

A: [Uplifted from my comment on suggestion of Muhamed Cicak and to draw more prominence.]
Lastpass has a 'Never URLs' option on the account admin page where you can tell it to ignore a URL - useful if you want Lastpass awake but not start interfering with your forms.
To access it:

*

*Open your Lastpass vault

*Open Account Settings

*On the top of the window there is a list of options - select 'Never URLs'

*There are options for 'Never Add Site', 'Never Fill Forms' and 'Never Do Anything'. Use the Add button to add a URL.

[EDIT] Additionally there is an accepted answer for page authors in a SO answer here which says to add
data-lpignore="true"

to tell lastpass to ignore it.

A: I ran into this today. It seems to be related with lastpass not being able to find the username and password fields. I found this post on the last pass forms.
From one of the users:

Update: I fixed this error by renaming the ids of my fields to reg_username, reg_password, login_username, and login_password.

I did this and the error has not shown itself.
Hopefully this will help someone else.


text:
Q: Form validation, regular expressions? Need 2 strings only I have a form that people must fill in. There has to be checks if the person filled in the form correctly. Now I need 2 type of checks but I have no clue how to accomplish this. I looked up regular expressions but I only get errors (deprecated??) and I am stuck on tutorials. What I need should be easy enough.
1) string may only contain letters and dots
2) string may only contain letters, dashes - and '
Who can help me?

A: are you using eregi? because that function is deprecated since php 5.3.0.
look this website: http://takien.com/513/how-to-fix-function-eregi-is-deprecated-in-php-5-3-0.php

A: // (1)
if ( preg_match('/[^\w\.\']/u', $field1) )
    ... check one failed

// (2)
if ( preg_match('/[^\w]/u', $field2) )
    ... check two failed

// (3)
if ( preg_match('/[^\d]/', $field3) )
    ... check three failed

// (4)
if ( preg_match('/[^\w\d]/u', $field4) )
    ... check four failed

// (5) emails cannot be checked a 100% but ...
if ( !preg_match('/^(?:[0-9a-z\_\-]+\.?)+\@(?:[0-9a-z\-]+\.)+[a-z]{2,4}$/i', $field5) )
    ... check five failed

A: 1) string may only contain letters, dots and ' (NOTE: I use mysql_real_escape_string) how do I solve this?
^[A-Za-z0-9.']+$

2) string may only contain letters
Regular Expression to match only letters
3) string may only contain numbers
Regex to match "{number}"
4) string may only contain letters and numbers
combine 2) and 3)
5) check for valid email address
Using a regular expression to validate an email address


text:
Q: Why proc sql and proc means produce different results? I happened to  find the following issue which confused me for several hours.
data test;
    input RandNo$ Trt$ Tmax;
    cards;
    K64 R   0.5
    K64 T   0.15
    K64 R   0.15
    K64 T   0.5
    K65 T   0.5
    K65 R   0.33
    K65 T   0.17
    K65 R   0.5
;
run;

proc sql noprint;
    create table SQL as
    select RandNo, TRT, avg(Tmax) as Tmax_Mean
    from test
    group by RandNo, TRT
    ;
quit;

ods output Summary = Means;
proc means data = test n mean;
    class RandNo TRT;
    var Tmax;
run;
ods output;

proc sql;
    select a.RandNo, a.TRT, a.Tmax_Mean as SQL,
        b.Tmax_Mean as Means,
        SQL - Means as Dif
    from SQL as a
    left join Means as b
    on a.RandNo = b.RandNo and a.TRT = b.TRT
    ;
quit;

Output:
RandNo Trt SQL Mean Dif
K64 R 0.325 0.325 0
K64 T 0.325 0.325 -555E-19
K65 R 0.415 0.415 0
K65 T 0.335 0.335 -555E-19

So why dose the results from proc means and proc sql differs from the other? Thx in advance.
PS: I have tried deleting the observations of 'K64' or 'K65' and the difference just disappear this time.

A: The statistical engine beneath standard procedures (means, univariate, summary, etc...) is the same, however, SQL statistical engine as you discovered can have very small variation from the Procs engine.
As to why is more a question for the SAS developers. One possibility is the SQL engine may have an extra bit available from the treatment or representation of SQL ISO NULL versus SAS MISSING values (. through .Z), which in turn could affect the result.
You can view the underlying bits of the double precision representation using for RB8.
    put(SQL,RB8.) format=$hex16. as SQL_RB8,
    put(Means,RB8.) format=$hex16. as Means_RB8

 RandNo    Trt            SQL          Mean       Dif      SQL_RB8           Means_RB8.
 --------------------------------------------------------------------------------------------
     K64       R            0.325         0.325         0  CDCCCCCCCCCCD43F  CDCCCCCCCCCCD43F
     K64       T            0.325         0.325  -555E-19  CCCCCCCCCCCCD43F  CDCCCCCCCCCCD43F
     K65       R            0.415         0.415         0  90C2F5285C8FDA3F  90C2F5285C8FDA3F
     K65       T            0.335         0.335  -555E-19  703D0AD7A370D53F  713D0AD7A370D53F

When there is miniscule difference you see

*

*CC... and CD... for .325

*70... and 71... for .335

The difference is in a very lower order bit.  Lookup IEEE 754 if you want to learn more about the nitty gritty of storing decimal values in a double precision space.

A: I'm guessing that one proc applies fuzzing by default but the other doesn't. It's difficult to say exactly why, other than 'legacy reasons'.


text:
Q: How to play .mp3 file from online resources in C#? my question is very similar to this question

I have music urls. Urls like http://site.com/audio.mp3 . I want play
  this file online, like youtube. Do you know a class or code can do
  this ?

How can I play an mp3 online without downloading all for to play it?
to play the file cache will be created but at least play the file immediately

A: I found the solution with the library NAudio
http://naudio.codeplex.com/
SOLUTION
public static void PlayMp3FromUrl(string url)
{
    using (Stream ms = new MemoryStream())
    {
        using (Stream stream = WebRequest.Create(url)
            .GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
        }

        ms.Position = 0;
        using (WaveStream blockAlignedStream =
            new BlockAlignReductionStream(
                WaveFormatConversionStream.CreatePcmStream(
                    new Mp3FileReader(ms))))
        {
            using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
            {
                waveOut.Init(blockAlignedStream);
                waveOut.Play();
                while (waveOut.PlaybackState == PlaybackState.Playing )
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
        }
    }
}`

I FOUND THE ANSWER HERE
Play audio from a stream using C#

A: Many libraries like IrKlang provide streaming audio support, if you're looking for minimal development effort I'd suggest you take a look at it!
http://www.ambiera.com/irrklang/


text:
Q: Given a function $f$ defined in $R^2$. Let $F(r,\theta)=f(r\cos\theta,r\sin\theta).$ Verify a formula of the modulus of the gradient. Given a function $f$ defined in $R^2$. Let
$$F(r,\theta)=f(r\operatorname{cos}\theta,r\operatorname{sin}\theta).$$
Verify the formula
$$|\nabla f(r\operatorname{cos}\theta, r\operatorname{sin}\theta)|^2=[D_1 F(r,\theta)]^2+\frac{1}{r^2}[D_2 F(r,\theta)]^2.$$
I have found that
$$D_1 F(r,\theta)=\operatorname{cos}\theta D_1 f(x,y)+\operatorname{sin}\theta D_2 f(x,y)$$
and
$$D_2 F(r,\theta)=-r\operatorname{sin}\theta D_1 f(x,y)+r\operatorname{cos}\theta D_2 f(x,y)$$, where $x=rcos\theta, y=rsin\theta$.
Hence, we get
$$[D_1 F(r,\theta)]^2+\frac{1}{r^2}[D_2 F(r,\theta)]^2=D_1 f(x,y)^2+D_2 f(x,y)^2$$.
However, $$\nabla f(r\operatorname{cos}\theta, r\operatorname{sin}\theta)=(D_1 f\operatorname{cos}\theta+D_2 f\operatorname{sin}\theta,-rD_1 f\operatorname{sin}\theta+rD_2 f\operatorname{cos}\theta)$$.
Hence I do not get the equality. Where am I getting this wrong? I've been checking my calculations for a long time but I just can't get the answer.
I would greatly appreciate any help.

A: I think the notation $\nabla f(r\cos \theta,r\sin\theta)$ here means $(D_1 f(x,y),D_2f(x,y))$. Hence
$$|\nabla f(r\cos \theta,r\sin\theta)|^2=(D_1f(x,y))^2+(D_2f(x,y))^2$$


text:
Q: Visio Pie Chart set angle of first slice to 12 o'clock I'm trying to start the first slice of a master pie chart object in Visio to the 12 o'clock (0 degrees) position - currently it seems to default to the 3 o'clock position. In excel this would be equivalent to setting "Angle of first slice" property in the Format Data Series group to 0 degrees.
Previously I had adjusted the Shape Transformation Angle to 90 deg but that rotates the entire object 90 degrees including any text associated with the shape. I then thought I might be able to add a new shape data property "Prop.FirstSliceAngle" and set the value to 90 but that didn't update the shape at all.

Any visio specific suggestions?

A:
Previously I had adjusted the Shape Transformation Angle to 90 deg but that rotates the entire object 90 degrees including any text associated with the shape. I then thought I might be able to add a new shape data property "Prop.FirstSliceAngle" and set the value to 90 but that didn't update the shape at all.

Pie chart shape contain 10 parts you need modify each of them to get the text in the right position…

A: You can try this code for change slices text angles.
Sub PieChart_Modify()
Dim PC As Master ' Pie chart master
Dim PCsh As Shape ' ' Pie chart's main shape
Dim ssh As Shape ' Pie chart's slices
Set PC = ActiveDocument.Masters.Item("Pie chart") ' define PC
Set PCsh = PC.Shapes(1) ' define PCsh
For Each ssh In PCsh.Shapes ' iterate slices
    ssh.Cells("TxtAngle").FormulaU = "IF(BITXOR(FlipX,FlipY),-(Sheet.5!Angle+Angle),-Sheet.5!Angle-Angle)"
Next
End Sub


text:
Q: C code having trouble displaying the right time with a minute added to it this is the ques i was suppose to code...ive done the code but its not displaying the final time properly...any help would be usefull
Write a program that prompts a user to enter the hour, minute, and either AM
or PM. The program will add 1 minute to the time that has been entered, and
display the new time. This program need only to ask for the time once.
   #include <stdio.h>
   #include <stdlib.h>

   int main()
   {
    int mint, hour;
    char tod;

    printf("Enter the hour: ");
    scanf("%d", &hour);
    printf("Enter the minute: ");
    scanf("%d", &mint);
    printf("Enter AM or PM: ");
    getchar;
    scanf("%s", &tod);

    if(mint ==59){
        mint = 0;
    }
    if (hour == 12){
        hour = 1;
        if (tod='A'){
            tod = 'P';
        }
        else
            tod = 'A';
    }
    else
        mint = mint + 1;

 /*   if (hour < 11){
        if (mint < 59){
            mint = mint + 1;

    }
        else
            hour = hour + 1;
            mint = 0;
    }
    if (hour == 11 && mint == 59){
        hour = 12;
        mint = 0;
        if (tod[0]='A'){
            tod[0]='P';
        }
        else
            tod[0]='A';

  }
    if (hour == 12 && mint == 59){
        hour = 1;
        mint = 0;

    }*/
    printf("The new time is %d:%0d %c", hour, mint, tod);

  }

A: When you compile, get into the good habit of adding the compiler flag -Wall to turn on all warnings, which will quickly show you the problem spots:
$ gcc -Wall test42.c
test42.c:23:19: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
           if (tod='A'){
               ~~~^~~~
test42.c:23:19: note: place parentheses around the assignment to silence this warning
           if (tod='A'){
                  ^
               (      )
test42.c:23:19: note: use '==' to turn this assignment into an equality comparison
           if (tod='A'){
                  ^
                  ==
test42.c:15:8: warning: expression result unused [-Wunused-value]
       getchar;
       ^~~~~~~
2 warnings generated.

Take a look at the second note to the first warning.


text:
Q: How to move and rename multiple files using powershell? I have a large number of files (>4 million) and need to rename and move them to another folder in small steps.
I am a total beginner in powershell, but I already managed to move them in small packages of 100 files (the powershell script is executed as scheduled task).
But so far I failed with renaming the files. In each file, there are two strings that need to be replaced.
The following codes works fine, except for the renaming part (line 12 and 13):
#Get 'n' number of files
$FileLimit = 100

$PickupDirectory = Get-ChildItem -Path "\\server\path$\ERROR\subfolder\"
$DropDirectory = "\\server\path$\destination\"

$Counter = 0
foreach ($file in $PickupDirectory)
{
    if ($Counter -ne $FileLimit)
    {
        $file | Rename-Item -NewName {$_.name -replace '999999','367'}
        $file | Rename-Item -NewName {$_.name -replace 'oldname','newname'}

        $Destination = $DropDirectory+$file.Name

        Move-Item $file.FullName -destination $Destination
        $Counter++
    }
}
exit

What is the correct way to rename those files?
Thank you so much for your help!
Best wishes
Philipp
Edit: Sorry, here's the Error Log :
Rename-Item : Cannot rename because item at 'Microsoft.PowerShell.Core\FileSystem::\\server\path$\ERROR\subfolder\1566392#5990762$20180116^999999_2018_01_16_oldname_1566392_Kägi.pdf' does not exist.
At C:\Scripts\mv_Verordnung_für_Physiotherapie.ps1:12 char:28
+ ... pDirectory | Rename-Item -NewName {$_.name -replace '^999999','^367'}
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

Edit2: Updated the code with tipps from comments. Error still the same.

A: You should do the limiting (if necessary at all) earlier with the Get-ChildItem =>
$PickupDirectory = Get-ChildItem -Path "\\server\path$\ERROR\subfolder\" | Select -First $FileLimit

*

*Instead of using the currently iterated item ($file) you use the whole array $PickupDirectory

*You can't apply the 2. replace to an already changed value.

*instead of rename and move do it in one step.

#Get 'n' number of files
$FileLimit = 100

$PickupDirectory = Get-ChildItem -Path "\\server\path$\ERROR\subfolder\" | Select -First $FileLimit

$DropDirectory = "\\server\path$\destination\"

foreach ($file in $PickupDirectory){
    $Destination = Join-Path $DropDirectory ($file.Name -replace '^999999','^367' `
                                                        -replace 'oldname','newname')
    $file | Move-Item -Destination $Destination
}

A: You're calling Rename-Item on the $PickupDirectory collection. Instead call it on the $file variable you are using in the foreach loop:
$file | Rename-Item -NewName { $_.name -replace '^999999', '^367' }
$file | Rename-Item -NewName { $_.name -replace 'oldname', 'newname' }


text:
Q: How do I properly pass the size of a vector to a function requiring an int? I'm using a library with a function that has a parameter of type int.
I need to pass the size of the vector as the argument for this parameter.
I know I can get the the size of a vector using someVector.size(), but this returns the type size_t.
I know I can cast the size_t to an int: e.g. static_cast<int>(someVector.size()).  However, casting might cause problems if someVector.size() exceeds the max value of int.
What's the proper way to pass the size of a vector to a function requiring a parameter of type int?

A: There is no "safe" way to pass a std::size_t to a function accepting int (whenever the size_t is larger than the maximal representable int you're in trouble). You can however test if passing is safe:
if(v.size() < std::numeric_limits<int>::max()) // need to #include <limits>
{
    // safe to pass
}
else
{
    // not safe, throw error/exit/print something
}

The comparison is always safe, provided the int is positive.

A: I would look into the library documentation for solutions, they might accept values of type unsigned int which is pretty similar to size_t. Here is another post that might help: unsigned int vs. size_t.


text:
Q: What is the trajectory of a photon moving through a vacuum? Since electromagnetic energy is carried by photons and moves in forms of waves, does it mean that a single photon when propagating through space doesn't follow the straight path but instead always moves up and down, up and down like a wave. If so another question arises the speed of propagation of light in vacuum is fixed meaning that it will always take the same amount of time for it to travel from point A to point B, but if a photon always moves up and down it will also mean that it travels longer distance than the distance between A and B and so it ill travel faster than light propagates, is it even possible, could you please clarify these concepts for me?

A:
Since electromagnetic energy is carried by photons and moves in forms of waves, does it mean that a single photon when propagating through space doesn't follow the straight path but instead always moves up and down, up and down like a wave.

The term photon belongs to the realm of quantum mechanics. The photon is  a fundamental elementary particle in the standard model of particle physics. Electromagnetic energy is defined well in classical electrodynamics and it does move this energy as a wave in time and space.
A single elementary particle propagating through space is mathematically modeled by a wavefunction which is a solution of a quantum mechanical equation. This is a complex number function, it has a sinusoidal form but the only physically measurable effect is the probability of getting a "photon" signal at a specific (x,y,z,t). It is the probability that has a sinusoidal dependence in space time, not the photon, as can be seen in the answer here. The energy of the photon is h*nu, where nu is the frequency of the classical wave which will emerge from a large number of such energy  photons.
So it is not possible to talk of a trajectory of a single photon at the microscopic quantum level. It is only macroscopically, when the atomic source is known, and the interaction footprint  of the photon is detected on a screen or a camera that a straight line can be drawn which in effect is the optical ray of the classical em wave.

If so another question arises the speed of propagation of light in vacuum is fixed meaning that it will always take the same amount of time for it to travel from point A to point B, but if a photon always moves up and down it will also mean that it travels longer distance than the distance between A and B and so it ill travel faster than light propagates, is it even possible,

No, it is not possible in vacuum. The photon does not propagate as you imagine, and can only be described by its energy=h*nu and its spin direction. It always travels at c.
In the complicated quantized environment of a medium with an index of refraction the way the photon wavefunctions are related to the emergent classical wave, shows that the individual photon paths, which at the microscopic level are always in vacuum and travel with velocity c, can not be an optical ray. An individual photon impinging on a transparent medium will interact by elastic scatterings with the atoms of the lattice and certainly its path cannot be one straight line. In coherence with the zillions of photons in a classical em wave it is better to discuss the classical paths and let quantum mechanics take care of the individual interactions. A true analysis quantum mechanically needs quantum field theory and is unnecessarily complicated.

A: Your confusion comes from combining two different concepts (although they are related). Photon is a discrete particle. A wave is a continuous. You can look at light as a discrete particle or a wave, but if you think of them the way you are thinking of them, things get confusing.

*

*A photon does not travel among the wave's amplitude function. It
travels in all possible paths and we observe one path at a time (And
usually if the path from A to B is simple, the many possible paths
cancel out).

*A photon always travels at speed c.

*The up and downs
of a electromagnetic wave are the consequences of a photon moving.
They are self inducing oscillations in the electromagnetic field.

*You can also think that the ups and downs of an electromagnetic wave can be represented as a photon, which is carrying information about a change in the electromagnetic field at speed c. (A change caused perhaps by moving a charged particle like an electron.)

By the way, if I didn't answer your question, try to think about why we started thinking of light as particles. (The problems that lead to the concepts you are studying). You can start at the photo-electric effect.

A: Photons can be regarded as stable particles depending on perspective. In the Sun's core hydrogen atoms break down into a mixed plasma which includes protons and deuterium atoms. If these collide they form a helium-3 nucleus and a gamma ray is released. The gamma ray is a highly energized photon. It is very difficult for this photon to escape the Sun as it is surrounded by densely packed protons. It bounces around for a while (maybe a thousand or a million years) before it gets to the surface. Due to losing some energy from collisions with protons the photon will now be in the visible spectrum. Then if it is "aimed" towards Earth it will take about 8 minutes through the vacuum to get here but not in an exact straight line as space-time is curved by all of the matter nearby (planets etc). The photon does not move up and down with the waveform however. The photon is represented by a waveform because that it how we measure it. For us, with our measurements the photon is the waveform. One Wavelength = One Photon. The wave moves as one. If I threw a coat-hanger at you it would not take on the trajectory of its shape. The entire coat-hanger would move as one. Hope this breaks your perception that a photon travels along itself. You don't walk along yourself. All the best.


text:
Q: Right justify a component within a div in React Suppose:
props.data1 = 'data1' and props.data2 = 'data2'
In React, I have the following code:

        {props.data1}    {props.data2}

Which appears like: data1        data2.
What I am trying to do is right justify only data2 so it looks like the following:
data1                                data2
Assuming that is the furthest data2 can be pushed horizontally. Is there any tag/CSS that I can add to enable this? I've tried using span, but it causes data2 to be pushed to a newline in React.

A: So to achieve this you'll need two child elements on the HTML side like so:

data1
data2

css:
.container {
display:flex;
flex-direction: row;
justify-content: space-between;
}

A: If you don't mind adding the contained text in their own elements you can use display: flex; on the containing div, and set its justify-content attribute to space-between.

.container {
  width: 300px;
  border: 1px solid salmon;
  display: flex;
  justify-content: space-between;
}

  data1
  data2

A: If you are triyng to separate the texts, you can use css flex.

  {data1}
  {data2}

A: You can try this:

.wrapper {
  display: flex;
  justify-content: space-between;
}

data1

data2


text:
Q: Javascript write DOM not working out of function I'm pretty new to javascript and I can't get this to run.
After pressing the equal button it runs the function calc() which should write the calculator result onto the display but it just don't work... But if I run the calc() from developer console it runs perfectly so I guess there is something wrong with scoping whatsoever. Maybe you guys have an idea :)?
Please forgive me missing error handling as I am doing basic stuff first.

/**
 * core
 */
var display = null;
var input = null;

var latestNumber = null;
var result = null;
var displayNumber = null;
var operator = null;

function setOperator(operatorValue) {

    if (displayNumber === null && operator === null){
        displayNumber = readInput();
        writeOutput(displayNumber + " " + String(operatorValue));
        clearInput();

    } else if (displayNumber !== null && operator !== null){
        writeOutput( displayNumber + " " + String(operatorValue));
    }

    operator = String(operatorValue);

}

function addDigit(digit){
    let oldValue = readInput();

    if(Number.isNaN(oldValue)){
        oldValue = "";
    }

    let newInputValue = String(oldValue) + String(digit); //Parse numbers to string

    writeInput(newInputValue);
}

function calc (firstNumber, op, secondNumber){

    switch (op) {
        case "+":
            result = firstNumber + secondNumber;
            break;

        case "-":
            result = firstNumber - secondNumber;
            break;

        case "*":
            result = firstNumber * secondNumber;
            break;

        case "/":
            if (secondNumber === 0) {
                window.alert("Error: Division by zero");
            }
            else {
                result = firstNumber / secondNumber;
            }
            break;
    }

    operator = null;
    latestNumber = null;
    displayNumber = null;

    writeInput(result);
}

/**
 * UI
 */

window.addEventListener('load', function() {

    //Initialize number Buttons
    (function () {
        const numbers = document.getElementsByClassName("number");

        for (let i = 0; i < numbers.length; ++i) {
            numbers[i].addEventListener('click', () => addDigit(numbers[i].value));
        }
    })();

    //Initialize operation Buttons
    (function () {
        const operators = document.getElementsByClassName("operator");
        for (let i = 0; i < operators.length; ++i) {
            operators[i].addEventListener('click', () => setOperator (operators[i].value));
        }
    })();

    //Initialize calc button
    (function () {
        const equalButton = document.getElementById("key-=");
        equalButton.addEventListener('click', ()=> calc (displayNumber, operator, readInput()));
    })();

    //Initialize clear button
    (function () {
        const commands = document.getElementsByClassName("command");
        for (let i = 0; i < commands.length; ++i) {
            commands[i].addEventListener('click', ()=> clearAll ());
        }
    })();

    //Initialize Display
    display = (function (){
        return document.getElementById("output");
    })();
    input = (function () {
        return document.getElementById("input");
    })();
    writeOutput("Welcome");

});

//Function to read from input
function readInput () {
    return parseFloat(input.value);
}

//Function to write to input
function writeInput (value) {
    input.value = value;
}

//Function to write to output
function writeOutput (string) {
    display.value = string;
}

//Function to clear input
function clearInput () {
    input.value = "";
}

//Function to clear output
function clearOutput () {
    display.value = "";
}

//Function to clear display
function clearAll (){
    result = null;
    lastNumber = null;
    displayNumber = null;
    operator = null;

    clearInput();
    clearOutput();
}
/* reset */
*  {
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 -ms-box-sizing: border-box;
 box-sizing: border-box;
 margin: 0;
 padding: 0;
}

html {
 font-size: 1vw;
}

html, body {
 width: 100%;
 margin: 0;
 padding: 0;
}

/* document */
body {
 font-family: "URW Gothic L", "Helvetica", "Arial", sans-serif;
 /* Background source:
  * http://www.texturex.com/Leather-Textures/black+leather+texture+large+close+up+grain+material+dark+fabric+stock+photo.jpg.php
  * Free offered by Free Leather Textures */
 background: url('../../../media/black-leather-texture.jpg');
}

.display {
 border: 0.2rem solid gray;
 border-radius: 0.5rem;
 background: black;
 padding: 0.5rem;
 width: 100%;
 display: block;
}
.display > output {
 display: block;
 height: 1.5rem;
 margin: 0;
 color: aqua;
}

form {
 width: 100%;
 padding: 0.5rem;
}

fieldset {
 border: none;
 margin: 0;
 font-size: 0;
}
fieldset > button {
 width: 20%;
 margin: 3.3%;
 padding: 2vw;
}
fieldset > button:nth-child(4n) {
 margin-right: 0;
}
fieldset > button:nth-child(4n+1) {
 margin-left: 0;
}

button {
 box-shadow: 0 0 0.5rem black;
 border: none;
 border-radius: 0.5rem;
 text-align: center;
 vertical-align: middle;
 margin: 0;
 font-weight: bold;
 font-size: 1.5rem;
}
output {
 font-size: 1rem;
}

button.number, button.command {
 background: white;
}
button.number:active, button.command:active {
 background: rgb(230, 230, 230);
 box-shadow: inset 0 0 0.5rem black;
}
button.operator {
 box-shadow: 0 0 0.5rem rgb(80,80, 80);
 background: black;
 color: white;
}
button.operator:active {
 background: rgb(60, 60, 60);
 box-shadow: inset 0 0 0.5rem black;
}

#key-c {
 background: red;
 color: white;
}
#key-c:active {
 background: darkred;
}
button:focus {
 box-shadow: 0 0 0.5rem deepskyblue;
}
<form>
  <fieldset class="display">
    <output name="output" id="output" class="output"></output>
    <output name="input" id="input" class="input"></output>
  </fieldset>

  <fieldset>
    <button type="button" name="key-0" id="key-0" class="number" value="0">0</button>
    <button type="button" name="key-1" id="key-1" class="number" value="1">1</button>
    <button type="button" name="key-2" id="key-2" class="number" value="2">2</button>
    <button type="button" name="key-+" id="key-+" value="+" class="operator">+</button>

    <button type="button" name="key-3" id="key-3" class="number" value="3">3</button>
    <button type="button" name="key-4" id="key-4" class="number" value="4">4</button>
    <button type="button" name="key-5" id="key-5" class="number" value="5">5</button>
    <button type="button" name="key--" id="key--" value="-" class="operator">−</button>

    <button type="button" name="key-6" id="key-6" class="number" value="6">6</button>
    <button type="button" name="key-7" id="key-7" class="number" value="7">7</button>
    <button type="button" name="key-8" id="key-8" class="number" value="8">8</button>
    <button type="button" name="key-*" id="key-*" value="*" class="operator">∗</button>

    <button type="button" name="key-9" id="key-9" class="number" value="9">9</button>
    <button type="button" name="key-c" id="key-c" class="command">C</button>
    <button type="button" name="key-=" id="key-=" class="command">=</button>
    <button type="button" name="key-/" id="key-/" value="/" class="operator">÷</button>
  </fieldset>
</form>

A: The problem here is that the "Clear" and the "Equals" buttons are sharing the same class.
So, when you call the equals function it also triggers this code:
(function () {
    const commands = document.getElementsByClassName("command");
    for (let i = 0; i < commands.length; ++i) {
        commands[i].addEventListener('click', ()=> clearAll ());
    }
})();

You are printing the result and then clearing the field.
Try changing the class on the equals button and it will work.
        <button type="button" name="key-c" id="key-c" class="command">C</button>
        <button type="button" name="key-=" id="key-=" class="equals">=</button>


text:
Q: Rank Over Partition By in Oracle SQL (Oracle 11g) I have 4 columns in a table

*

*Company Part Number

*Manufacturer Part Number

*Order Number

*Part Receipt Date
Ex.

I just want to return one record based on the maximum Part Receipt Date which would be the first row in the table (The one with Part Receipt date 03/31/2015).
I tried
RANK() OVER (PARTITION BY Company Part Number,Manufacturer Part Number
            ORDER BY Part Receipt Date DESC,Order Number DESC) = 1

at the end of the WHERE statement and this did not work.

A: This would seem to do what you want:
select t.*
from (select t.*
      from t
      order by partreceiptdate desc
     ) t
where rownum = 1;

A: Analytic functions like rank() are available in the SELECT clause, they can't be invoked directly in a WHERE clause. To use rank() the way you want it, you must declare it in a subquery and then use it in the WHERE clause in the outer query. Something like this:
select company_part_number, manufacturer_part_number, order_number, part_receipt_date
from   ( select t.*, rank() over (partition by...  order by...) as rnk
         from   your_table t
       )
where  rnk = 1

Note also that you can't have a column name like company part number (with spaces in it) - at least not unless they are enclosed in double-quotes, which is a very poor practice, best avoided.


text:
Q: How To Limit Access To A Telegram Bot When I send a message to my Telegram Bot, it responses with no problems.
I wanna limit the access such that me and only me can send message to it.
How can I do that?

A: Start a conversation with your bot, and send it a message. This will queue up an updates for the bot containing the message and the chat ID for your conversation.
To view recent updates, you call the getUpdates method. This is done by making a HTTP GET request to the URL https://api.telegram.org/bot$TOKEN/getUpdates Where $TOKEN is the token provided by the BotFather. Something like:
"chat":{
        "id":12345,
        "first_name":"Bob",
        "last_name":"Jones",
        "username":"bjones",
        "type":"private"},
      "date":1452933785,
      "text":"Hi there, bot!"}}]}

Once you determined your chat id you can write a piece of code in your bot like:
id_a = [111111,2222222,3333333,4444444,5555555]

    def handle(msg):
        chat_id = msg['chat']['id']
        command = msg['text']
        sender = msg['from']['id']
     if sender in id_a:
    [...]
     else:
           bot.sendMessage(chat_id, 'Forbidden access!')
           bot.sendMessage(chat_id, sender)

A: As this question is related to python-telegram-bot, information below is related to it:
When you add handlers to your bot's dispatcher, you can specify various pre-built filters (read more at docs, github) or you can create custom ones in order to filter incoming updates.
To limit access to a specific user, you need to add Filters.user(username="@telegramusername") when initializing handler, e.g.:
dispatcher.add_handler(CommandHandler("start", text_callback, Filters.user(username="@username")))

This handler will accept /start command only from user with username @username.
You can also specify user-id instead of username, which I would highly recommend, as latter is non-constant and can be changed over time.

A: in my case this idea helped, actually logic is pretty easy,maybe you will find it useful. I used a telebot module:
# list with an id's, type int
prmssn=[
    12345678,87654321
]

@bot.message_handler(content_types=['text'])
def handle_text(message):
    # get the user's id of a last message
    u_id=message.chat.id
    # you can use print to find out an id's of those who're trying to write to your bot
    print(u_id)
    # we use a permission list to compare id, if id is in the perm. list bot is going to answer, otherwise it keeps silence
    if u_id in prmssn:
        # get user's message
        u_query=message.text.strip()
        # echo it back
        bot.send_message(message.chat.id, u_query)

A: Filter messages by field update.message.from.id

A: Based on the python-telegram-bot code snippets, one can build a simple wrapper around the handler:
def restricted(func):
    """Restrict usage of func to allowed users only and replies if necessary"""
    @wraps(func)
    def wrapped(bot, update, *args, **kwargs):
        user_id = update.effective_user.id
        if user_id not in conf['restricted_ids']:
            print("WARNING: Unauthorized access denied for {}.".format(user_id))
            update.message.reply_text('User disallowed.')
            return  # quit function
        return func(bot, update, *args, **kwargs)
    return wrapped

where conf['restricted_ids'] might be an id list, e.g. [11111111, 22222222].
So the usage would look like this:
@restricted
def bot_start(bot, update):
    """Send a message when the command /start is issued"""
    update.message.reply_text('Hi! This is {} speaking.'.format(bot.username))

Update | for functions and methods (DRY, python-telegram-bot version 12 and above)
The solution above cannot be used on methods inside classes (positional arguments change). For a while, I had just created an additional decorator for methods. However one would always need to keep in mind which decorator to use when.
Building on top of this solution, the following decorator class can be built:
class restricted(object):
    """
    Decorator class used to restrict usage of commands.
    Sends a "disallowed" reply if necessary. Works on functions and methods.
    """
    def __init__(self, func):
        self._func = func
        self._obj = None
        self._wrapped = None

    def __call__(self, *args, **kwargs):
        if not self._wrapped:
            if self._obj:
                self._wrapped = self._wrap_method(self._func)
                self._wrapped = partial(self._wrapped, self._obj)
            else:
                self._wrapped = self._wrap_function(self._func)
        return self._wrapped(*args, **kwargs)

    def __get__(self, obj, type_=None):
        self._obj = obj
        return self

    def _wrap_method(self, method): # Wrapper called in case of a method
        @wraps(method)
        def inner(self, *args, **kwargs): # `self` is the *inner* class' `self` here
            user_id = args[0].effective_user.id # args[0]: update
            if user_id not in cfg.RESTRICTED_IDS:
                print(f'Unauthorized access denied on {method.__name__} ' \
                    f'for {user_id} : {args[0].message.chat.username}.')
                args[0].message.reply_text('User disallowed.')
                return None # quit handling command
            return method(self, *args, **kwargs)
        return inner

    def _wrap_function(self, function): # Wrapper called in case of a function
        @wraps(function)
        def inner(*args, **kwargs): # `self` would be the *restricted* class' `self` here
            user_id = args[0].effective_user.id # args[0]: update
            if user_id not in cfg.RESTRICTED_IDS:
                print(f'Unauthorized access denied on {function.__name__} ' \
                    f'for {user_id} : {args[0].message.chat.username}.')
                args[0].message.reply_text('User disallowed.')
                return None # quit handling command
            return function(*args, **kwargs)
        return inner

This works then, as expected, on functions and methods. It's not entirely DRY (cf. comments), but at least self-contained.

A: I ran into this question myself so I thought I might say how I did it with Python's python-telegram-bot. So, with the new release (Version 20) [some classes/functions have changed] you could do something such as:
async def restrict(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="There is no bot in Ba Sing Se."
    )

# Creating the Application
application = ApplicationBuilder().token(TOKEN).build()

# Restrict bot to the specified user_id
restrict_handler = MessageHandler(~ filters.User(USER_ID), restrict)
application.add_handler(restrict_handler)

See the github tutorial for the rest of the scaffolding, but this puts the restricted handlder first using a filter to effectively cut off access to any user who doesn't match the USER_ID you feed to it, and because it's first, all other handlers don't hit.
The other answers work well if you want to specifically restrict certain actions, but this is good for a blanket restriction. You could also just use a filter inside each action you want restricted.

A: Filtering by update.message.chat_id works for me.
In order to find your chat id, send a message to your bot and browse to
https://api.telegram.org/bot$TOKEN/getUpdates

where $TOKEN is the bot token as provided by BotFather, as mentioned in the answer by fdicarlo, where you can find the chat id in the json structure.


text:
Q: Node JS Karma Testing - HotTowel Template extension I am teaching myself node.js and I have taken Hot Towel template and begun to extend its function.
I have added a new Controller which implements angular-file-upload.
It works fine up to the point where i try and implement a Karma test against the new module whereupon it throws this error
   Chrome 46.0.2490 (Mac OS X 10.11.1) UploadController "before each" hook for "should be created successfully" FAILED
    Error: [$injector:unpr] Unknown provider: routerHelperProvider <- routerHelper
    http://errors.angularjs.org/1.4.7/$injector/unpr?p0=routerHelperProvider%20%3C-%20routerHelper
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:68:12
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4289:19
        at Object.getService [as get] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4294:45
        at getService (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at Object.invoke (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4469:13)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:79
        at forEach (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:336:20)
        at Object.createInjector [as injector] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:3)
        at Context.workFn (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-mocks/angular-mocks.js:2427:52)
Chrome 46.0.2490 (Mac OS X 10.11.1) UploadController "after each" hook: workFn for "should be created successfully" FAILED
    Error: [$injector:unpr] Unknown provider: routerHelperProvider <- routerHelper
    http://errors.angularjs.org/1.4.7/$injector/unpr?p0=routerHelperProvider%20%3C-%20routerHelper
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:68:12
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4289:19
        at Object.getService [as get] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4294:45
        at getService (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at Object.invoke (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4469:13)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:79
        at forEach (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:336:20)
        at Object.createInjector [as injector] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:3)
        at Context.workFn (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-mocks/angular-mocks.js:2427:52)
Chrome 46.0.2490 (Mac OS X 10.11.1) upload routes state "before each" hook for "should map state upload to url /upload " FAILED
    Error: [$injector:unpr] Unknown provider: routerHelperProvider <- routerHelper
    http://errors.angularjs.org/1.4.7/$injector/unpr?p0=routerHelperProvider%20%3C-%20routerHelper
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:68:12
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4289:19
        at Object.getService [as get] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4294:45
        at getService (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4437:39)
        at Object.invoke (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4469:13)
        at /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:79
        at forEach (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:336:20)
        at Object.createInjector [as injector] (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular/angular.js:4299:3)
        at Context.workFn (/Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-mocks/angular-mocks.js:2427:52)
Chrome 46.0.2490 (Mac OS X 10.11.1): Executed 42 of 45 (3 FAILED) (0.371 secs / 0.053 secs)

The Upload Controller looks like:-
(function () {
    'use strict';

    angular
        .module('app.upload',['angularFileUpload'])
        .controller('UploadController', UploadController);

    UploadController.$inject = ['logger','FileUploader','$scope'];
    /* @ngInject */
    function UploadController(logger, FileUploader, scope) {
        var vm = this;
        vm.title = 'Upload';

        var uploader = scope.uploader = new FileUploader({
            url: '/upload'
        });

        activate();

        function activate() {
            logger.info('Activated Upload View');
        }

        // FILTERS

        uploader.filters.push({
            name: 'customFilter',
            fn: function(item /*{File|FileLikeObject}*/, options) {
                return this.queue.length < 10;
            }
        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
            console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function(fileItem) {
            console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function(addedFileItems) {
            console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function(item) {
            console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function(fileItem, progress) {
            console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function(progress) {
            console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function(fileItem, response, status, headers) {
            console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function(fileItem, response, status, headers) {
            console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function(fileItem, response, status, headers) {
            console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function(fileItem, response, status, headers) {
            console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteAll = function() {
            console.info('onCompleteAll');
        };

        console.info('uploader', uploader);

    }
})();

The upload-routes.js looks like this:-
(function() {
    'use strict';

    angular
        .module('app.upload')
        .run(appRun);

    appRun.$inject = ['routerHelper'];
    /* @ngInject */
    function appRun(routerHelper) {
        routerHelper.configureStates(getStates());
    }

    function getStates() {
        return [
            {
                state: 'upload',
                config: {
                    url: '/upload',
                    templateUrl: 'app/upload/upload.html',
                    controller: 'UploadController',
                    controllerAs: 'vm',
                    title: 'Upload',
                    settings: {
                        nav: 3,
                        content: '<i class="fa fa-lock"></i> Upload'
                    }
                }
            }
        ];
    }
})();

The test spec looks like:-
/* jshint -W117, -W030 */
describe('UploadController', function() {
    var controller;

    beforeEach(function() {
        bard.appModule('app.upload');
        bard.inject('$controller', '$log', '$rootScope');
    });

    beforeEach(function () {
        controller = $controller('UploadController');
        $rootScope.$apply();
    });

    bard.verifyNoOutstandingHttpRequests();

    describe('Upload controller', function() {

        it('should be created successfully', function () {

            expect(controller).to.be.defined;
        });

        describe('after activate', function() {
            it('should have title of Upload', function() {
                expect(controller.title).to.equal('Upload');
            });

            it('should have logged "Activated"', function() {
                expect($log.info.logs).to.match(/Activated/);
            });
        });
    });
});

I found a link that indicated that this error occurs when all required dependencies are not loaded.
The build is orchestrated by gulp.
The gulp.js and gulp.config files look ok and the right resources are loaded in the browser.
When i run gulp in SingleRun mode = False and spawn an instance of Chrome i get the following in the console.log:-
15 11 2015 23:21:37.527:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.528:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.528:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.529:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.531:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.532:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.532:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.532:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.533:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.534:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.534:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.534:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.535:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.536:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.546:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.546:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.547:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.548:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.548:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.548:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.549:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)
15 11 2015 23:21:37.549:DEBUG [middlware:source-files]: Requesting /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map /
15 11 2015 23:21:37.549:DEBUG [middlware:source-files]: Fetching /Users/simon/Documents/Development/angular_dev/billrecon/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map
15 11 2015 23:21:37.550:DEBUG [proxy]: proxying request - /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map to localhost:8888
15 11 2015 23:21:37.550:WARN [proxy]: failed to proxy /base/bower_components/angular-file-upload/dist/angular-file-upload.min.js.map (connect ECONNREFUSED 127.0.0.1:8888)

***EDIT - ran gulp test --startServers=true - to ensure the server was started and it overcame the connected refused error. Still get the routerHelperProvider issue though
The files exist in the right place.
I think I am doing something obvious wrong but I cant see it.
Any suggestions?
Thanks
Simon

A: The issue seems to be with the version of phantomjs. So you need to do a couple of things.

*

*Download the latest version of phantomjs from here

*At the command prompt uninstall the following libraries:
npm uninstall phantomjs karma-phantomjs-launcher --save-dev

*At the command prompt install the following libraries:
npm install --save-dev phantomjs-prebuilt phantomjs2 karma-phantomjs2-launcher

*Update any references in the code from phantomjs to phantomjs2


text:
Q: Clean up SQL data before unique constraint I want to clean up some data in a table before putting in a unique constraint on two columns.
CREATE TABLE test (
 a integer NOT NULL,
 b integer NOT NULL,
 c integer NOT NULL,
 CONSTRAINT a_pk PRIMARY KEY (a)
);

INSERT INTO test (a,b,c) VALUES
 (1,2,3)
,(2,2,3)
,(3,4,3)
,(4,4,4)
,(5,4,5)
,(6,4,4)
,(7,4,4);

-- SELECT a FROM test WHERE ????

Output should be 2,6,7
I am looking for all rows after the first that have duplicated b,c
EX:

*

*Rows 1,2 have (2,3) as b,c
Row 1 is ok because it is the first, 2 is not.

*Rows 4,6,7 have (4,4) as b,c
Row 4 is ok because it is the first, 6,7 are not.
I will then:
DELETE FROM test WHERE a = those IDs;

.. and add the unique constraint.
I was thinking about an intersect on test with itself but not sure where to do go from there.

A: I ran a couple of tests. The EXISTS variant proves to be substantially faster - as I expected and contrary to what @Tometzky posted.
Test bed with 10.000 rows on PostgreSQL 9.1.2 with decent settings:
CREATE TEMP TABLE test (
  a serial
 ,b int NOT NULL
 ,c int NOT NULL
);

INSERT INTO test (b,c)
SELECT (random()* 100)::int AS b, (random()* 100)::int AS c
FROM   generate_series(1, 10000);

ALTER TABLE test ADD CONSTRAINT a_pk PRIMARY KEY (a);

Between the first and second round of tests, I ran:
ANALYZE test;

When I finally applied the DELETE, 3368 duplicates were deleted. Performance may vary if you have substantially more or fewer duplicates.
I ran each query a couple of times with EXPLAIN ANALYZE and took the best result. Generally, the best hardly differs from the first or worst.
A bare SELECT (without the DELETE) shows similar results.
1. CTE with rank()
Total runtime: 150.411 ms
Total runtime: 149.853 ms -- after ANALYZE
WITH x AS (
    SELECT a
          ,rank() OVER (PARTITION BY b, c ORDER BY a) AS rk
    FROM   test
    )
DELETE FROM test
USING  x
WHERE  x.a = test.a
AND    rk > 1;

2. CTE with row_number()
Total runtime: 148.240 ms
Total runtime: 147.711 ms -- after ANALYZE
WITH x AS (
    SELECT a
          ,row_number() OVER (PARTITION BY b, c ORDER BY a) AS rn
    FROM   test
    )
DELETE FROM test
USING  x
WHERE  x.a = test.a
AND    rn > 1;

3. row_number() in subquery
Total runtime: 134.753 ms
Total runtime: 134.298 ms  -- after ANALYZE
DELETE FROM test
USING (
    SELECT a
          ,row_number() OVER (PARTITION BY b, c ORDER BY a) AS rn
    FROM   test
    )  x
WHERE  x.a = test.a
AND    rn > 1;

4. EXISTS semi-join
Total runtime: 143.777 ms
Total runtime: 69.072 ms  -- after ANALYZE
DELETE FROM test t
WHERE EXISTS (
    SELECT 1
    FROM   test t1
    WHERE  t1.a < t.a
    AND   (t1.b, t1.c) = (t.b, t.c)
    );

The difference in the second run comes from a switch to a Hash Semi Join
instead of an additional Sort + Merge Semi Join.
Results

*

*EXISTS clearly wins with up-tp-date table statistics.

*With outdated statistics row_number() in a subquery is fastest.

*rank() is the slowest variant.

*CTE is slower than subquery.

*ANALYZE (updated statistics) helps performance and can help a lot. Autovacuum (default) should more or less take care of this automatically - except for temporary tables or immediately after major changes to the table. Read more here or here.

Test with 100.000 rows
I repeated the test with 100.000 rows and 63045 duplicates. Similar results, except that EXISTS was slower, even after ANALYZE.

*

*Total runtime: 1648.601 ms

*Total runtime: 1623.759 ms

*Total runtime: 1568.893 ms

*Total runtime: 1692.249 ms

Raising the statistics target to 1000 and then to the maximum of 10000 (overkill in real live) and another ANALYZE sped up all queries by ~ 1 %, but the query planner still went with Sort + Merge Semi Join for EXISTS.
ALTER TABLE test ALTER COLUMN b SET STATISTICS 10000;
ALTER TABLE test ALTER COLUMN c SET STATISTICS 10000;
ANALYZE test;

Only after I forced the planner to avoid the merge joins the planner used a Hash Semi Join taking half the time again:
SET enable_mergejoin = off

*Total runtime: 850.615 ms

Update
There have been improvements to the query planner since then. Went straight to Hash Semi Join in a retest with PostgreSQL 9.1.7.

A: Using window functions should be much faster than this answer:
select a
from (
  select a, rank() over (partition by b, c order by a) as rank
  from test ) as _
where rank>1;

A: select o.a from test o
where exists ( select 'x'
                 from test i
                where i.c = o.c
                  and i.b = o.b
                  and i.a < o.a
            );

Thanks to a coworker!

A: I would give this a try:
delete from
  test
where
  a not in (
    select   min(a)
    from     test
    group by b,c)

Between 20 and 60ms on my machine, for what it's worth, and analyse does not affect the plan.
 Delete on test  (cost=237.50..412.50 rows=5000 width=6)
   ->  Seq Scan on test  (cost=237.50..412.50 rows=5000 width=6)
         Filter: (NOT (hashed SubPlan 1))
         SubPlan 1
           ->  HashAggregate  (cost=225.00..235.00 rows=1000 width=12)
                 ->  Seq Scan on test  (cost=0.00..150.00 rows=10000 width=12)


text:
Q: Writing binary data in python (header fail) I am trying to write a binary file in python. Usually, i use numpy and struct.pack.
I want to reproduce this header taken from a C# code:
BinaryWriter writebin = new BinaryWriter(File.Open(..., FileMode.Create))
// write first Line = -99 +chr(13) +chr(10)
writebin.Write((byte)45);
writebin.Write((byte)57);
writebin.Write((byte)57);
writebin.Write((byte)32);
writebin.Write((byte)13);
writebin.Write((byte)10);

The opposite reading code in C# is:
First step, determine if it's binary:
string[] text = new string[1];
StreamReader reader = new StreamReader(..)
text = reader.ReadLine().Split(new char[] { ' ', ',', '\r', '\n' }, stringSplitOptions.RemoveEmptyEntries);
if (Convert.ToDouble(text[0]) < 0) {
  // THEN IT SHOULD GO ON
}

The second step would be something like:
BinaryReader readbin = new BinaryReader(..))
// read 1st line inclusive carriage return and line feed
byte[] header;
header = readbin.ReadBytes(6);

Would you know how to do this in python. I just cannot get to write the header!
Thanks!!!

A: Just found it! I feel pretty stupid...

with open(str(filename), 'wb') as writebin:
    writebin.write(struct.pack("=B",45))
    writebin.write(struct.pack("=B",57))
    writebin.write(struct.pack("=B",57))
    writebin.write(struct.pack("=B",32))
    writebin.write(struct.pack("=B",12))
    writebin.write(struct.pack("=B",10))
    writebin.write(struct.pack('i', self.nx))

See old stackoverflow answer ...


text:
Q: CSS Hover style remains after mouse is no longer hovering The following happens in Safari Version 7.0.1 and IE8.
Steps to reproduce the problem:
http://goo.gl/lP3Ky1
Problem:
The row's hover state remains after dismissing the popup menu, and it will not go away no matter where the mouse is, until you hover over it again.
What is the expected behavior?
The row's hover state should go away after dismissing the popup menu.
Does anybody know a fix for Safari Version 7.0.1 and IE8? I would be okay with some manual way to "untrigger" the css hover state.

A: Here is a workaround - http://jsfiddle.net/3BUaT/11/ . After going through many stackoverflow posts, understood that it is not possible to remove css pseudo class from javascript. So definitely a work around was necessary.
I'm using
tr.hovered td {
  background-color: lightblue;
}

instead of regular CSS hover state.
The problem is that when you click on an li in menu, it's not exactly triggering mouseout event from CSS in safari. Technically speaking, you did not actually took your mouse out of the element. It's just that the element was removed. This seems like a bug in safari.

A: This was an interesting issue to solve.  And while the solution is a bit hacky, it works.  After setting the HTML to "boo" we clone the entire row, insert it, and remove the old one:
$(function() {
  $("table").on("click", "td", function() {
    $("#menu")
        .clone()
        .one("click", function() {
              var $td = $(this).closest("td"),
                  $tr = $td.parent();

              $td.html("boo");
              $tr.clone(/* true */).insertAfter($tr);
              $tr.remove();
              return false;
        })
        .appendTo(this)
        .show();
  });
});

http://jsfiddle.net/ryanwheale/3BUaT/26/

A: Its not browser's fault. Its yours. You are appending the menu list to the row. So the menu list is a child of the row. So if you hover over child, the parent will also be in hover state.
I've updated your jsfiddle:
Jsfiddle;
$(function() {
  $("td").on("click", function() {
    $("#menu")
        .clone()
        .one("click", function() {
          // this is key to reproduce it.
          $(this).closest("td").html("boo");
          return false;
        })
        .appendTo($(this).parent().parent().last())
        .show();
  });
});

A: You are appending the div #menu to the td with your function. Now the CSS is going to apply the hover state to the td when you mouseover either the td or the appended menu. Hovering over the menu applies the tr:hover td css, because the menu is now part of the td.

A: OK, so here is my proposed solution which takes the points from my comments (on Tejas Jayasheel's answer) into account: JSFiddle
The differences are:

*

*#menu is not cloned and not added to the table cell, but instead just repositioned (so the element is also only displayed once)

*CSS hover only applied if the 'no-js' class is present in the HTML element (need to be added in your original file)

*otherwise hover effect is achieved by applying the class "clicked" to the cell

*additionally when menu is already visible the hover effect is "disabled" by toggling another class on all TD's

*clicking outside the menu on the already "clicked" cell will close/hide the menu without any further action
.no-js td:hover,
td.hover-enabled:hover,
td.clicked {
      background-color: lightblue;
}

What is the expected behavior? The row's hover state should go away after dismissing the popup menu.

Maybe ...! But keep in mind that you are heavily "confusing" the browser by removing the hovered element from DOM. I guess that Safari and IE 8 simply "do not recognize" that former hovered part isn't hovered anymore. This may or may not be a "bug". But at least it is "bad practice/ writing style" and should simply be avoided!

Does anybody know a fix for Safari Version 7.0.1 and IE8? I would be okay with some manual way to "untrigger" the css hover state.

The "fix" is shown in my example. It is a common recommendation to add, remove or toggle classes when it comes to scripting and hover. By doing so you avoid the "problem" at all. Because even in future versions of any browser the behaviour in such cases is "unpredictable" at best.


text:
Q: In DocuSign how can i generate my integrator key for the production org? In DocuSign how can i generate my integrator key for the production org and go live? Can anybody help me on this?

A: Before you go live with your API integration, you need to enable one of your developer demo account integrator keys in a live production account. To enable your key, you need to pass a quick, automated review process, which is accessible from your developer demo account.
See this documentation


text:
Q: how can i override the text of datepicker's button in extjs(sencha)? i intend to override the text of datepicker's buttons in extjs(modern) which display as 'cancel' and 'done',i tried both
{
    xtype: 'datepickerfield',
    label: 'label',
    name: 'birthday',
    defaultPhonePickerConfig  :{
        doneButton : '确定',
        cancelButton : '取消'
    }
}

and
Ext.define("Ext.locale.zh_CN.field.DatePicker", {
    override: "Ext.field.DatePicker",
    defaultPhonePickerConfig  :{
        doneButton : '确定',
        cancelButton : '取消'
    }
})

but they not working,can you tell me what goes wrong?

A: You just need to use picker config of datepickerfield instead of defaultPhonePickerConfig
 picker: {
            doneButton: '确定',
            cancelButton: '取消'
        },


text:
Q: Cmd windows >> log.bat I'm trying to send the subroutine command with which it will subroutine that will create a log!
version of my code
echo echo del %%file%% >subroutine.bat >temp.bat

this part "echo del %file% >subroutine.bat" to be stored in the subroutine
Do you have a solution?

A: If you want echo del %%file%% >subroutine.bat to be stored in a file temp.bat then
echo echo del %%file%% ^>subroutine.bat >temp.bat

will do the job. The caret (^) turns off the special meaning of the redirector > so that it is echoed literally. You can do this with any character having a special meaning to cmd &^!<>| except %. To echo a % you need to double the % thus: echo %%


text:
Q: Prove Borel measurable function I want to prove that $\mathcal{f:[0,4\pi] \to \mathbb{R}:f(x)} = \left\{ \begin{matrix}\mathcal{\frac{1}{1+\sin(x)}} & \sin(x) \neq-1\\ 0& \sin(x)=-1 \end{matrix}\right.$ is a Borel measurable function.
This is the prove I have but I'm not completly convinced of its correctness.
Let's call $A=\{x \in [0,4\pi] | \sin(x) \neq -1\}$.
We prove that $A$ is measurable.
$A=\{x \in [0,4\pi] | \sin(x) \neq -1\}$= $\{x \in [0,4\pi] | \sin(x) = -1\}^{C}$ =$\{x \in [0,4\pi] | x=\frac{-\pi}{2}+2k\pi\}^{C}$=$[\{\frac{3\pi}{2}\}\bigcup \{\frac{7\pi}{2}\}]^{C}$=$B^{C}$
Because $B$ is a countable union of singletons is $B$ measurable. Because $A$ ist he complement of $B$ is $A$ also measurable.
Now we define $g:A\to\mathbb{R}: x\to\frac{1}{1+\sin(x)}$. $g$ is a continuous function on the domain so $g$ is a measurable function.
Now $f^{-1}(D)=g^{-1}(D)$ when $\{x|\sin(x)=-1\}$ not in $D$, with D a random Borel measurable set in $[0,4\pi]$ . and $f^{-1}(D)=g^{-1}(D) \bigcup A$ when $\{x|\sin(x)=-1\}$ in $D$


text:
Q: Получение даты через String.format() Есть код  для Android,цель выводить имя месяца:
    day_of_month = (TextView)findViewById(R.id.day_of_month);
    day_of_week = (TextView)findViewById(R.id.day_of_week);
    String month_s = String.format("%1$tB",new Date());
    String day_s = String.format("%1$tA",new Date());
    month.setText(month_s);
    day_of_week.setText(day_s);

Все хорошо,кроме падежа месяца:он выводиться как Марта,Февраля,Сентября и т.д,то есть в родительном падеже.Как вывести в именительном:Март,Февраль,Сентябрь?
Благодаря ответу код приобрёл такой вид:
SimpleDateFormat format = new SimpleDateFormat("yyyy;LLLL;dd;EEEE");
    String date_string = String.format("%s",format.format(new Date()));
    String[] date_array = date_string.split(";");
    year.setText(date_array[0]);
    month.setText(date_array[1]);
    day_of_month.setText(","+date_array[2]);
    day_of_week.setText(date_array[3]);

A: По-моему, через String.format - никак. С API 9 можно воспользоваться SimpleDateFormat с параметром "L" (stand-alone month):
SimpleDateFormat format = new SimpleDateFormat( "LLLL" );
System.out.printf( "sdf: %s%n", format.format( new Date() ) ); // sdf: Март

Аналогичный параметр для дня недели - "c", хотя для русского языка это не важно.


text:
Q: How to get the keys and values separately from the JSON string in swift3? I have a JSON string as:
{
    "messages": null,
    "data": [
        {
            "id": 27,
            "key": "ABC",
            "value": "5",
            "description": "Hi all"
        },
        {
            "id": 28,
            "key": "DEF",
            "value": "1",
            "description": "I am here"
        }]
 "status": 0
}

Now i need to get the values of the key and update it with the values which is present in core data.
For this i am using the code:
func updateAllRecords(responseArray: [ApplicationSettingsDataResponse]) {
    for settingsObject in responseArray {
    if #available(iOS 10.0, *) {
      let request = NSFetchRequest<ApplicationSettings>(entityName: "ApplicationSettings")

      do {
        let context = persistentContainer.viewContext
        let searchResults = try context.fetch(request)

        for settingsKeys in searchResults {

        if  settingsKeys.key == settingsObject.key {
            settingsKeys.value = settingsObject.value
            try context.save()
          }
        }

      } catch {
        print ("There was an error")
      }

    } else {

        }
  }
  }
}

Am I correct in doing this? Please have a view to this code.

A: First convert json response to dictionary and you can easily get the keys and value using
let keys = jsonDict.flatMap { $0.0 }

OUTPUT
["status", "data", "messages"]
For moreinfo i created demo
import UIKit
func convertToDictionary(text: String) -> [String:Any]?
{
    if let data = text.data(using: .utf8)
    {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? Dictionary
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

let str = "{\"messages\": 0,\"data\": [{\"id\": 27,\"key\": \"ABC\",\"value\": \"5\",\"description\": \"Hi all\"},{\"id\": 28,\"key\": \"DEF\",\"value\": \"1\",\"description\": \"I am here\"}],\"status\": 0}"

let str2 = "{\"messages\": 1,\"data\": [{\"id\": 27,\"key\": \"ABC\",\"value\": \"5\",\"description\": \"Hi all\"},{\"id\": 28,\"key\": \"DEF\",\"value\": \"1\",\"description\": \"I am not here\"}],\"status\": 1}"

let replaceWithDict:[String:Any] = convertToDictionary(text: str) ?? ["test":"test"]
var resultDict:[String:Any] = convertToDictionary(text: str2) ?? ["test":"test"]
let keys = replaceWithDict.flatMap { $0.0}
print(resultDict)
for key in keys
{  resultDict.updateValue(replaceWithDict[key], forKey: key) }
print(resultDict)

OUTPUT
Before update
    ["status": 1, "data": <__NSArrayI 0x608000034900>(
{
    description = "Hi all";
    id = 27;
    key = ABC;
    value = 5;
},
{
    description = "I am not here";
    id = 28;
    key = DEF;
    value = 1;
}
)
, "messages": 1]

AFTER UPDATE
["status": Optional(0), "data": Optional(<__NSArrayI 0x600000033460>(
{
    description = "Hi all";
    id = 27;
    key = ABC;
    value = 5;
},
{
    description = "I am here";
    id = 28;
    key = DEF;
    value = 1;
}
)
), "messages": Optional(0)]


text:
Q: NSIS file in use check methods Before starting my installation I need to check whether a particular file is in use. This is not an executable file, so the option to check for process existence is out of scope.
My job is to determine whether a database file is currently in use. I thought of renaming the file and get the return code. But unfortunately, there is no return code available for the API. Now I'm thinking about calling MoveFile with System plugin. Anyone can suggest anything else ?
Edit:
FileOpen $0 "$INSTDIR\FILENAME" r
${If} ${Errors}
 MessageBox MB_OK|MB_ICONEXCLAMATION "File in use"
${EndIf}
FileClose $0

I could achive the same by the above method. If there is other approaches, kindly let me know.

A: FileOpen is probably the best way to do this. Renaming is more complicated and probably has more timing issues.
Use FileOpen with a mode if you want to check if you can write to the file. Not sure if your app always opens the database for exclusive write access or if it has a read-only mode...


text:
Q: check duplicate values with messy data and conditional formatting I have a row with phone numbers and I want to highlight duplicates using conditional formatting. Problem is the numbers are often entered sloppily, sometimes there are whitespaces and sometimes a number starts with 0.
For example, the data could look like this:
123 456 78
0 123 45678
12345678
54312344
0543 12344

(the first 3 numbers and the last 2 should be highlighted as duplicates)
The formula I have written so far is this:
=COUNTIF(D:D,IF(LEFT(D1) = "0",SUBSTITUTE(RIGHT(D1,LEN(D1) - 1)," ",""), SUBSTITUTE(D1, " ", ""))) > 1

But that one does not work and I cannot figure out why.

A: You can use this formula on your conditional formatting:
=COUNTIF(D:D,REGEXREPLACE(D:D,"\s+|(0)+",""))

Screenshot:


text:
Q: Weighted features in machine learning I am a beginner in machine learning. So any help or suggestion would be of great help.
I have read that putting weights on features and Predicting is a very bad idea. But what if few features needs to be weighted.
In a classification problem let's say it's a common norm that age is most dependent, how do I give weights to this feature. I was thinking to normalize it but with a variance of 1.5 or 2 (other features with variance 1), I believe that this feature will have more weight. Is this fundamentally wrong ? If wrong any other method.
Does it effect differently for classification and regression problems ?

A: If we are talking specifically about random forests (as you tagged) then you can use the Weighted Subspace Random Forest algorithm (in R wsrf package). The algorithm determines a weight for each variable and then uses these during the model building.

The informativeness of a variable with respect to the class is
  measured by an information gain ratio. The measure is used as the
  probability of that variable being selected for inclusion in the
  variable subspace when splitting a specific node during the tree
  building process. Therefore, variables with higher values by the
  measure are more likely to be chosen as candidates during variable
  selection and a stronger tree can be built.

A: Generally if a feature has more Importance compared to other features and the model is Dense enough, with enough training sample, your model will automatically give it more Importance by optimizing weight matrices to account for that because we have partial derivatives in back propagation which calculate change by each connection, so it learns to give more importance to that feature on itself. If you don't normalize it, but scale it to a higher scale, you might have overstated it's important.
In practice a neural network works best if the inputs are centered and white. That means that their covariance is diagonal and the mean is the zero vector. This improves optimization of the neural net, since the hidden activation functions don't saturate that fast and thus do not give you near zero gradients early on in learning.
If you do scale just one feature up by a small value, it may or may not have desired effects, but the higher probability is of saturated gradients, so we avoid it.


text:
Q: Alias in KDE desktop session Can be set alias for desktop session like it can be set in terminal? In fact I am not sure if desktop sessions work in the same way. Is there some central interpreter which interprets the commands from all GUI applications (some kind of back-end shell) or how does it work?
What I would need to do is to set alias gvim="gvim --remote-tab-silent" for KDE session so in Krusader settings or in any other GUI app when I invoke gvim, gvim with --remote-tab-silent will be invoked.
How to do this (not wrapping in in script)?

A: It depends. Graphical programs usually use the same methods as non-graphical ones; that is, one of:

*

*Sometimes the program hands a list of parameters directly to the kernel, using something along the lines of:
if (fork() == 0)
    execlp("vim", "--remote-tab-silent", "/home/LeNoob/somefile.txt", NULL);

The various exec*() functions tell the kernel, "run exactly this thing and pass it this exact list of command-line options into argv[]."

*Other times, programs will ask the shell – /bin/sh – to interpret a command line:
system("vim $HOME/.bashrc");

It's practically the same shell as in terminals, but is run in non-interactive mode using the -c option. Also, it's always /bin/sh by convention, regardless of what shell (bash, zsh...) you've chosen to use interactively. So the above is rougly the same as:
if (fork() == 0)
    execl("/bin/sh", "-c", "vim $HOME/.bashrc");

(The shell itself, of course, will use exec*() directly.)

*Finally, desktop environments that use D-Bus can use it to start various services by simply sending a message to the desired "bus name" (e.g. org.gnome.gedit). Also known as "bus activation", when dbus-daemon sees a program sending a message to a bus name that nothing currently "owns", it searches its configuration for the program's path, and again uses exec() to start it.
This is a commonly used D-Bus feature, but mostly just for background services like "dconf". In the future, GNOME is planning to use this to also start regular apps like Nautilus or Gedit as well. However, right now, it uses the same method as all other DEs do, by reading the relevant .desktop file [see below] and exec()'ing the program directly, so I'm only including this for completeness.
(Of course, real programs do not have "vim" and "somefile.txt" hardcoded in them – they use something like getenv("EDITOR") and the desired file name – but you get the point.)
However, none of this actually matters, since the shell never interprets aliases in non-interactive mode, and while it would interpret shell functions, it will never read your ~/.bashrc to see which functions you have defined.

So the next questions are, how do you configure gVim as your text editor; and does your program search for gvim in $PATH directories, or does it take the full path /usr/bin/gvim from its configuration file?
Terminal-based programs use the $EDITOR variable, so instead of EDITOR=gvim you could use EDITOR="gvim --remote-tab-silent" in your ~/.profile or similar.
Desktop environments find gVim according to /usr/share/applications/gvim.desktop – specifically, the line Exec=gvim -f %F, which only tells them to start gvim but doesn't say where it is, so $PATH will be used. This means it can be overridden in two ways:

*

*you could make a script that wraps gvim and put it somewhere early in $PATH – for example, call the script ~/bin/gvim then put ~/bin at the beginning of $PATH;

*or you could copy the .desktop file from /usr to ~/.local/share/applications/gvim.desktop, and change the Exec= line to have the desired options:
Exec=gvim --remote-tab-silent -f %F

(Normally the changes will be picked up immediately, but if they don't, try running kbuildsycoca4 or kbuildsycoca4 --noincremental from a terminal.)