问:
Accessing Static variable from one class to another but getting incorrect value
This is my first question on stackoverflow,

I want to access static int variable of one class in another class but when i access this variable in another class it always gives me "zero".

This is First class:

```<code>package kk;

public class ag {
    public static int n=0;

    public static int as()
    {
        return n;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        n=3;
        n=n*5;
        System.out.println(n);
    }

}
</code>```

Here the output is 15 i.e. n=15 here.

Second class:

```<code>package kk;

public class ah extends ag {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //ag aa =new ag();
int k =ag.as();
System.out.println(k);
    }

}
</code>```

In this am trying to access the static variable n from First class but getting 0 as output but i want 15.

答:
Java keeps the values maintained for variables only for execution. When 1st program finishes execution, this object no longer exists. Hence for 2nd class execution this value will not be present & initialized to 0 according to definition.

If you really want it to be 15 then initialize it to 15.

```<code>package kk;

public class ag {
    public static int n=3*5;

    public static int as()
    {
        return n;
    }
}
</code>```

OR

call the main() of ag before calling as()

```<code>package kk;

public class ah extends ag {

    public static void main(String[] args) {
        ag.main(args);
        int k =ag.as();
        System.out.println(k);
    }
}
</code>```

Body:
This is my first question on stackoverflow,

I want to access static int variable of one class in another class but when i access this variable in another class it always gives me "zero".

This is First class:

package kk;

public class ag {
    public static int n=0;

    public static int as()
    {
        return n;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        n=3;
        n=n*5;
        System.out.println(n);
    }

}

Here the output is 15 i.e. n=15 here.

Second class:

package kk;

public class ah extends ag {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //ag aa =new ag();
int k =ag.as();
System.out.println(k);
    }

}

In this am trying to access the static variable n from First class but getting 0 as output but i want 15.

Body:
Java keeps the values maintained for variables only for execution. When 1st program finishes execution, this object no longer exists. Hence for 2nd class execution this value will not be present & initialized to 0 according to definition.

If you really want it to be 15 then initialize it to 15.

package kk;

public class ag {
    public static int n=3*5;

    public static int as()
    {
        return n;
    }
}

OR

call the main() of ag before calling as()

package kk;

public class ah extends ag {

    public static void main(String[] args) {
        ag.main(args);
        int k =ag.as();
        System.out.println(k);
    }
}


来源: stackexchange

答:
Your calculations:

n=3;
 n=n*5;

are evaluating in main() method of class ag, so it has no impact on class ah where you have second main() method - it looks like you have to programs, not just one.

ContentLicense: CC BY-SA 3.0

Title: Accessing Static variable from one class to another but getting incorrect value


问:
Does Java automatically save an 'evaluate' statement in a predefined Java variable?
Say I perform a simple add/concatenation statement:

```<code>variable + newInput
</code>```

Without setting the calculated value to a new variable, as in:

```<code>variable = variable + newInput
</code>```

or

```<code>variable += newInput
</code>```

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

```<code>Print(_)
</code>```

Is there anything like this in Java?

答:
You can for sure do:

```<code>variable + newInput
</code>```

but the result of that operation must be assigned to a variable, if not, it will get lost...

the most you can get is

```<code>variable += newInput
</code>```

whihch is similar to

```<code>variable = variable + newInput
</code>```

Body:
Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?

Body:
You can for sure do:

variable + newInput

but the result of that operation must be assigned to a variable, if not, it will get lost...

the most you can get is

variable += newInput

whihch is similar to

variable = variable + newInput


问:
Removing code from GitHub
Is there a way to entirely remove a directory and its history from GitHub?</p>

答:
If you are asking about deleting a project from GitHub, open your project, click the "Admin" tab (or browse directly to https://github.com/username/project_name/edit) and on the bottom of the page, click "Delete This Repository". It'll ask you to confirm this, and then it's gone.

If you just want to erase a part of your repository, you need to do it to your git repository and push it to GitHub.

GitHub has written a howto about this in their FAQ. I Haven't tried this myself, so I can't guide you further, but you probably can manage this yourself here on.

In either case, this, naturally, doesn't delete any third party pulls – if someone has pulled the repository before you deleted it, it's out, without you being able to do much about it (other than trying the "pretty please"-technique).

OwnerDisplayName: namin

ContentLicense: CC BY-SA 2.5

Title: Removing code from GitHub

OwnerDisplayName: wolfie


问:
How to save TextBox text to text file using streamwriter
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.</p>

```<code>public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }
</code>```

答:
Why do you want to use a StreamWriter? I think it's more easier like this:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";

    System.IO.File.WriteAllText(writerFile, this.textBlock.Text);
    System.IO.File.AppendAllText(writerFile, this.textBlock1.Text);
}
</code>```

Body:
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.

public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }

Body:
Why do you want to use a StreamWriter? I think it's more easier like this:

private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";

    System.IO.File.WriteAllText(writerFile, this.textBlock.Text);
    System.IO.File.AppendAllText(writerFile, this.textBlock1.Text);
}


问:
How to disable Toast Messages generated in Screen Pinning?
i'm developing lockscreen application, and i want to disable home button,

my app is - Device Owner and Device Administrator

now i'm usnig screen pinning for disable home button.

but if i started activity each time i get msg "Screen pinned" and on close "Screen Unpinned" and if click on home then, "Unpinning isn't allowed by your organisation"

I want to remove all those toast messages.

答:
Assuming you used the ADB to list your app as a Device Owner, you can use a similar command prompt to disable all toast messages:

```<code>adb shell appops set android TOAST_WINDOW deny
</code>```

For this command to work, cd to the directory where your adb.exe resides (except if you added it to the PATH). This will disable all toast messages to the android device that is connected (virtual or not). If there are multiple devices, the first one found will be selected.

ContentLicense: CC BY-SA 4.0

Body:
Assuming you used the ADB to list your app as a Device Owner, you can use a similar command prompt to disable all toast messages:

adb shell appops set android TOAST_WINDOW deny

For this command to work, cd to the directory where your adb.exe resides (except if you added it to the PATH). This will disable all toast messages to the android device that is connected (virtual or not). If there are multiple devices, the first one found will be selected.


问:
Calculate similarity matrix for the 1st column
I have started working on a few ML projects and use R as the preferred language. I am trying to build a basic recommendation system

http://www.dataperspective.info/2014/05/basic-recommendation-engine-using-r.html

I need to find the similarity matrix (according to the website) and using cosine function (in 'lsa' package) to find user_similarity.

```<code>library(lsa)
data_rating <- read.csv("recommendation_basic1.csv", header = TRUE)

x = data_rating[,2:7]
x[is.na(x)] = 0
print(x)

similarity_users <- cosine(as.matrix(x))
similarity_users
</code>```

But I need to find the similarity matrix among users and this code is giving me an output similarity matrix among the movies. Do I need to modify the below line?

```<code>x = data_rating[,2:7]
</code>```

PS. The recommendation_basic1.csv is the same as in the link.

答:
Putting this in so the question is not unanswered.

You can just use   similarity_users <- cosine(as.matrix(t(x)))

Here, the t is matrix transpose,  so it just switches the rows and columns  which is equivalent to switching the users and the movies.

Body:
I have started working on a few ML projects and use R as the preferred language. I am trying to build a basic recommendation system

http://www.dataperspective.info/2014/05/basic-recommendation-engine-using-r.html

I need to find the similarity matrix (according to the website) and using cosine function (in 'lsa' package) to find user_similarity.

library(lsa)
data_rating <- read.csv("recommendation_basic1.csv", header = TRUE)

x = data_rating[,2:7]
x[is.na(x)] = 0
print(x)

similarity_users <- cosine(as.matrix(x))
similarity_users

But I need to find the similarity matrix among users and this code is giving me an output similarity matrix among the movies. Do I need to modify the below line?

x = data_rating[,2:7]

PS. The recommendation_basic1.csv is the same as in the link.


问:
.NET Core MVC web API controller returns no data despite being identical to one that does
I am trying to build web api's using .NET Core

I have created some sample data and returned it in the default Get() function in the ValuesController created by default

```<code>namespace CoreWebAppMultiFunction.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
         // GET api/values
        [HttpGet]
        public List<Info> Get()
        {
            List<Info> info = new List<Info>();
            info.Add(new Info { ID = 0, Data = "this is on the test", Read = true });
            info.Add(new Info { ID = 2, Data = "this is also on the test", Read = false });
            return info;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
    }
}
</code>```

But when I create a new controller the new controller does not return anything, just a blank browser window. The browsers console has a 404: Unable to load resource with every URL I try to use.

```<code>namespace CoreWebAppMultiFunction.Controllers
{
    [Route("MoreInfo/[controller]")]
    public class MoreInfoController : Controller
    {
        [HttpGet]
        public SomeMoreInfo SomeInfo()
        {
            return new SomeMoreInfo { ID = 0, data = "data", yesno = true };
        }
    }
}
</code>```

Is it possible that I am trying to access it incorrectly in the browser URL? Or is there something wrong with how I set up the controller?

Thanks in advance

答:
So as it turns out, adding a route above a class hides all the functions except the HttpGet functions. And if there are multiple they are treated like overloads or the service simply returns absolutely nothing.

Following the example class that gets auto created seems to have been a poor move and confused me.

Body:
I am trying to build web api's using .NET Core

I have created some sample data and returned it in the default Get() function in the ValuesController created by default

namespace CoreWebAppMultiFunction.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
         // GET api/values
        [HttpGet]
        public List<Info> Get()
        {
            List<Info> info = new List<Info>();
            info.Add(new Info { ID = 0, Data = "this is on the test", Read = true });
            info.Add(new Info { ID = 2, Data = "this is also on the test", Read = false });
            return info;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
    }
}

But when I create a new controller the new controller does not return anything, just a blank browser window. The browsers console has a 404: Unable to load resource with every URL I try to use.

namespace CoreWebAppMultiFunction.Controllers
{
    [Route("MoreInfo/[controller]")]
    public class MoreInfoController : Controller
    {
        [HttpGet]
        public SomeMoreInfo SomeInfo()
        {
            return new SomeMoreInfo { ID = 0, data = "data", yesno = true };
        }
    }
}

Is it possible that I am trying to access it incorrectly in the browser URL? Or is there something wrong with how I set up the controller?

Thanks in advance


问:
iOS implement the file browser push same view controller show error
I need create the file browser function using the UITableViewController.

I load the data in the tableview, if user selected row at index path is a folder,

I want to push the same data structure and uitableview and using reload tableview to change the data show in the save view controller.

So I try to add

```<code> [self.navigationController pushViewController:self animated:YES];
</code>```

in the didSelectRowAtIndexPath delegate method.

All method code :

```<code> -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

     [self.navigationController pushViewController:self animated:YES];
 }
</code>```

But I got the error log is below

```<code> Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Pushing the same view controller instance more than once is not supported
</code>```

I using pushViewController because the iOS can show the back to preview file title and have  navigation animate.

Have anyone can teach me how to resolve the problem or have some better function implement method?

thank you very much.

答:
Possible solution for it - it's allocate new instance of your class and push it into navigationController, instead of pushing self

Something like that:

```<code> -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     YourController *controller = [[YourController alloc] init]
     [self.navigationController pushViewController: controller animated:YES];
 }
</code>```

Body:
I need create the file browser function using the UITableViewController.

I load the data in the tableview, if user selected row at index path is a folder,

I want to push the same data structure and uitableview and using reload tableview to change the data show in the save view controller.

So I try to add

 [self.navigationController pushViewController:self animated:YES];

in the didSelectRowAtIndexPath delegate method.

All method code :

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

     [self.navigationController pushViewController:self animated:YES];
 }

But I got the error log is below

 Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Pushing the same view controller instance more than once is not supported

I using pushViewController because the iOS can show the back to preview file title and have  navigation animate.

Have anyone can teach me how to resolve the problem or have some better function implement method?

thank you very much.

Body:
Possible solution for it - it's allocate new instance of your class and push it into navigationController, instead of pushing self

Something like that:

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     YourController *controller = [[YourController alloc] init]
     [self.navigationController pushViewController: controller animated:YES];
 }


问:
Waiting for exact value from SERIAL PORT VB.net
I'm trying to wait microcontroller print "OK" to Serial Port, and VB.net check that "OK" and assign that value to string variable - check_OK. The first problem i faced - its data recevied event handler i just dont know how to make it check for exact value from serial port. I used Richtextbox1 to save ok from serial port then trying make its value = check_OK. I tried like this: </p>

```<code>Public Class Form1
Dim check_OK As String
Dim OK_rs As Byte

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String)
    If Me.RichTextBox1.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})

    Else
        Me.RichTextBox1.Text = ""
        Me.RichTextBox1.Text &= [text]
        If RichTextBox1.Text = "O" Or RichTextBox1.Text = "K" Then
            check_OK = check_OK & RichTextBox1.Text
        End If
    End If
End Sub
</code>```

答:
These serial communication problems often benefit from being broken down into several parts.  Since the microcontroller is the sender, the first thing I'd check is whether it's sending properly.  To do this, connect to a terminal program first.  This takes your VB code out of the picture.

Now, if the terminal program is getting the correct input from the microcontroller, you've just proved half of your system correct and you can then focus on the VB side.  Divide and conquer. :)

Body:
I'm trying to wait microcontroller print "OK" to Serial Port, and VB.net check that "OK" and assign that value to string variable - check_OK. The first problem i faced - its data recevied event handler i just dont know how to make it check for exact value from serial port. I used Richtextbox1 to save ok from serial port then trying make its value = check_OK. I tried like this:

Public Class Form1
Dim check_OK As String
Dim OK_rs As Byte

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String)
    If Me.RichTextBox1.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})

    Else
        Me.RichTextBox1.Text = ""
        Me.RichTextBox1.Text &= [text]
        If RichTextBox1.Text = "O" Or RichTextBox1.Text = "K" Then
            check_OK = check_OK & RichTextBox1.Text
        End If
    End If
End Sub


问:
Haskell Streams (Comonadic): Infinite?
I've seen streams used as the default example of a comonad, but I can't quite figure how they're infinite, but not.

Assume we have the data constructor (from here)

```<code>data Stream a = a :> Stream a
</code>```

How do we finally finish off a stream? Do we write it w/ an undefined at the end? I get that the language is lazy, but somewhere the knot must be cut, right? Am I just wrong?

答:
A stream is inherently infinite; you can't create a finite stream. Compare Stream and List:

```<code>data List   a = Empty | a :  List a
data Stream a =         a :> Stream a
</code>```

You can create a finite list because of Empty constructor; it is possible to create a List value without referring to another List value. A Stream value, on the other hand, can only be created by using another Stream value. Any time you pattern match on a Stream, you get a value of type a and another Stream value.

"Finishing" a stream simply means you stop pulling values from it, not that you ever reach the "end" of the stream.

In practice, this means you cannot instantiate a full stream in memory; you can only build it on-demand, typically by calling a function to generate remainder of the stream when pattern matching on the :> constructor.

Title: Haskell Streams (Comonadic): Infinite?

Body:
I've seen streams used as the default example of a comonad, but I can't quite figure how they're infinite, but not.

Assume we have the data constructor (from here)

data Stream a = a :> Stream a

How do we finally finish off a stream? Do we write it w/ an undefined at the end? I get that the language is lazy, but somewhere the knot must be cut, right? Am I just wrong?

Body:
A stream is inherently infinite; you can't create a finite stream. Compare Stream and List:

data List   a = Empty | a :  List a
data Stream a =         a :> Stream a

You can create a finite list because of Empty constructor; it is possible to create a List value without referring to another List value. A Stream value, on the other hand, can only be created by using another Stream value. Any time you pattern match on a Stream, you get a value of type a and another Stream value.

"Finishing" a stream simply means you stop pulling values from it, not that you ever reach the "end" of the stream.

In practice, this means you cannot instantiate a full stream in memory; you can only build it on-demand, typically by calling a function to generate remainder of the stream when pattern matching on the :> constructor.


问:
How to implement this constraint in Python with Gurobi?
I have an expression given below and i was wondering if you can help me to formalize as an ILP constraint in order to solve by Gurobi optimizer (Python):

forall ( y in Y), forall (j in M), forall (x in X):
 IF r[x][y] = 1 and c[y,j] = 1 THEN p[x,a] = 1 , forall (a in {U[j],...,W[j] - 1} )
Where:
r[x][y], c[y,j] and p[x,a] are 3 binary variables;
U[j] and W[j] are 2 positive integer variables, where U[j] + beta = W[j]
(beta is a positive constant)

I know that this constraint can be written  as a logical implication in conjunctive normal form: x ∧ y → z
I have already tried this solution: z≥x+y−1  together with several other possibilities :(
But, i had an error with Gurobi solver

My Python code for this constraint is as follows:

for y in Y:

for j in M:

for x in X:

for a in range(int(U[j]),int(W[j])):

M1.addConstr(r[x][y] + c[y,j] - 1 <=  p[x,a], 'TileRequirement_%s_%s_%s_%s'%(y,j,x,a))

I always get the error in this line: for a in range(int(U[j]),int(W[j])):, because both U[j] and W[j] are defined as positive integer variables
So, can someone help me ?
Thanks :)

Best regards
Khadija

答:
# -*- coding: utf-8 -*-
#programmer: Khadija HS
#date: June 2017
#name: B-C-MCT PLNE Model (Khadija.HS,2017) <---> BCMCT1.py

"""
Solve the B-C-MCTP (fixed Z & min Delta) sub-pb of 3-PSDPP (K-HS et al.,2016), where:
    X: list of input tiles (tile x)
    Y: list of output tiles (tile y)
    Ry: requirement relation between  X & Y
        <---> is a List of Y list, each sub List define the input tiles required by each y
        <---> rxy: incidence matrix (0-1): Input Tiles/Output Tiles (Configuration of each output tile % input tile)
        <---> Ry is a list of list where Row <--- x & Column <--- y
    alpha: prefetches times (uniform)
    beta: computations times (uniform)
    Delta: the Total completion time (to be determined)
"""

from gurobipy import *
""" Find Yx: set of output tiles y that required the input tile x """
def OuputTileTe(Ry,X):
    Yx=[]
    for x in X:
        Yx.append(OuputTileTex(Ry,x))
    return Yx
""" Find B: List Ts for x """
def OuputTileTex(Ry,x):
    B=[]
    for y in range(len(Ry)):
        if x in Ry[y]:
            B.append(y)
    return B

""" Find N: Max Value of N ( <---> sum(len(Ry),y in Y)) """
def NbPrefetchTile(S):
    N=0
    for k in range(0,len(S)):
        N += len(S[k])
    return  N

""" BCMCT1 - Model"""
def BCMCT1(X,Y,Z,Ry,alpha,beta):
    # DET VBLES: M,N,Z1,T,K,L
    M=list(range(len(Y)))                   # List of Computation steps
    nb=NbPrefetchTile(Ry)                   # Number of prefetches (Big Value of N)
    N=range(nb)                             # List of Prefetches steps
    ListZ=range(Z)                          # List of Buffers
    T=range(alpha*len(X) + beta*len(Y))     # List of Start Date times (Computation+Prefetches)
    K=range(alpha)                          # Interval Time of a prefetch step
    L=range(beta)                           # Interval Time of a compute step

    # DET VBLES: A,T1,B,Yx
    A=alpha*nb + beta*len(Y)                # Big Value of Total Completion Time
    T1=range(A)                             # List of Start Date times (Computation+Prefetches)
    minLen=min([len(elt) for elt in Ry])    #1,alpha+1
    B=alpha*minLen + beta*len(Y)            # Value of LB2
    Yx=OuputTileTe(Ry,X)                    # List of output tile y, for x, x in X

    # MODEL
    M1=Model("BCMCT1")

    # CONSTANT VARIABLES
    r=[[0]*len(Y) for i in range(len(X))]
    for x in X:
        for y in Y:
            if x in Ry[Y.index(y)]:
                r[x][y]=1

    # DECISION VARIABLES
    c,p,q,U,W,a={},{},{},{},{},{}

    for y in Y:
        for j in M:
            c[y,j]=M1.addVar(vtype=GRB.BINARY,name="c[%s,%s]"%(y,j)) #obj=beta,

    for x in X:
        for t in T:
            p[x,t]=M1.addVar(vtype=GRB.BINARY,name="p[%s,%s]"%(x,t)) #obj=1,

    for x in X:
        for t in T:
            q[x,t]=M1.addVar(vtype=GRB.BINARY,name="q[%s,%s]"%(x,t)) #obj=1,

    for j in M:
        U[j]=M1.addVar(vtype='I',name="U_%s"%j)
        W[j]=M1.addVar(obj=1,vtype='I',name="W_%s"%j)

    for j in M:
        a[j]=M1.addVar(vtype=GRB.BINARY,name="a[%s]"%j)

    # MODEL UPDATE
    M1.update()

    # OBJECTIVE
    Obj=W[len(M)-1]
    M1.setObjective(Obj, GRB.MINIMIZE)

    # CONSTRAINTS
    """ (1): Computation's Assignement Constraints """
    """ (a) """
    for j in M:
        M1.addConstr(quicksum(c[y,j] for y in Y)==1,'ComputeAssign1_%s'%j)
    """ (b) """
    for y in Y:
        M1.addConstr(quicksum(c[y,j] for j in M)==1,'ComputeAssign2_%s'%y)

    """ (2): Buffer's Constraints """
    for t in T:
        M1.addConstr(quicksum(p[x,t] for x in X) <= Z,'BufferNb_%s'%t)

    """ 3): Computation/Prefetch's Constraints """
    """ (a) """
    for t in T:
        M1.addConstr(quicksum(q[x,t] for x in X) <= 1,'PrefetchTileA_%s'%t)

    """ (b) """
    for x in X:
        for t in T[1:]:
            for k in K:
                M1.addConstr(p[x,t] - p[x,t-1] <= q[x,t-k],'PrefetchTileB_%s_%s_%s'%(x,t,k))

    """ (c) """
    for y in Y:
        for j in M:
            for x in X:
                for t in T:
                    M1.addConstr(3 - r[x][y] - c[y,j] - a[j] + p[x,t] >= 1, 'TileRequirement_%s_%s_%s_%s'%(y,j,x,t))

    """ (5): Computation Time's Constraint """
    """ (a) """
    for j in M:
        M1.addConstr(W[j] == U[j] + beta,'ComputeTime1_%s'%j)

    """ (b) """
    for j in M[1:]:
        M1.addConstr(W[j-1] <= U[j],'ComputeTime2_%s'%j)

    # SOLUTION
    M1.__data=c,p,q,U,W,a
    return M1```

Please find attached my detailed ILP
May be, it will be easier to understand my question about constraint number 17
where,

L = range(beta)

K=range(alpha)

\Lambda (Big M)=alpha*Z*Y+beta*Y

r[x][y]= 1 if x in Ry and 0 otherwise (forall x in X & forall y in Y) : incidence matrix given as input data

I will give you an example that is very simple to understand more my problem as follows:
let:
X=[X1,X2,X3,X4]
Y=[Y1,Y2,Y3]
Ry=[(X1,X2,X3), (X2,X4),(X1,X3,X4)]
Z=3
alpha=2, beta=4

The objective is to find a computation sequence for computing Y1,Y2 & Y3 in order to minimize Delta (total completion time)

An optimal solution is: Y2, Y3, Y1 (or Y2,Y1,Y3) with \Delta=17

ILP Formulation

Body:
# -*- coding: utf-8 -*-
#programmer: Khadija HS
#date: June 2017
#name: B-C-MCT PLNE Model (Khadija.HS,2017) <---> BCMCT1.py

"""
Solve the B-C-MCTP (fixed Z & min Delta) sub-pb of 3-PSDPP (K-HS et al.,2016), where:
    X: list of input tiles (tile x)
    Y: list of output tiles (tile y)
    Ry: requirement relation between  X & Y
        <---> is a List of Y list, each sub List define the input tiles required by each y
        <---> rxy: incidence matrix (0-1): Input Tiles/Output Tiles (Configuration of each output tile % input tile)
        <---> Ry is a list of list where Row <--- x & Column <--- y
    alpha: prefetches times (uniform)
    beta: computations times (uniform)
    Delta: the Total completion time (to be determined)
"""

from gurobipy import *
""" Find Yx: set of output tiles y that required the input tile x """
def OuputTileTe(Ry,X):
    Yx=[]
    for x in X:
        Yx.append(OuputTileTex(Ry,x))
    return Yx
""" Find B: List Ts for x """
def OuputTileTex(Ry,x):
    B=[]
    for y in range(len(Ry)):
        if x in Ry[y]:
            B.append(y)
    return B

""" Find N: Max Value of N ( <---> sum(len(Ry),y in Y)) """
def NbPrefetchTile(S):
    N=0
    for k in range(0,len(S)):
        N += len(S[k])
    return  N

""" BCMCT1 - Model"""
def BCMCT1(X,Y,Z,Ry,alpha,beta):
    # DET VBLES: M,N,Z1,T,K,L
    M=list(range(len(Y)))                   # List of Computation steps
    nb=NbPrefetchTile(Ry)                   # Number of prefetches (Big Value of N)
    N=range(nb)                             # List of Prefetches steps
    ListZ=range(Z)                          # List of Buffers
    T=range(alpha*len(X) + beta*len(Y))     # List of Start Date times (Computation+Prefetches)
    K=range(alpha)                          # Interval Time of a prefetch step
    L=range(beta)                           # Interval Time of a compute step

    # DET VBLES: A,T1,B,Yx
    A=alpha*nb + beta*len(Y)                # Big Value of Total Completion Time
    T1=range(A)                             # List of Start Date times (Computation+Prefetches)
    minLen=min([len(elt) for elt in Ry])    #1,alpha+1
    B=alpha*minLen + beta*len(Y)            # Value of LB2
    Yx=OuputTileTe(Ry,X)                    # List of output tile y, for x, x in X

    # MODEL
    M1=Model("BCMCT1")

    # CONSTANT VARIABLES
    r=[[0]*len(Y) for i in range(len(X))]
    for x in X:
        for y in Y:
            if x in Ry[Y.index(y)]:
                r[x][y]=1

    # DECISION VARIABLES
    c,p,q,U,W,a={},{},{},{},{},{}

    for y in Y:
        for j in M:
            c[y,j]=M1.addVar(vtype=GRB.BINARY,name="c[%s,%s]"%(y,j)) #obj=beta,

    for x in X:
        for t in T:
            p[x,t]=M1.addVar(vtype=GRB.BINARY,name="p[%s,%s]"%(x,t)) #obj=1,

    for x in X:
        for t in T:
            q[x,t]=M1.addVar(vtype=GRB.BINARY,name="q[%s,%s]"%(x,t)) #obj=1,

    for j in M:
        U[j]=M1.addVar(vtype='I',name="U_%s"%j)
        W[j]=M1.addVar(obj=1,vtype='I',name="W_%s"%j)

    for j in M:
        a[j]=M1.addVar(vtype=GRB.BINARY,name="a[%s]"%j)

    # MODEL UPDATE
    M1.update()

    # OBJECTIVE
    Obj=W[len(M)-1]
    M1.setObjective(Obj, GRB.MINIMIZE)

    # CONSTRAINTS
    """ (1): Computation's Assignement Constraints """
    """ (a) """
    for j in M:
        M1.addConstr(quicksum(c[y,j] for y in Y)==1,'ComputeAssign1_%s'%j)
    """ (b) """
    for y in Y:
        M1.addConstr(quicksum(c[y,j] for j in M)==1,'ComputeAssign2_%s'%y)

    """ (2): Buffer's Constraints """
    for t in T:
        M1.addConstr(quicksum(p[x,t] for x in X) <= Z,'BufferNb_%s'%t)

    """ 3): Computation/Prefetch's Constraints """
    """ (a) """
    for t in T:
        M1.addConstr(quicksum(q[x,t] for x in X) <= 1,'PrefetchTileA_%s'%t)

    """ (b) """
    for x in X:
        for t in T[1:]:
            for k in K:
                M1.addConstr(p[x,t] - p[x,t-1] <= q[x,t-k],'PrefetchTileB_%s_%s_%s'%(x,t,k))

    """ (c) """
    for y in Y:
        for j in M:
            for x in X:
                for t in T:
                    M1.addConstr(3 - r[x][y] - c[y,j] - a[j] + p[x,t] >= 1, 'TileRequirement_%s_%s_%s_%s'%(y,j,x,t))

    """ (5): Computation Time's Constraint """
    """ (a) """
    for j in M:
        M1.addConstr(W[j] == U[j] + beta,'ComputeTime1_%s'%j)

    """ (b) """
    for j in M[1:]:
        M1.addConstr(W[j-1] <= U[j],'ComputeTime2_%s'%j)

    # SOLUTION
    M1.__data=c,p,q,U,W,a
    return M1

Please find attached my detailed ILP
May be, it will be easier to understand my question about constraint number 17
where,

L = range(beta)

K=range(alpha)

\Lambda (Big M)=alpha*Z*Y+beta*Y

r[x][y]= 1 if x in Ry and 0 otherwise (forall x in X & forall y in Y) : incidence matrix given as input data

I will give you an example that is very simple to understand more my problem as follows:
let:
X=[X1,X2,X3,X4]
Y=[Y1,Y2,Y3]
Ry=[(X1,X2,X3), (X2,X4),(X1,X3,X4)]
Z=3
alpha=2, beta=4

The objective is to find a computation sequence for computing Y1,Y2 & Y3 in order to minimize Delta (total completion time)

An optimal solution is: Y2, Y3, Y1 (or Y2,Y1,Y3) with \Delta=17

ILP Formulation


问:
Samsung Galaxy S7 Edge ignores datePickerMode
I am setting the datePickerMode in my styles file to spinner like this:

```<code><style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:dialogTheme">@style/MyDialogTheme</item>
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>

<style name="ItvDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>

<style name="MyDatePicker" parent="android:Widget.Material.Light.DatePicker">
    <item name="android:datePickerMode">spinner</item>
</style>
</code>```

and then create a DatePicker

```<code>DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
        //handle result
        }
    };

DatePickerDialog dialog = new DatePickerDialog(this, onDateSetListener, dob.getYear(), dob.getMonth() - 1,
            dob.getDay());

dialog.show();
</code>```

This worked fine across a lot of devices including the Samsung Galaxy S7 Edge on Android 6, but since updating the device to Android 7 it ignores the mode spinner and shows the calendar.

The spinner works fine on an One Plus 3 on Android 7.1.1.

Any ideas?

答:
You Should try to raise the
  targetSdkVersion to 24 because of the android 7.0

Body:
I am setting the datePickerMode in my styles file to spinner like this:

and then create a DatePicker

DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
        //handle result
        }
    };

DatePickerDialog dialog = new DatePickerDialog(this, onDateSetListener, dob.getYear(), dob.getMonth() - 1,
            dob.getDay());

dialog.show();

This worked fine across a lot of devices including the Samsung Galaxy S7 Edge on Android 6, but since updating the device to Android 7 it ignores the mode spinner and shows the calendar.

The spinner works fine on an One Plus 3 on Android 7.1.1.

Any ideas?


问:
How to disable the options in select element based on another select element with same option values?
I have to disable the slect options based on value selected in another select.

```<code><select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

   <select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>
</code>```

here I get same data,but my requirement is,if I select two in first dropdown I need to disable the values less than two in second dropdown and If i select two in dropdown two I need to disable the values greater than two in first dropdown.

Any help would be appreciated.

答:
Try following code:

    </p>

```<code><script>
var app = angular.module('myApp1', []);
app.controller('myCtrl', function($scope) {
    //get your value and compare
});
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function($scope) {
    //get your value and compare
});

</script>
</code>```

Body:
I have to disable the slect options based on value selected in another select.

<select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

   <select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

here I get same data,but my requirement is,if I select two in first dropdown I need to disable the values less than two in second dropdown and If i select two in dropdown two I need to disable the values greater than two in first dropdown.

Any help would be appreciated.

Body:
Try following code:

<script>
var app = angular.module('myApp1', []);
app.controller('myCtrl', function($scope) {
    //get your value and compare
});
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function($scope) {
    //get your value and compare
});

</script>


问:
Winforms Deployment Project running only with Administrator priviliges
I have created a deployment project for my C# WinForms application. After installing the exe of this deployed project, I am able to run it only as administrator. How do I make this work without "Run As Administrator" ?

答:
Remove <requestedExecutionLevel level="requireAdministrator" uiAccess="true" /> from your manifest file.

If that doesn't help, try Manifest View - available from https://weblogs.asp.net/kennykerr/manifest-view-1-0 .


问:
iTextSharp and Xamarin
I'm trying to use  iTextSharp dll in an Xamarin App, but I´m not able to compile because I´ve received this error:</p>

```<code>Error       Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Drawing.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
   at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver)   App2.Android    C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets   1399    2
</code>```

答:
You need to use Xamarin Port.

Xam.iTextSharpLGPL ( Install-Package Xam.iTextSharpLGPL)

You can download package from NuGet
https://www.nuget.org/packages/Xam.iTextSharpLGPL/

Title: iTextSharp and Xamarin

Body:
I'm trying to use  iTextSharp dll in an Xamarin App, but I´m not able to compile because I´ve received this error:

Error       Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Drawing.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
   at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver)   App2.Android    C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets   1399    2


问:
Java orm problem
There is a big table business_apply in our system. It's used to store business apply information, and contains hundreds of columns.

When business type differs, a column may mean different things.

What kind of orm framework can make our life easier? Hibernate, iBatis or something else?

答:
You can check out Cayenne.

Have a look at http://cayenne.apache.org/doc30/scripting-sqltemplate.html
and
http://cayenne.apache.org/doc30/data-rows.html

This way you can still benefit from ORM API without sacrificing speed.

Title: Java orm problem


问:
Error on compiling MongoDB C++11 driver
I'm trying to compile MongoDB C++11 driver with the following CMake command.

```<code>cmake -G "Visual Studio 15 2017 Win64" \
"-DCMAKE_INSTALL_PREFIX=../installation/cxx-driver" \
"-DLIBBSON_DIR=../installation/libbson" \
"-DLIBMONGOC_DIR=../installation/c-driver" \
"-DCMAKE_PREFIX_PATH=../installation" \
"-DBOOST_ROOT=E:/Softwares/Libraries/Boost/boost_1_64_0" \
../mongo-cxx-driver-r3.1.1
</code>```

Got the following error.

```<code>fatal error C1083: Cannot open include file: 'bson.h': No such file or directory
</code>```

The 'bson.h' file exists in the following path

```<code>../installation/libbson/include/libbson-1.0
</code>```

My expectation is either the -DLIBBSON_DIR or the -DCMAKE_PREFIX_PATH directives would help showing where include directory is. What am I doing wrong?

答:
Remove unnecessary quotes:</p>

```<code>cmake -G "Visual Studio 15 2017 Win64" \
-DCMAKE_INSTALL_PREFIX=../installation/cxx-driver \
-DLIBBSON_DIR=../installation/libbson \
-DLIBMONGOC_DIR=../installation/c-driver \
-DCMAKE_PREFIX_PATH=../installation \
-DBOOST_ROOT=E:/Softwares/Libraries/Boost/boost_1_64_0 \
../mongo-cxx-driver-r3.1.1
</code>```

Title: Error on compiling MongoDB C++11 driver

Body:
I'm trying to compile MongoDB C++11 driver with the following CMake command.

cmake -G "Visual Studio 15 2017 Win64" \
"-DCMAKE_INSTALL_PREFIX=../installation/cxx-driver" \
"-DLIBBSON_DIR=../installation/libbson" \
"-DLIBMONGOC_DIR=../installation/c-driver" \
"-DCMAKE_PREFIX_PATH=../installation" \
"-DBOOST_ROOT=E:/Softwares/Libraries/Boost/boost_1_64_0" \
../mongo-cxx-driver-r3.1.1

Got the following error.

fatal error C1083: Cannot open include file: 'bson.h': No such file or directory

The 'bson.h' file exists in the following path

../installation/libbson/include/libbson-1.0

My expectation is either the -DLIBBSON_DIR or the -DCMAKE_PREFIX_PATH directives would help showing where include directory is. What am I doing wrong?

Body:
Remove unnecessary quotes:

cmake -G "Visual Studio 15 2017 Win64" \
-DCMAKE_INSTALL_PREFIX=../installation/cxx-driver \
-DLIBBSON_DIR=../installation/libbson \
-DLIBMONGOC_DIR=../installation/c-driver \
-DCMAKE_PREFIX_PATH=../installation \
-DBOOST_ROOT=E:/Softwares/Libraries/Boost/boost_1_64_0 \
../mongo-cxx-driver-r3.1.1


问:
Remove last numbers in rows in R
This is a fragment of my data.frame:

```<code>MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t
</code>```

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

答:
We can use sub to match the dot (\\. -escape as it is a metacharacter meaning any character) followed by one or more numbers (\\d+) at the end ($) of the string and replace by blank ("")

```<code>df1$col1 <- sub("\\.\\d+$", "", df1$col1)
df1$col1
#[1] "MC0_1_N" "MC0_1_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N"
#[8] "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N"
</code>```

NOTE: Here we assumed it is the first column.  If it is row.names then replace df1$col1 with row.names(df1)

i.e.

```<code>row.names(df1) <- sub("\\.\\d+$", "", row.names(df1))
</code>```

Title: Remove last numbers in rows in R

Body:
This is a fragment of my data.frame:

MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

Body:
We can use sub to match the dot (\\. -escape as it is a metacharacter meaning any character) followed by one or more numbers (\\d+) at the end ($) of the string and replace by blank ("")

df1$col1 <- sub("\\.\\d+$", "", df1$col1)
df1$col1
#[1] "MC0_1_N" "MC0_1_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N"
#[8] "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N" "MC0_5_N"

NOTE: Here we assumed it is the first column.  If it is row.names then replace df1$col1 with row.names(df1)

i.e.

row.names(df1) <- sub("\\.\\d+$", "", row.names(df1))


问:
Alter table structure to match copy table
I have 2 tables corporate and corporate_copy. Initially they were same in structure but people started added new columns into corporate and forgot do do so for corporate_copy.

Somewhere in the application there is less used functionality that copies data from corporate to corporate_copy and that kept failing without anyone noticing. Now I have to add 28 columns (ofcourse with same type and length and constraints etc....).

I know it can be done in one ALTER TABLE statement but I still feel it is lengthy task.

Do we have any luxury that will make copy table same as main table by keeping data and adding default values in newly added columns?

I am asking much but is there anything like that?

答:
```<code>--Generate a dynamic query which contain all the missing column list and Execute it
--for eg I tried Something

    BEGIN TRAN

    DECLARE  @SqlSelect NVARCHAR(MAX),@ColumnDeclaration VARCHAR(2000)

    SELECT DISTINCT ' '+COLUMN_NAME+' '+ DATA_TYPE +' '+ISNULL(CONVERT(NVARCHAR(10), CHARACTER_MAXIMUM_LENGTH ),'')+' 'Missing_Column INTO #T FROM INFORMATION_SCHEMA.COLUMNS a
    WHERE a.column_name not in (SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS b
    WHERE b.table_name in ('Corporate_Copy'))
    and a.table_name in ('Corporate')

    SELECT @ColumnDeclaration=STUFF((
                                SELECT ', ' + Missing_Column
                                FROM #T
                                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(max)'), 1, 1, '')

    SET @SqlSelect=' ALTER TABLE Corporate_Copy  Add'+ @ColumnDeclaration + ');'
    PRINT @SqlSelect

    ROLLBACK TRAN
</code>```


问:
ForEach() : Why can't use break/continue inside
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

```<code>lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);
</code>```

Error:

"No enclosing loop out of which to
break or continue"

答: break and continue are C# language keywords that require compiler support. ForEach, to the C# compiler, is just a method.</p>

Body:
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to
break or continue"


问:
laravel eloquent count with a groupby
If I'd have the following table structure

```<code>ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User
</code>```

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

```<code>[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]
</code>```

答: Also, you can use DB::select('select * from xxx group by yyy') to execute the query.

Title: laravel eloquent count with a groupby

Body:
If I'd have the following table structure

ID      name   type
1       John   Admin
2       Johan  Admin
3       Sam    User
4       Rick   User

How would I use Laravels Eloquent with a groupBy query, but still grab each record, and also sum up per type how many records each type has?

Example result would be as follow

[
    'type' => 'Admin',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'John'
        ],
        1 => [
            'name' => 'Johan'
        ]
    ]
],
[
    'type' => 'User',
    'records' => 2
    'data' => [
        0 => [
            'name' => 'Sam'
        ],
        1 => [
            'name' => 'Rick'
        ]
    ]
]


问:
Can you provide no knowledge SaaS, if server only serves requests with a VPN/Tor IP address?
to protect users you would reject serving requests originating from non-VPN/Tor IP addresses.

how can you get and keep updated a list of

the Top/most secure VPN providers's IP addresses? (others won't be approved by/work with the service)

Tor exit nodes IP addresses?

答:
Tor exit nodes can be listed with https://check.torproject.org/cgi-bin/TorBulkExitList.py, or you can get them programmatically like a DNS lookup using https://www.torproject.org/projects/tordnsel.html.en

The problems with listing VPN IP addresses are many:

There are many VPN providers, and they change frequently;

Some VPN providers provide reasonable security, many do not, and it's
extremely difficult to verify;

Users can roll their own VPN using a cloud service;

Many VPNs do NOT want their IP addresses known, and may even change

them regularly, in order to increase protection for their users.


问:
3D Numpy arrays into ITK SNAP
How to convert 3D Numpy arrays, which represent video of medical data to a proper file format that is compatible for ITK-SNAP application to do manual segmentation?</p>

答: PyBuffer should be the class of choice for that conversion. It is part of Module_BridgeNumPy which needs to be enabled in CMake configuration step of ITK. If you want to use SimpleITK, this should help. Once you have a normal itk::Image, you can write it to disk using one of many supported formats.</p>

Title: 3D Numpy arrays into ITK SNAP


问:
ServletPath changes from RESTEasy 3.0.10.Final to 3.0.23.Final
I've upgraded my Wildfly 8.2.1.Final with a new version of RESTEasy to be able to use SNI support (not available in 3.0.10.Final version). So I copied the resteasy-jboss-modules-3.0.23.Final content in my /wildfly/modules/system/layers/base directory. But now I have a different behavior ! my Rest services are not called. And when I've inspected the context/servlet path I found different values between 3.0.10.Final and 3.0.23.Final versions:

With RESTEasy 3.0.10.Final I have the following values :

```<code>        String contextPath = request.getContextPath(); // = "/myApp"
        String servletPath = request.getServletPath(); // = "/api"
        String pathInfo = request.getPathInfo(); // = "/auth"
</code>```

And with RESTEasy 3.0.23.Final I have :

```<code>        String contextPath = request.getContextPath(); // = "/myApp"
        String servletPath = request.getServletPath(); // = "/api/auth"
        String pathInfo = request.getPathInfo(); // = null
</code>```

my jboss-web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <context-root>/myApp</context-root>
</jboss-web>
</code>```

And I have no servlet mappings in my web.xml. All I have is class extending javax.ws.rs.core.Application with @ApplicationPath annotation :

```<code>@ApplicationPath("/api")
public class RESTActivator extends Application {
    private final Set<Class<?>> classes;

    public RESTActivator() {
        HashSet<Class<?>> c = new HashSet<>();
        c.add(ARestService.class);
        c.add(AnotherRestService.class);
        classes = Collections.unmodifiableSet(c);
    }

    @Override
    public Set<Class<?>> getClasses() {
        return classes;
    }
}
</code>```

答:
The behaviour of request.getServletPath() and request.getPathInfo() in a JAX-RS context is not defined by the specification, so I guess that an implementation is free to manage these how it sees fit.

If these path components are important to you consider using the services of an injected javax.ws.rs.core.UriInfo via @javax.ws.rs.core.Context instead.

Body:
I've upgraded my Wildfly 8.2.1.Final with a new version of RESTEasy to be able to use SNI support (not available in 3.0.10.Final version). So I copied the resteasy-jboss-modules-3.0.23.Final content in my /wildfly/modules/system/layers/base directory. But now I have a different behavior ! my Rest services are not called. And when I've inspected the context/servlet path I found different values between 3.0.10.Final and 3.0.23.Final versions:

With RESTEasy 3.0.10.Final I have the following values :

        String contextPath = request.getContextPath(); // = "/myApp"
        String servletPath = request.getServletPath(); // = "/api"
        String pathInfo = request.getPathInfo(); // = "/auth"

And with RESTEasy 3.0.23.Final I have :

        String contextPath = request.getContextPath(); // = "/myApp"
        String servletPath = request.getServletPath(); // = "/api/auth"
        String pathInfo = request.getPathInfo(); // = null

my jboss-web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <context-root>/myApp</context-root>
</jboss-web>

And I have no servlet mappings in my web.xml. All I have is class extending javax.ws.rs.core.Application with @ApplicationPath annotation :

@ApplicationPath("/api")
public class RESTActivator extends Application {
    private final Set<Class<?>> classes;

    public RESTActivator() {
        HashSet<Class<?>> c = new HashSet<>();
        c.add(ARestService.class);
        c.add(AnotherRestService.class);
        classes = Collections.unmodifiableSet(c);
    }

    @Override
    public Set<Class<?>> getClasses() {
        return classes;
    }
}


问:
read the following link
i want to go to next page of the following link

```<code><a href="javascript: __doPostBack('ctl00$PlaceHolderMain$g_781eb52f_faa9_4d59_9cae_2baec06ac484','dvt_firstrow={51};dvt_startposition={Paged=TRUE&p_Created_x0020_Date=6%2f9%2f2009%208%3a33%3a19%20AM&p_ID=216}');">
<img src="/_layouts/images/next.gif" border="0" alt="Next"></a></td></tr></table></div></td>
</code>```

how can i go next in java program

答: Have you tried HttpUnit? It has API for some basic JavaScript </p>

Title: read the following link

Body:
i want to go to next page of the following link

how can i go next in java program


问:
memcpy to string buffer defined in macro
i am using avrx to build a software run on custom tiny device, but i'm still newbie to C.
As indicated by makefile, it's using "c99 plus GCC extensions".
Today i finally ran into a piece of code written by some old colleague, it made me very confused:

```<code>#define SOMEDATA    "ABC"
void main(void)
{
    memcpy(SOMEDATA, "OK", sizeof("OK"));
    printf(SOMEDATA);//it works just fine?!?!?

    memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));
    printf(SOMEDATA);//well, now it go nuts. all i see is some random data.
}
</code>```

Why?
Why the logic in main() behaved like that? I used to thought that MACROs acts like constant and cannot be modified.

答:
This quote from the C Standard (6.4.5 String literals) will be useful for you

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

The first statement of the quote says that two string literals with the same values can be stored in the static memory either as distinct arrays or as the same one array,

So in fact this expression in the condition of the if statement

```<code>#define SOMEDATA    "ABC"

//...

if ( SOMEDATA == SOMEDATA )
{
    //...
}
</code>```

can yield either true or false depending on the settings of options of the compiler.

That is these two calls of memcpy

```<code>memcpy(SOMEDATA, "OK", sizeof("OK"));
//..
memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));
</code>```

that are equivalent to

```<code>memcpy("ABC", "OK", sizeof("OK"));
//..
memcpy("ABC", "VERY_LONG", sizeof("VERY_LONG"));
</code>```

can write either to the same extent of memory or to different extents of memory.

The second statement of the quote says that any attempt to change a string literal results in undefined behavior of the program.

Take into account that according to the C Standard the function main without parameters used in a hosted environment shall be declared like

```<code>int main( void )
^^^^
</code>```

Though some compilers as the Microsoft compiler allows to use the type void as the return type of main it is better to follow the C Standard.

Body:
i am using avrx to build a software run on custom tiny device, but i'm still newbie to C.
As indicated by makefile, it's using "c99 plus GCC extensions".
Today i finally ran into a piece of code written by some old colleague, it made me very confused:

#define SOMEDATA    "ABC"
void main(void)
{
    memcpy(SOMEDATA, "OK", sizeof("OK"));
    printf(SOMEDATA);//it works just fine?!?!?

    memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));
    printf(SOMEDATA);//well, now it go nuts. all i see is some random data.
}

Why?
Why the logic in main() behaved like that? I used to thought that MACROs acts like constant and cannot be modified.

Body:
This quote from the C Standard (6.4.5 String literals) will be useful for you

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

The first statement of the quote says that two string literals with the same values can be stored in the static memory either as distinct arrays or as the same one array,

So in fact this expression in the condition of the if statement

#define SOMEDATA    "ABC"

//...

if ( SOMEDATA == SOMEDATA )
{
    //...
}

can yield either true or false depending on the settings of options of the compiler.

That is these two calls of memcpy

memcpy(SOMEDATA, "OK", sizeof("OK"));
//..
memcpy(SOMEDATA, "VERY_LONG", sizeof("VERY_LONG"));

that are equivalent to

memcpy("ABC", "OK", sizeof("OK"));
//..
memcpy("ABC", "VERY_LONG", sizeof("VERY_LONG"));

can write either to the same extent of memory or to different extents of memory.

The second statement of the quote says that any attempt to change a string literal results in undefined behavior of the program.

Take into account that according to the C Standard the function main without parameters used in a hosted environment shall be declared like

int main( void )
^^^^

Though some compilers as the Microsoft compiler allows to use the type void as the return type of main it is better to follow the C Standard.


问:
.NET Core project reference issues - "Cannot find project info for 'XXX.csproj'"
I have a ASP.NET Core Web Application (.NET Framework) which targets .NET Framework 4.5.2.

After adding a reference to an empty class library of type 'Class Library (.NET Framework)', the following error appears:

"Cannot find project info for 'XXX.csproj'. This can indicate a
  missing project reference." Below you can see a screenshot of the
  error.

This is my project file:

```<code><Target Name="GenerateBuildDependencyFile"
    DependsOnTargets="_DefaultMicrosoftNETPlatformLibrary"
    BeforeTargets="_CheckForCompileOutputs"
    Condition=" '$(GenerateDependencyFile)' == 'true'"
    Inputs="$(ProjectAssetsFile)"
    Outputs="$(ProjectDepsFilePath)">

<GenerateDepsFile ProjectPath="$(MSBuildProjectFullPath "
                    AssetsFilePath="$(ProjectAssetsFile)"
                    DepsFilePath="$(ProjectDepsFilePath)"
                    TargetFramework="$(TargetFrameworkMoniker)"
                    AssemblyName="$(AssemblyName)"
                    AssemblyExtension="$(TargetExt)"
                    AssemblyVersion="$(Version)"
                    AssemblySatelliteAssemblies="@(IntermediateSatelliteAssembliesWithTargetPath)"
                    ReferencePaths="@(ReferencePath)"
                    ReferenceSatellitePaths="@(ReferenceSatellitePaths)"
                    RuntimeIdentifier="$(RuntimeIdentifier)"
                    PlatformLibraryName="$(MicrosoftNETPlatformLibrary)"
                    CompilerOptions="@(DependencyFileCompilerOptions)">
</GenerateDepsFile>
<ItemGroup>
    <FileWrites Include="$(ProjectDepsFilePath)" Condition="Exists('$(ProjectDepsFilePath)')"/>
</ItemGroup>
</Target>
</code>```

Source of the project file

I've searched the internet for a solution and found out that it could have something to do with transitive dependencies between projects. If A -> B -> C then A -> C. But I only have a .NET Core project and an empty class library.

答: What solved this for me was changing target framework from 4.5.2 to 4.6.1 if anyone should encounter the same :)</p>

Body:
I have a ASP.NET Core Web Application (.NET Framework) which targets .NET Framework 4.5.2.

After adding a reference to an empty class library of type 'Class Library (.NET Framework)', the following error appears:

"Cannot find project info for 'XXX.csproj'. This can indicate a
  missing project reference." Below you can see a screenshot of the
  error.

This is my project file:

<Target Name="GenerateBuildDependencyFile"
    DependsOnTargets="_DefaultMicrosoftNETPlatformLibrary"
    BeforeTargets="_CheckForCompileOutputs"
    Condition=" '$(GenerateDependencyFile)' == 'true'"
    Inputs="$(ProjectAssetsFile)"
    Outputs="$(ProjectDepsFilePath)">

<GenerateDepsFile ProjectPath="$(MSBuildProjectFullPath "
                    AssetsFilePath="$(ProjectAssetsFile)"
                    DepsFilePath="$(ProjectDepsFilePath)"
                    TargetFramework="$(TargetFrameworkMoniker)"
                    AssemblyName="$(AssemblyName)"
                    AssemblyExtension="$(TargetExt)"
                    AssemblyVersion="$(Version)"
                    AssemblySatelliteAssemblies="@(IntermediateSatelliteAssembliesWithTargetPath)"
                    ReferencePaths="@(ReferencePath)"
                    ReferenceSatellitePaths="@(ReferenceSatellitePaths)"
                    RuntimeIdentifier="$(RuntimeIdentifier)"
                    PlatformLibraryName="$(MicrosoftNETPlatformLibrary)"
                    CompilerOptions="@(DependencyFileCompilerOptions)">
</GenerateDepsFile>
<ItemGroup>
    <FileWrites Include="$(ProjectDepsFilePath)" Condition="Exists('$(ProjectDepsFilePath)')"/>
</ItemGroup>
</Target>

Source of the project file

I've searched the internet for a solution and found out that it could have something to do with transitive dependencies between projects. If A -> B -> C then A -> C. But I only have a .NET Core project and an empty class library.


问:
My input is "qwerty \n asdf " nextLine() takes input as "qwerty \n asdf "
Shouldn't the input read by nextLine() be "qwerty " as nextLine() should read my input only till it encounters \n.
This is my first question, Sorry if there's something wrong.
Help really appreciated.
Thank you.
My code

```<code>import java.util.Scanner;
class Kush
{
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    System.out.println(sc.nextLine());
}

}
</code>```

input :
abcd \n qwerty

output :
abcd \n qwerty

答:
The \n in input you are providing is treated as two characters \ & n
instead of a single newline char '\n'. To input a new line you should press enter key.

Below code will give you a better explanation.

```<code>String s = "abcd \n defg"; // here '\n' is a newline char
Scanner in = new Scanner(s);
while(in.hasNext()) {
    System.out.println(in.next());
}
</code>```

Output:

```<code>abcd
defg
</code>```

Body:
Shouldn't the input read by nextLine() be "qwerty " as nextLine() should read my input only till it encounters \n.
This is my first question, Sorry if there's something wrong.
Help really appreciated.
Thank you.
My code

import java.util.Scanner;
class Kush
{
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    System.out.println(sc.nextLine());
}

}

input :
abcd \n qwerty

output :
abcd \n qwerty

Body:
The \n in input you are providing is treated as two characters \ & n
instead of a single newline char '\n'. To input a new line you should press enter key.

Below code will give you a better explanation.

String s = "abcd \n defg"; // here '\n' is a newline char
Scanner in = new Scanner(s);
while(in.hasNext()) {
    System.out.println(in.next());
}

Output:

abcd
defg


问:
Angular2 - Subscribe not firing
I'm trying to implement a shared service in order to share information between components.

In this moment, the subscribe doesn't work and I don't know why...

This is the service:

service

```<code>private subject = new Subject<any>();

getCurrentUser(): Observable<any>
    {

        this.subject.next({data:"test"});
        return this.subject.asObservable();
    }
</code>```

component

```<code>subscription: Subscription;

ngOnInit() {

    this.subscription = this.authService.getCurrentUser().subscribe(data => {

      this.message = data;
      alert('I called the method');

    });
  }
</code>```

In this moment the execution didn't go inside the procedure that set the message and do the alert...

Thanks to support

答:
That's because you don't use the Observable the way it's meant to be used, an Observable is basically a data stream, and you're emitting the data before you subscribe to the stream.

```<code>private subject = new Subject<any>();

getUserObservable(): Observable<any>
{
    return this.subject.asObservable();
}

setUser(user:any):void{
    this.subject.next(user);
}
</code>```

In your tests:

subscription: Subscription;

```<code>  ngOnInit() {
    this.subscription = this.authService.getCurrentUserObservable().subscribe(data => {
      this.message = data;
      alert('I called the method');
    });
    // The subscription will be called right here.
    this.authService.setUser({data:"test"});
  }
</code>```

Then, if you call setUser from another component, service or whatever, your subscription will be called.

Title: Angular2 - Subscribe not firing

Body:
I'm trying to implement a shared service in order to share information between components.

In this moment, the subscribe doesn't work and I don't know why...

This is the service:

service

private subject = new Subject<any>();

getCurrentUser(): Observable<any>
    {

        this.subject.next({data:"test"});
        return this.subject.asObservable();
    }

component

subscription: Subscription;

ngOnInit() {

    this.subscription = this.authService.getCurrentUser().subscribe(data => {

      this.message = data;
      alert('I called the method');

    });
  }

In this moment the execution didn't go inside the procedure that set the message and do the alert...

Thanks to support

Body:
That's because you don't use the Observable the way it's meant to be used, an Observable is basically a data stream, and you're emitting the data before you subscribe to the stream.

private subject = new Subject<any>();

getUserObservable(): Observable<any>
{
    return this.subject.asObservable();
}

setUser(user:any):void{
    this.subject.next(user);
}

In your tests:

subscription: Subscription;

  ngOnInit() {
    this.subscription = this.authService.getCurrentUserObservable().subscribe(data => {
      this.message = data;
      alert('I called the method');
    });
    // The subscription will be called right here.
    this.authService.setUser({data:"test"});
  }

Then, if you call setUser from another component, service or whatever, your subscription will be called.


问:
In IIS 8.5, how do I map a sub-domain to an application within a site?
Currently I have an IIS 8.5 server with a URL of:

subdomain.domain.com/application_instance_name_1

Under a site called Portal Application there are 3 instances of the application, one for each customer.

I would like to create a subdomain per customer and direct it to their version of the application under the Site called Portal Application, for example, Customer 1 would type in:

customer_1_name.domain.com

and in IIS it would be directed to the site and Application below:

Sites/Portal Application/customer_1_application

This is my first time posting on here, I did find something that maybe relevant here but its for Apache not IIS.

IF you need further information please let me know.

Thanks

brian

答:
1) You need to install URL Rewrite and ARR module for IIS

2) Enable ARR. On the Application Request Routing page, select Enable proxy

3) Create rewrite rule

```<code>    <rewrite>
        <rules>
           <rule name="rewrite customer_1_name.domain.com" stopProcessing="true">
                <match url="(.*)" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^customer_1_name.domain.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://subdomain.domain.com/Portal Application/customer_1_application/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</code>```

P.S. You might have problem with your resources(images,styles,css,js). Because your html might contains absolute paths to resources

You can check this post, when author is creating outbound rule for fixing relative urls https://blogs.iis.net/carlosag/setting-up-a-reverse-proxy-using-iis-url-rewrite-and-arr

Body:
1) You need to install URL Rewrite and ARR module for IIS

2) Enable ARR. On the Application Request Routing page, select Enable proxy

3) Create rewrite rule

    <rewrite>
        <rules>
           <rule name="rewrite customer_1_name.domain.com" stopProcessing="true">
                <match url="(.*)" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^customer_1_name.domain.com$" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" url="http://subdomain.domain.com/Portal Application/customer_1_application/{R:1}" />
            </rule>
        </rules>
    </rewrite>

P.S. You might have problem with your resources(images,styles,css,js). Because your html might contains absolute paths to resources

You can check this post, when author is creating outbound rule for fixing relative urls https://blogs.iis.net/carlosag/setting-up-a-reverse-proxy-using-iis-url-rewrite-and-arr


问:
Can't deal with accents in Elasticsearch indexing and search
I have an issue with elasticsearch and the way the data are indexed/retrieved. I don't understand what happens.

This is the mapping I use (sorry, it's yaml format) :
The idea is simple, in theory... I have a string analyzer with lowercase and asciifolding filters. I don't want to care about case or accents, and I would like to use this analyzer to index and search.

```<code>settings:
    index:
        analysis:
            filter:
                autocomplete_filter:
                    type: edgeNGram
                    side: front
                    min_gram: 1
                    max_gram: 20
            analyzer:
                autocomplete:
                    type: custom
                    tokenizer: standard
                    filter: [lowercase, asciifolding, autocomplete_filter]
                string_analyzer:
                    type:        custom
                    tokenizer:   standard
                    filter:      [lowercase, asciifolding]
types:
    city:
        mappings:
            cityName:
                type: string
                analyzer: string_analyzer
                search_analyzer: string_analyzer
            location: {type: geo_point}
</code>```

When I run this query :

```<code>{
    "query": {
        "prefix":{
            "cityName":"per"
        }
    }
    ,
    "size":20
}
</code>```

I get some results like "Perpezat", "Pern", "Péreuil" which is the excepted result.

But if I run the following query :

```<code>{
    "query": {
        "prefix":{
            "cityName":"pér"
        }
    }
    ,
    "size":20
}
</code>```

Then I get no result at all.

If you have any clue or help, I would be happy to know it.
Thanks

答:
@mario-trucco Finally, I've found this post that explains a better way to analyze the strings.

What is an effective way to search world-wide location names with ElasticSearch?

Of course it doesn't answer my initial question and I still don't understand what happened, but it solves my problem by removing it.

Thanks again for your help and time.

Body:
I have an issue with elasticsearch and the way the data are indexed/retrieved. I don't understand what happens.

This is the mapping I use (sorry, it's yaml format) :
The idea is simple, in theory... I have a string analyzer with lowercase and asciifolding filters. I don't want to care about case or accents, and I would like to use this analyzer to index and search.

settings:
    index:
        analysis:
            filter:
                autocomplete_filter:
                    type: edgeNGram
                    side: front
                    min_gram: 1
                    max_gram: 20
            analyzer:
                autocomplete:
                    type: custom
                    tokenizer: standard
                    filter: [lowercase, asciifolding, autocomplete_filter]
                string_analyzer:
                    type:        custom
                    tokenizer:   standard
                    filter:      [lowercase, asciifolding]
types:
    city:
        mappings:
            cityName:
                type: string
                analyzer: string_analyzer
                search_analyzer: string_analyzer
            location: {type: geo_point}

When I run this query :

{
    "query": {
        "prefix":{
            "cityName":"per"
        }
    }
    ,
    "size":20
}

I get some results like "Perpezat", "Pern", "Péreuil" which is the excepted result.

But if I run the following query :

{
    "query": {
        "prefix":{
            "cityName":"pér"
        }
    }
    ,
    "size":20
}

Then I get no result at all.

If you have any clue or help, I would be happy to know it.
Thanks


问:
Import Variable from function in Class
I can't figure out how to import a variable that is created in a loop in a function and in a Class. I would then have the error " AttributeError: "Example" object has no attribute "address" .

It looks like this:

a.py

```<code>class Example():
    global address
    address = ""

    def __init__(self):
        pass

    def loop_function(self, cam):

        for i in imageZbar.symbols:
            print(i.data)
            address = i.data
        return address
</code>```

b.py

```<code>from a import Example
from flask import Flask,render_template
app = Flask(__name__)

app.route("/example/")
def blabla():
    imported_address = Example.address
    return render_template("example.html", imported_address = imported_address)
</code>```

答:
Not sure why you put a global when it is behaving like a class member... Why not use:

a.py

```<code>class Example():

    def __init__(self):
        self.address = ""

    def loop_function(self, cam):
        for i in imageZbar.symbols:
            print(i.data)
            self.address = i.data
        return self.address
</code>```

b.py

```<code>from a import Example

app = Flask(__name__)
eg = Example()
cam = None # I do not see anywhere this variable
eg.loop(cam)

app.route("/example/")
def blabla():
    return render_template("example.html", imported_address = eg.address)
</code>```

If you do not need it to behave like a class (i.e. only want to use the loop function) why even bother to create a class, why don't you create a function. Also, why it has to be global?

BTW, checking the comments, you have an error of the variable cam... I do not see that you initialize it anywhere in the code

Also, you do not show where are you getting:

```<code> imageZbar.symbols
</code>```

this should be a parameter for the loop function as far as I know

Title: Import Variable from function in Class

Body:
I can't figure out how to import a variable that is created in a loop in a function and in a Class. I would then have the error " AttributeError: "Example" object has no attribute "address" .

It looks like this:

a.py

class Example():
    global address
    address = ""

    def __init__(self):
        pass

    def loop_function(self, cam):

        for i in imageZbar.symbols:
            print(i.data)
            address = i.data
        return address

b.py

from a import Example
from flask import Flask,render_template
app = Flask(__name__)

app.route("/example/")
def blabla():
    imported_address = Example.address
    return render_template("example.html", imported_address = imported_address)

Body:
Not sure why you put a global when it is behaving like a class member... Why not use:

a.py

class Example():

    def __init__(self):
        self.address = ""

    def loop_function(self, cam):
        for i in imageZbar.symbols:
            print(i.data)
            self.address = i.data
        return self.address

b.py

from a import Example

app = Flask(__name__)
eg = Example()
cam = None # I do not see anywhere this variable
eg.loop(cam)

app.route("/example/")
def blabla():
    return render_template("example.html", imported_address = eg.address)

If you do not need it to behave like a class (i.e. only want to use the loop function) why even bother to create a class, why don't you create a function. Also, why it has to be global?

BTW, checking the comments, you have an error of the variable cam... I do not see that you initialize it anywhere in the code

Also, you do not show where are you getting:

 imageZbar.symbols

this should be a parameter for the loop function as far as I know


问:
How to select integer from an object?
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

```<code>stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )
</code>```

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

答:
Try this:</p>

```<code>$myValue = $myObject->{1}->Product;
</code>```

Title: How to select integer from an object?

Body:
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

Body:
Try this:

$myValue = $myObject->{1}->Product;


答:
Your subject emits the value before you are subscribing. That's is how a subject works. You could use a BehaviorSubject. A BehanvoirSubject re-sends the value, but takes a default value:

private subject = new BehaviorSubject<any>(undefined);

If that's is not what you want you could use a map:

return this.subject.asObservable().map(value => !isNullOrUndefined(value))

Title: Angular2 - Subscribe not firing


答:
The way I'd explain it is this: ForEach is a method, not a language feature. The C# foreach construct is a feature of the language within which the other language constructs break and continue are permitted.

I would also point out (not trying to judge, just making an observation) that this is a good example of why some developers object to the use of a ForEach method: it doesn't really save typing in this simple case, it requires one more redirection than necessary, and it doesn't have all the functionality of foreach anyway.

In my opinion the main scenario in which a ForEach method makes sense is as an extension on IEnumerable<T>--to put at the end of a chain of method calls. It seems (to me) a bit strange that they added it to List<T>.

Title: ForEach() : Why can't use break/continue inside

Body:
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to
break or continue"


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
Two quick examples.  The first is your classic Gaps-and-Islands, and the second will use an ad-hoc tally table to identify the missings elements via a LEFT JOIN.

The following was created in SQL Server, but if your database supports the window functions, it should be a small task to adapt.

Gaps and Islands

```<code>Declare @YourTable table (X int)
Insert Into @YourTable values
(1),(2),(3),(5),(6),(10)

Select X1 = min(X)
      ,X2 = max(X)
 From (
        Select *
              ,Grp = X - Row_Number() over (Order by X)
         From @YourTable
     ) A
 Group By Grp
</code>```

Returns

```<code>X1  X2
1   3
5   6
10  10
</code>```

Ad-hoc Tally Table

```<code>Declare @YourTable table (X int)
Insert Into @YourTable values
(1),(2),(3),(5),(6),(10)

 ;with cte0(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cteN(N) As (Select Row_Number() over (Order By (Select NULL)) From cte0 N1, cte0 N2, cte0 N3, cte0 N4, cte0 N5, cte0 N6) -- 1 Million
Select N
 From  cteN
 Left  Join @YourTable on X=N
 Where X is Null
  and  N<=(Select max(X) from @YourTable)
 Order By N
</code>```

Returns

```<code>N
4
7
8
9
</code>```

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
Two quick examples.  The first is your classic Gaps-and-Islands, and the second will use an ad-hoc tally table to identify the missings elements via a LEFT JOIN.

The following was created in SQL Server, but if your database supports the window functions, it should be a small task to adapt.

Gaps and Islands

Declare @YourTable table (X int)
Insert Into @YourTable values
(1),(2),(3),(5),(6),(10)

Select X1 = min(X)
      ,X2 = max(X)
 From (
        Select *
              ,Grp = X - Row_Number() over (Order by X)
         From @YourTable
     ) A
 Group By Grp

Returns

X1  X2
1   3
5   6
10  10

Ad-hoc Tally Table

Declare @YourTable table (X int)
Insert Into @YourTable values
(1),(2),(3),(5),(6),(10)

 ;with cte0(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cteN(N) As (Select Row_Number() over (Order By (Select NULL)) From cte0 N1, cte0 N2, cte0 N3, cte0 N4, cte0 N5, cte0 N6) -- 1 Million
Select N
 From  cteN
 Left  Join @YourTable on X=N
 Where X is Null
  and  N<=(Select max(X) from @YourTable)
 Order By N

Returns

N
4
7
8
9


问:
Angular 4 - How can I retrieve id in next url by clicking on specific post?
I want to clik on specific post(product.component) and retrieve its id on next url(details.component). Thank you in advance !

product.component.html

```<code> <div class="card">
    <h5>{{titre}}</h5>
    <p class="card-text">{{description}}</p>
    <p><a [routerLink]="['details',id]">Click here!</a></p>
  </div>
</code>```

product.component.ts

```<code>import {Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  @Input() titre:string;
  @Input() description:string;
  @Input() id:string;

  ngOnInit() {
  }

}
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  title = 'home works!';

  products = [{
    titre:"titre1",
    desc:"desc1",
    id:"0"
  },{
    titre:"titre2",
    desc:"desc2",
    id:"1"
  },{
    titre:"titre3",
    desc:"desc3",
    id:"2"
  }];

}
</code>```

details.component.ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {

    id:any;

  constructor(route: ActivatedRoute) {
    this.id = route.snapshot.params['id'];
  }

  ngOnInit() {

  }

  onSubmit = function (user) {
    console.log(user);
  }
}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { DetailsComponent } from './details/details.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent,
    DetailsComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {
        path: '',
        pathMatch: 'full',
        component: HomeComponent
      },
      {
        path: 'product',
        component: ProductComponent
      },
      {
        path: 'details/:id',
        component: DetailsComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

home.component.html

```<code><div class="home">
  <div class="album text-muted">
  <div class="container">
    <div class="row">
      <product
        class="col-md-4"
        *ngFor="let p of products"
        [description]="p.desc"
        [id]="p.id"
        [titre]="p.titre">
      </product>
    </div>
  </div>
</div>
</code>```

答:
In your routes make sure that you're defining the id as an argument.

```<code>{
  path: 'details/:id',
  component: DetailsComponent
}
</code>```

Then update your DetailsComponent to this...

```<code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit, OnDestroy {
  public id: any;
  private idSubscription: Subscription;

  constructor(public route: ActivatedRoute) {}

  ngOnInit() {
    this.idSubscription = this.route.params.subscribe((params: any) => {
      console.log(params.id)
      this.id = params.id;
    });
  }

  ngOnDestroy() {
    this.idSubscription.unsubscribe();
  }

  onSubmit = function (user) {
    console.log(user);
  }
}
</code>```

Body:
I want to clik on specific post(product.component) and retrieve its id on next url(details.component). Thank you in advance !

product.component.html

{{titre}}

{{description}}

Click here!

product.component.ts

import {Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  @Input() titre:string;
  @Input() description:string;
  @Input() id:string;

  ngOnInit() {
  }

}

home.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  title = 'home works!';

  products = [{
    titre:"titre1",
    desc:"desc1",
    id:"0"
  },{
    titre:"titre2",
    desc:"desc2",
    id:"1"
  },{
    titre:"titre3",
    desc:"desc3",
    id:"2"
  }];

}

details.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {

    id:any;

  constructor(route: ActivatedRoute) {
    this.id = route.snapshot.params['id'];
  }

  ngOnInit() {

  }

  onSubmit = function (user) {
    console.log(user);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { DetailsComponent } from './details/details.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent,
    DetailsComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {
        path: '',
        pathMatch: 'full',
        component: HomeComponent
      },
      {
        path: 'product',
        component: ProductComponent
      },
      {
        path: 'details/:id',
        component: DetailsComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

home.component.html

      <product
        class="col-md-4"
        *ngFor="let p of products"
        [description]="p.desc"
        [id]="p.id"
        [titre]="p.titre">
      </product>

Body:
In your routes make sure that you're defining the id as an argument.

{
  path: 'details/:id',
  component: DetailsComponent
}

Then update your DetailsComponent to this...

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit, OnDestroy {
  public id: any;
  private idSubscription: Subscription;

  constructor(public route: ActivatedRoute) {}

  ngOnInit() {
    this.idSubscription = this.route.params.subscribe((params: any) => {
      console.log(params.id)
      this.id = params.id;
    });
  }

  ngOnDestroy() {
    this.idSubscription.unsubscribe();
  }

  onSubmit = function (user) {
    console.log(user);
  }
}


问:
How can I set LIMIT in query in Realm?
I have done R&D for limit in query with no success. There is one way with which to paginate data in Realm with sub list but no success with that. It shows duplicate value in it.

Here is what I attempted for pagination.

```<code> RealmResults<Person> mPersonData=RealmUtils.getAllPersonWithTagsDescending();
    if (mPersonData != null) {
    int startPos=getAllPerson.size()-1;
    int endPos=mPersonData.size()-1;
    List<Person> newPersonData=mPersonData.subList(startPos,endPos);
    getAllPerson.addAll(newPersonData);
    mAdapter.notifyDataSetChanged();
}
</code>```

What am I doing wrong?

答:
As @EpicPandaForce said, you can use lessThan()and greaterThan() to set the limit, but realm have between() method, check: https://realm.io/docs/java/latest/#chaining-queries

Example :

Just get items with limit 50 :

```<code>static int LIMIT = 50;
final RealmResults<Item> resultsFilter = realm.where(Item.class)
                .between("id", 0, LIMIT)
                .findAllSorted("id", Sort.ASCENDING);
</code>```

Or when I want to get last 10 items:

```<code>static int LIMIT = 10;
final RealmResults<Item> resultsAll = realm.where(Item.class).findAll();
final RealmResults<Item> resultsFilter = realm.where(Item.class)
                .between("id", resultsAll.size() - LIMIT, resultsAll.size())
                .findAllSorted("id", Sort.DESCENDING);
</code>```

Title: How can I set LIMIT in query in Realm?

Body:
I have done R&D for limit in query with no success. There is one way with which to paginate data in Realm with sub list but no success with that. It shows duplicate value in it.

Here is what I attempted for pagination.

 RealmResults<Person> mPersonData=RealmUtils.getAllPersonWithTagsDescending();
    if (mPersonData != null) {
    int startPos=getAllPerson.size()-1;
    int endPos=mPersonData.size()-1;
    List<Person> newPersonData=mPersonData.subList(startPos,endPos);
    getAllPerson.addAll(newPersonData);
    mAdapter.notifyDataSetChanged();
}

What am I doing wrong?

Body:
As @EpicPandaForce said, you can use lessThan()and greaterThan() to set the limit, but realm have between() method, check: https://realm.io/docs/java/latest/#chaining-queries

Example :

Just get items with limit 50 :

static int LIMIT = 50;
final RealmResults<Item> resultsFilter = realm.where(Item.class)
                .between("id", 0, LIMIT)
                .findAllSorted("id", Sort.ASCENDING);

Or when I want to get last 10 items:

static int LIMIT = 10;
final RealmResults<Item> resultsAll = realm.where(Item.class).findAll();
final RealmResults<Item> resultsFilter = realm.where(Item.class)
                .between("id", resultsAll.size() - LIMIT, resultsAll.size())
                .findAllSorted("id", Sort.DESCENDING);


问:
Changing keyboard layout on application focus
As everybody knows the en-US Keyboard-layout is the best one for programming. So I'd like to use it in my IDEs. But since I live in a non-en-US country I need the de-CH layout for all other applications. Now I wonder if it is possible to set the layout depending to which application currently has the focus. If that is possible, can a human brain adapt to such a behaviour or is it just confusing?

cheers,
AC

The operating system is Windows 7 and the IDEs are VisualStudio and Netbeans

答:
I think you can configure it easily with built-in Windows settings. </p>

<p>In "Control Panel" - "Clock, language and Region" - "Language", you can enable "Enable different input methods for each application window" (the translation is approximated because I am using Spanish OS). I think that suffices. </p>

Body:
I think you can configure it easily with built-in Windows settings.

In "Control Panel" - "Clock, language and Region" - "Language", you can enable "Enable different input methods for each application window" (the translation is approximated because I am using Spanish OS). I think that suffices.