问:
Best service/connection combo for Flex/Server Implementation
I'm starting a Flex app on a pretty big reporting engine and want to know how best to connect to a Postgres Database.  I'd like to create a REST API architecture so I can use the service for more than just the Flex app(mobile possibly).

These are my options I've found:

Datatype: either XML, JSON or AMF

Flex Service: HTTPService or WebService

Server(using PHP): ZendAMF, custom json_encode implementation, Zend_Rest_Server

I've got my views all mapped out, and the api functions designed.  Basically what I need is advice on which Flex / back-end service combo to provide.

Thanks for the advice!

答:
Best service/connection combo for Flex/Server Implementation

There is no best way, but actually depends upon your project and how would you like to proceed. There are three ways.

Remoting

HTTP Service

Web Service

Since you would like to re use those services in other applications too, i would suggest you to go with Web Service. You can create your Web Service using any Server siding language which you prefer and communicate it with your Flex Application.

Regarding AMF

Its one of the ways how you can interact your Flex App with Server siding language. AMFPHP or ZendAMF does a good job and its so easy to communicate.

I would suggest you to concentrate more on Flex Architecture rather than looking into how your Flex is gonna communicate with Backend.

Check out for Modules based Architecture.
Check for which framework you are going to develop your Flex App. [ Mate, Cainogram, Swiz or someother] When you have decided with your frontend Architecture on how the flow should happen, you can then decide on how to communicate and which is the best possible approach for your project keeping the future things in your mind.

Since your Application is going to be reports oriented, go for Web Service.


来源: stackexchange

问:
Recurrence Relation: Writing a recurrence relation
I'm trying to write a recurrence relation for this algorithm.But I've got confused with the "root" variable.Can anyone help me or suggest me a better recursive algorithm to count the number of possible binary trees with n nodes?

```<code>Algorithm countTrees(n) {
    if(n<=1) then return 1
    else {
        sum = 0
        for root=1 to root<= n do {
            left = countTrees(root-1)
            right = countTrees(n-root)
            sum = sum+(left*right)
        }
        return sum
    }
}
</code>```

I've written this so far but I don't know how to deal with the root to solve this.

T(n) = n[T(root-1)+T(n-root)]

答:
Your code is already a recurrence relation for the number of binary trees, just expressed as an algorithm. I guess you were stuck because you had a summation over a loop. Here it is in standard mathematical notation-- with the loop value changed from 1..n to 0..n-1 to be more standard:

```<code>C(0) = C(1) = 1
C(n) = sum(C(i) * C(n-i-1) for i = 0...n-1)
</code>```

Writing it by hand (or with LaTeX) you'd use a summation sign rather than sum, but it's logically the same.

This is the recurrence relation for the Catalan numbers (although normally the C(1) case would not be explicitly listed) and the Wikipedia page linked also includes the closed-form solution for the recurrence relation and proofs of its correctness.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a recurrence relation for this algorithm.But I've got confused with the "root" variable.Can anyone help me or suggest me a better recursive algorithm to count the number of possible binary trees with n nodes?

Algorithm countTrees(n) {
    if(n<=1) then return 1
    else {
        sum = 0
        for root=1 to root<= n do {
            left = countTrees(root-1)
            right = countTrees(n-root)
            sum = sum+(left*right)
        }
        return sum
    }
}

I've written this so far but I don't know how to deal with the root to solve this.

T(n) = n[T(root-1)+T(n-root)]

Body:
Your code is already a recurrence relation for the number of binary trees, just expressed as an algorithm. I guess you were stuck because you had a summation over a loop. Here it is in standard mathematical notation-- with the loop value changed from 1..n to 0..n-1 to be more standard:

C(0) = C(1) = 1
C(n) = sum(C(i) * C(n-i-1) for i = 0...n-1)

Writing it by hand (or with LaTeX) you'd use a summation sign rather than sum, but it's logically the same.

This is the recurrence relation for the Catalan numbers (although normally the C(1) case would not be explicitly listed) and the Wikipedia page linked also includes the closed-form solution for the recurrence relation and proofs of its correctness.


问:
R - select only factor columns of dataframe
I am trying to select only factor columns from my data frame. Example is below:

```<code>bank[,apply(bank[,names(bank)!="id"], is.factor)]
</code>```

But the code behaves strangely. Step by step:

```<code>sapply(bank[,names(bank)!="id"], is.factor)
</code>```

I get:

```<code>age         sex      region      income     married    children         car
      FALSE        TRUE        TRUE       FALSE        TRUE       FALSE        TRUE
   save_act current_act    mortgage         pep      ageBin
       TRUE        TRUE        TRUE        TRUE        TRUE
</code>```

Looks OK. Now, I assume that I just pass this matrix of TRUE/FALSE to the next step and get only the columns I need:

```<code>bank[,sapply(bank[,names(bank)!="id"], is.factor)]
</code>```

But as result I get all the same columns as in original bank dataframe. Nothing is filtered out. I tried it one way or another but can't find a solution. Any advice on what I am doing wrong?

答:
```<code>#DATA
df = mtcars
colnames(df) = gsub("mpg","id",colnames(df))
df$am = as.factor(df$am)
df$gear = as.factor(df$gear)
df$id = as.factor(df$id)

#Filter out 'id' after selecting factors
df[,sapply(df, is.factor) & colnames(df) != "id"]
</code>```

Body:
I am trying to select only factor columns from my data frame. Example is below:

bank[,apply(bank[,names(bank)!="id"], is.factor)]

But the code behaves strangely. Step by step:

sapply(bank[,names(bank)!="id"], is.factor)

I get:

age         sex      region      income     married    children         car
      FALSE        TRUE        TRUE       FALSE        TRUE       FALSE        TRUE
   save_act current_act    mortgage         pep      ageBin
       TRUE        TRUE        TRUE        TRUE        TRUE

Looks OK. Now, I assume that I just pass this matrix of TRUE/FALSE to the next step and get only the columns I need:

bank[,sapply(bank[,names(bank)!="id"], is.factor)]

But as result I get all the same columns as in original bank dataframe. Nothing is filtered out. I tried it one way or another but can't find a solution. Any advice on what I am doing wrong?


问:
Steam API CSGo Get All Item Categories
I'm trying to find API method for Steam CSGO, which I can use to retreive all:

weapon categories;

wear;

exterior;

phase;

grade.

Any advice would be appreciated.

答:
to retrieve the "Phase" of a item you would need to retrieve paintindex and check what "phase" said paintindex is.

to get the wear value, exterior etc you can simply use the "globaloffensive" npm module and then call the "inspectItem" function with the inspect_url for the item you want to get data for.

```<code>csgo.inspectItem("URL",function(item) {
    let paintindex = item.paintindex; // ITEMS paintindex, used to identify phase...
    let wear = item.paintwear; // "FLOAT VALUE".
    let quality = item.quality;
    //...
});
</code>```

If you need a database for the "paintindex" you could check metjm.net.

Regards

Title: Steam API CSGo Get All Item Categories

Body:
to retrieve the "Phase" of a item you would need to retrieve paintindex and check what "phase" said paintindex is.

to get the wear value, exterior etc you can simply use the "globaloffensive" npm module and then call the "inspectItem" function with the inspect_url for the item you want to get data for.

csgo.inspectItem("URL",function(item) {
    let paintindex = item.paintindex; // ITEMS paintindex, used to identify phase...
    let wear = item.paintwear; // "FLOAT VALUE".
    let quality = item.quality;
    //...
});

If you need a database for the "paintindex" you could check metjm.net.

Regards


问:
jQuery elevateZoom work only when I put an alert() before
I have this code to launch jQuery elevateZoom but, only works if I put an alert() before.

I have already try with/without load() function.

```<code>jQuery(document).ready(function($){
    alert("Hi");
    $("#sh-product-main-image").load(function(){
        $(this).elevateZoom({
            zoomType: "inner",
            debug : true,
            cursor: "crosshair",
            zoomWindowFadeIn: 500,
            zoomWindowFadeOut: 500
        });
    });
});
</code>```

This is another variation of the code I have tried:

```<code>jQuery(document).ready(function($){
    alert("Hi");
    $("#sh-product-main-image").elevateZoom({
        zoomType: "inner",
        debug : true,
        cursor: "crosshair",
        zoomWindowFadeIn: 500,
        zoomWindowFadeOut: 500
    });
});
</code>```

答:
This is because $(document).ready() happens when the DOM is loaded, not when all the images are loaded. The alert causes a delay and allows time for the image to be loaded.

The following should work:

```<code>$(window).on("load", function() {
    $("#sh-product-main-image").elevateZoom({
        zoomType: "inner",
        debug : true,
        cursor: "crosshair",
        zoomWindowFadeIn: 500,
        zoomWindowFadeOut: 500
    });
});
</code>```

Body:
I have this code to launch jQuery elevateZoom but, only works if I put an alert() before.

I have already try with/without load() function.

jQuery(document).ready(function($){
    alert("Hi");
    $("#sh-product-main-image").load(function(){
        $(this).elevateZoom({
            zoomType: "inner",
            debug : true,
            cursor: "crosshair",
            zoomWindowFadeIn: 500,
            zoomWindowFadeOut: 500
        });
    });
});

This is another variation of the code I have tried:

jQuery(document).ready(function($){
    alert("Hi");
    $("#sh-product-main-image").elevateZoom({
        zoomType: "inner",
        debug : true,
        cursor: "crosshair",
        zoomWindowFadeIn: 500,
        zoomWindowFadeOut: 500
    });
});

Body:
This is because $(document).ready() happens when the DOM is loaded, not when all the images are loaded. The alert causes a delay and allows time for the image to be loaded.

The following should work:

$(window).on("load", function() {
    $("#sh-product-main-image").elevateZoom({
        zoomType: "inner",
        debug : true,
        cursor: "crosshair",
        zoomWindowFadeIn: 500,
        zoomWindowFadeOut: 500
    });
});


问:
jquery css selector to match elements with id contains specific text after the last dot
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

```<code><div id ='my.very.first.cow'></div> // get it
<div id = 'my.very.first.cowandcat'></div> //get it
<div id = 'my.very.firstcow.andcat'></div> //DON'T get it - not after the last dot
</code>```

答:
To match anything that ends with <code>.cow</code>    </p>

```<code>div[id$='.cow'] {background-color: blue}
</code>```

Body:
I need to write css selector for jquery that matches elements with id that contains some text after the last dot.
Something that resembles  $(div[id*='cow']) - but stronger because I need it to match only if the text is after last dot.
So take everything after the last dot and see if the text contains my string.
For example text to look for - cow

 // get it

 //get it

 //DON'T get it - not after the last dot

Body:
To match anything that ends with .cow

div[id$='.cow'] {background-color: blue}


问:
How to deploy web app directly from Visual Studio 2008?
I used to use discountasp.net and I can use Visual Studio 2008 to "publish" the website directly to the web host. I am using a dedicated server now (well, to be exact, Amazon EC2 Windows), how should I setup the web server so I can deploy the website directly from VS 2008? I tried to setup a FTP server but couldn't get it working.

Thanks!

答:
You can configure the FTP server in IIS to accept connections using your Windows account.  Note that you'll have to point the "home" directory of the FTP account to your web directory or a parent thereof (if you use the parent, you'll configure the system to navigate on login to the web directory).

This isn't specific to IIS, you could also use the paid Server from IpSwitch or the free one from FileZilla.

If you cannot get FTP to work, it is probably a permissions issue.  Note that an "old school" way of doing this is simply to publish to a local directory, zip the entire directory and then copy the zipped archive up to the server.  It might help you over the hump until you get FTP working.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: splattne


问:
JOGL Depth Buffering Not Working
I have been using JOGL for a few days now and this is now becoming a major road block.  I can not get shapes to draw in the correct z-order, instead, they are drawn in the order they are given to OpenGL.

I have spent the last few hours researching this and the general resolutions (and my reactions) seem to be the following:

Make sure your frustum is correct

I have double checked the frustum, it seems correct

I have switched to gluLookAt instead of a custom built frustum

I have switched to glOrthof just to make sure it is not perspective that is the problem.

I have not even set ANY view at all, instead working in the -1, 1 range that seems to be default

Make sure the following calls are in the init:

gl.glEnable(GL.GL_DEPTH_TEST);

gl.glDepthFunc(GL.GL_LEQUAL);

Make sure you are clearing the depth buffer on each redraw

gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

I have provided the very basic sample of a program below where this problem is occurring.  If you have JOGL and run it, you will see the red triangle at Z-position -0.5f ALWAYS on top while the triangles rotate around each other.  If you swap the two triangle vertex calls, the green triangle will then always be on top.

This has been an immense headache for me so any insight will be helpful, either from JOGL or OpenGL in general, but I can't seem to see what is wrong.

Also note that for brevity I removed the proper code to destroy the window.

```<code>import java.awt.Frame;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

import com.jogamp.opengl.util.Animator;

public class JOGLTest implements GLEventListener
{
    static GLU glu = new GLU();
    static GLCanvas canvas = new GLCanvas();
    static Frame frame = new Frame("JOGL test");
    static Animator animator = new Animator(canvas);

    float rot = 0.0f;

    public void display(GLAutoDrawable glDrawable)
    {
        final GL2 gl = glDrawable.getGL().getGL2();

        rot++;

        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

        gl.glLoadIdentity();

        gl.glRotatef(rot, 0.0f, 1.0f, 0.0f);

        gl.glBegin(GL.GL_TRIANGLES);

        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-1.0f, -1.0f, 0.0f);
        gl.glVertex3f(1.0f, -1.0f, 0.0f);

        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(-1.0f, 1.0f, -0.5f);
        gl.glVertex3f(1.0f, 1.0f, -0.5f);
        gl.glVertex3f(0.0f, 0.0f, -0.5f);

        gl.glEnd();
    }

    public void dispose(GLAutoDrawable arg0)
    {

    }

    public void init(GLAutoDrawable glDrawable)
    {
        GL2 gl = glDrawable.getGL().getGL2();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        gl.glClearDepth(1.0f);
        gl.glEnable(GL.GL_DEPTH_TEST);
        gl.glDepthFunc(GL.GL_LEQUAL);
    }

    public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
            int arg4)
    {

    }

    public static void main(String[] args)
    {
        canvas.addGLEventListener(new JOGLTest());
        frame.add(canvas);
        frame.setSize(640, 480);
        frame.setVisible(true);

        animator.start();
        canvas.requestFocus();
    }
}
</code>```

答:
I have solved the problem over much deliberation.

I created a GLCapabilities object and manually set the number of bits for a depth buffer while creating a GLCanvas.  The code is as follows:

```<code>GLProfile glp = GLProfile.getDefault();
GLCapabilities caps = new GLCapabilities(glp);

caps.setDepthBits(16);
canvas = new GLCanvas(caps);
</code>```

Title: JOGL Depth Buffering Not Working

Body:
I have been using JOGL for a few days now and this is now becoming a major road block.  I can not get shapes to draw in the correct z-order, instead, they are drawn in the order they are given to OpenGL.

I have spent the last few hours researching this and the general resolutions (and my reactions) seem to be the following:

Make sure your frustum is correct

I have double checked the frustum, it seems correct

I have switched to gluLookAt instead of a custom built frustum

I have switched to glOrthof just to make sure it is not perspective that is the problem.

I have not even set ANY view at all, instead working in the -1, 1 range that seems to be default

Make sure the following calls are in the init:

gl.glEnable(GL.GL_DEPTH_TEST);

gl.glDepthFunc(GL.GL_LEQUAL);

Make sure you are clearing the depth buffer on each redraw

gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

I have provided the very basic sample of a program below where this problem is occurring.  If you have JOGL and run it, you will see the red triangle at Z-position -0.5f ALWAYS on top while the triangles rotate around each other.  If you swap the two triangle vertex calls, the green triangle will then always be on top.

This has been an immense headache for me so any insight will be helpful, either from JOGL or OpenGL in general, but I can't seem to see what is wrong.

Also note that for brevity I removed the proper code to destroy the window.

import java.awt.Frame;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

import com.jogamp.opengl.util.Animator;

public class JOGLTest implements GLEventListener
{
    static GLU glu = new GLU();
    static GLCanvas canvas = new GLCanvas();
    static Frame frame = new Frame("JOGL test");
    static Animator animator = new Animator(canvas);

    float rot = 0.0f;

    public void display(GLAutoDrawable glDrawable)
    {
        final GL2 gl = glDrawable.getGL().getGL2();

        rot++;

        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

        gl.glLoadIdentity();

        gl.glRotatef(rot, 0.0f, 1.0f, 0.0f);

        gl.glBegin(GL.GL_TRIANGLES);

        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-1.0f, -1.0f, 0.0f);
        gl.glVertex3f(1.0f, -1.0f, 0.0f);

        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(-1.0f, 1.0f, -0.5f);
        gl.glVertex3f(1.0f, 1.0f, -0.5f);
        gl.glVertex3f(0.0f, 0.0f, -0.5f);

        gl.glEnd();
    }

    public void dispose(GLAutoDrawable arg0)
    {

    }

    public void init(GLAutoDrawable glDrawable)
    {
        GL2 gl = glDrawable.getGL().getGL2();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        gl.glClearDepth(1.0f);
        gl.glEnable(GL.GL_DEPTH_TEST);
        gl.glDepthFunc(GL.GL_LEQUAL);
    }

    public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
            int arg4)
    {

    }

    public static void main(String[] args)
    {
        canvas.addGLEventListener(new JOGLTest());
        frame.add(canvas);
        frame.setSize(640, 480);
        frame.setVisible(true);

        animator.start();
        canvas.requestFocus();
    }
}

Body:
I have solved the problem over much deliberation.

I created a GLCapabilities object and manually set the number of bits for a depth buffer while creating a GLCanvas.  The code is as follows:

GLProfile glp = GLProfile.getDefault();
GLCapabilities caps = new GLCapabilities(glp);

caps.setDepthBits(16);
canvas = new GLCanvas(caps);


问:
ModelForm has no model class specified when use model forms
I created a single web page that works for a data entry operator which enter the data to database. I used modelForm to take the data. When I use it django raise an error that "ModelForm has no model class specified". What should I do?

model.py

```<code>class Person(models.Model):

    NIC = models.CharField(unique=True,max_length=12)
    FName = models.CharField(max_length=30)
    LName = models.CharField(max_length=30)
    FullName = models.CharField(max_length=100)
    DOB = models.DateField()
    Nationality = models.CharField(max_length=20)
    AddressLine1 = models.CharField(max_length=100)
    AddressLine2 = models.CharField(max_length=100)
    AddressLine3 = models.CharField(max_length=100)
    AddressLine4 = models.CharField(max_length=100, null=True,blank=True)
    ContactNum = models.CharField(max_length=12)
    Email = models.EmailField()
    FacebookProf = models.CharField(max_length=100,null=True,blank=True)
    LinkedInProf = models.CharField(max_length=100,null=True,blank=True)
    PImage = models.ImageField(upload_to= Person_directory_path,null=True)
    Objective = models.TextField()
    CVPDF = models.ImageField(upload_to=Person_directory_path)
    SpecialNotes = models.TextField(blank=True,null=True)
    Department = models.ManyToManyField("Department")
    Post = models.ManyToManyField("Post")
    Degree = models.ManyToManyField("Degree",through="Person_Degree",null=True)
    Interview = models.ManyToManyField("Interview",through='Person_Interview',null=True)

    def __str__(self):
        return self.NIC, self.FName, self.LName, self.FullName, self.Email
</code>```

forms.py

```<code>from django.forms import ModelForm

from django import forms

from .models import Person

class Interview_Form(forms.ModelForm):

    class meta:
        model = Person
        fields = ['NIC', 'FName', 'LName','FullName','Email']
</code>```

views.py

```<code>from .forms import *

def deo(request):

    deoForm = Interview_Form()
    context = {
        'deoForm':deoForm,
    }
    return render(request, 'deo.html', context)
</code>```

答:
To me it looks like you're importing ModelForm from django.forms, but when you create Interview_form you are using forms.ModelForm.

You should just be using ModelForm.

Body:
I created a single web page that works for a data entry operator which enter the data to database. I used modelForm to take the data. When I use it django raise an error that "ModelForm has no model class specified". What should I do?

model.py

class Person(models.Model):

    NIC = models.CharField(unique=True,max_length=12)
    FName = models.CharField(max_length=30)
    LName = models.CharField(max_length=30)
    FullName = models.CharField(max_length=100)
    DOB = models.DateField()
    Nationality = models.CharField(max_length=20)
    AddressLine1 = models.CharField(max_length=100)
    AddressLine2 = models.CharField(max_length=100)
    AddressLine3 = models.CharField(max_length=100)
    AddressLine4 = models.CharField(max_length=100, null=True,blank=True)
    ContactNum = models.CharField(max_length=12)
    Email = models.EmailField()
    FacebookProf = models.CharField(max_length=100,null=True,blank=True)
    LinkedInProf = models.CharField(max_length=100,null=True,blank=True)
    PImage = models.ImageField(upload_to= Person_directory_path,null=True)
    Objective = models.TextField()
    CVPDF = models.ImageField(upload_to=Person_directory_path)
    SpecialNotes = models.TextField(blank=True,null=True)
    Department = models.ManyToManyField("Department")
    Post = models.ManyToManyField("Post")
    Degree = models.ManyToManyField("Degree",through="Person_Degree",null=True)
    Interview = models.ManyToManyField("Interview",through='Person_Interview',null=True)

    def __str__(self):
        return self.NIC, self.FName, self.LName, self.FullName, self.Email

forms.py

from django.forms import ModelForm

from django import forms

from .models import Person

class Interview_Form(forms.ModelForm):

    class meta:
        model = Person
        fields = ['NIC', 'FName', 'LName','FullName','Email']

views.py

from .forms import *

def deo(request):

    deoForm = Interview_Form()
    context = {
        'deoForm':deoForm,
    }
    return render(request, 'deo.html', context)


问:
Getting value out of ConfigParser instead of string
I have a file.ini structured like so:

```<code>item1 = a,b,c
item2 = x,y,z,e
item3 = w
</code>```

and my configParser is set like this:

```<code>def configMy(filename='file.ini', section='top'):
    parser = ConfigParser()
    parser.read(filename)
    mydict = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            mydict[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
    return mydict
</code>```

right now "mydict" is returning key-value pairs of strings, i.e.:
{'item1': 'a,b,c', 'item2': 'x,y,e,z', 'item3':'w'}

how can I alter it to return the value as a list? like this:
{'item1': [a,b,c], 'item2': [x,y,e,z], 'item3':[w]}

答:
You can use split on the parsed data to split the list.

```<code>def configMy(filename='file.ini', section='top'):
    parser = ConfigParser()
    parser.read(filename)
    mydict = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            mydict[param[0]] = param[1].split(',')
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
    return mydict
</code>```

If needed, you could then add some more logic to convert back to a single value if the list only has a single value. Or check for commas in the value before splitting.

Body:
I have a file.ini structured like so:

item1 = a,b,c
item2 = x,y,z,e
item3 = w

and my configParser is set like this:

def configMy(filename='file.ini', section='top'):
    parser = ConfigParser()
    parser.read(filename)
    mydict = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            mydict[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
    return mydict

right now "mydict" is returning key-value pairs of strings, i.e.:
{'item1': 'a,b,c', 'item2': 'x,y,e,z', 'item3':'w'}

how can I alter it to return the value as a list? like this:
{'item1': [a,b,c], 'item2': [x,y,e,z], 'item3':[w]}

Body:
You can use split on the parsed data to split the list.

def configMy(filename='file.ini', section='top'):
    parser = ConfigParser()
    parser.read(filename)
    mydict = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            mydict[param[0]] = param[1].split(',')
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
    return mydict

If needed, you could then add some more logic to convert back to a single value if the list only has a single value. Or check for commas in the value before splitting.


问:
Error in program when parsing negative integers into an array
I am having a strange issue with one of my assignments. I am attempting to take integers from user input and store them in an array. After that, four recursive methods will be run on them to find different characteristics of those numbers. However, whenever I attempt to run the program with a negative integer in any of the indexes the program stops responding.

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];
    InputStreamReader inRead = new InputStreamReader(System.in);
    BufferedReader buffRead = new BufferedReader(inRead);
    String line = buffRead.readLine();

    try {
        while (!line.equals("0") && index < 100) {
            numbers[index] = Integer.parseInt(line);
            index++;
            line = buffRead.readLine();

        }
    } catch (IOException exception) {
        System.out.println("Array index out of bound");
    }
`       int min = findMin(numbers, 0, numbers.length - 1);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println("The maximum number among numbers that are less than the first number is " + maxLessThanFirst);

    }

    public static int findMin(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            return numbers[startIndex];
        } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
            return findMin(numbers, startIndex, endIndex - 1);
        } else {
            return numbers[endIndex];
        }

    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

}
</code>```

This is the only relevant section of code that is necessary to understand the problem, I believe. If additional code is needed just ask. Thank you!

答:
Replace your findMin method. Pass the array and zero for the index;</p>

```<code>public static int findMin(int[] numbers, int index) {
    if (index == numbers.length - 1)
    {
        return numbers[index];
    }
    else
    {
        return Math.min(numbers[index], findMin(numbers, index + 1));
    }
}
</code>```

Body:
I am having a strange issue with one of my assignments. I am attempting to take integers from user input and store them in an array. After that, four recursive methods will be run on them to find different characteristics of those numbers. However, whenever I attempt to run the program with a negative integer in any of the indexes the program stops responding.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];
    InputStreamReader inRead = new InputStreamReader(System.in);
    BufferedReader buffRead = new BufferedReader(inRead);
    String line = buffRead.readLine();

    try {
        while (!line.equals("0") && index < 100) {
            numbers[index] = Integer.parseInt(line);
            index++;
            line = buffRead.readLine();

        }
    } catch (IOException exception) {
        System.out.println("Array index out of bound");
    }
`       int min = findMin(numbers, 0, numbers.length - 1);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println("The maximum number among numbers that are less than the first number is " + maxLessThanFirst);

    }

    public static int findMin(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            return numbers[startIndex];
        } else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
            return findMin(numbers, startIndex, endIndex - 1);
        } else {
            return numbers[endIndex];
        }

    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

}

This is the only relevant section of code that is necessary to understand the problem, I believe. If additional code is needed just ask. Thank you!

Body:
Replace your findMin method. Pass the array and zero for the index;

public static int findMin(int[] numbers, int index) {
    if (index == numbers.length - 1)
    {
        return numbers[index];
    }
    else
    {
        return Math.min(numbers[index], findMin(numbers, index + 1));
    }
}


问:
Get size of folder or file
How can I retrieve size of folder or file in Java?</p>

答: in linux if you want to sort directories then  du -hs * | sort -h</p>

Title: Get size of folder or file


问:
SSIS Case Statement not working
This SSIS case expression looks perfectly valid to me, but it's coming up red. Can anybody explain why?</p>

```<code>[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2"
</code>```

答: Probably because you don't have the " : {ELSE} " part of the expression.   What do you want the value to be if the column does not equal "MEDICAL"?</p>

Title: SSIS Case Statement not working

Body:
This SSIS case expression looks perfectly valid to me, but it's coming up red. Can anybody explain why?

[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2"


问:
Selecting a csv file from storage in android
Hello I wish to upload a csv file in android but somehow this code segment doesn't work for csv file.</p>

```<code>Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/csv");
startActivityForResult(intent, OPEN_REQUEST_CODE);
</code>```

答:
You should probably use ACTION_GET_CONTENT instead of ACTION_OPEN_DOCUMENT, and you'll need to add CATEGORY_OPENABLE to the Intent.

See the selected answer at Android Intent choose CSV for import

Body:
Hello I wish to upload a csv file in android but somehow this code segment doesn't work for csv file.

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/csv");
startActivityForResult(intent, OPEN_REQUEST_CODE);


问:
Meteor onConnection client side hook?
Is there a onConnection hook for client side on Meteor?   This is my issue:
Im trying to detect anytime Meteor reconnects to server to programmatically resubscribe to some data based on a parameter.

Meteor actually resubscribe automatically to my default subscriptions, but I have also a globlal subscription based on a parameter, and it is not reloaded after reconnection:

```<code>Meteor.subscribe('Members', fnGetLastEvent());
</code>```

Im trying to reload it on a Meteor reconnection hook, if it exist.
Thanks in advance.

答:
I don't have a direct answer for you, but here are a few things you can try to see if they are a fit for your specific use case.

1) Set your own onReconnect callback function on the client side.

```<code>Meteor.onReconnect = function() {
  console.log("meteor has reconnected);
  // do stuff
};
</code>```

I tested this out from Chrome developer tools in the console of a Meteor app that I have.  I set the onReconnect callback, ran Meteor.disconnect(), then ran Meteor.reconnect() and my callback fired.  The only caveat is I'm not sure if this callback is run after the connection has been established or before.

2) Put your subscribe call inside of an autorun that uses Meteor.status() as a reactive data source.  I do a similar check in one of my apps to check if Meteor is not connected and then display a modal informing the user that their data is no longer real-time.  Here is the main logic that I use to detect when Meteor is disconnected vs. reconnected.

```<code>var updateCountdownTimeout;
var nextRetry = new ReactiveVar(0);

Tracker.autorun(() => {
  if (Meteor.status().status === 'waiting') {
    updateCountdownTimeout = Meteor.setInterval(() => {
      nextRetry.set(Math.round((Meteor.status().retryTime - (new Date()).getTime()) / 1000));
    }, 1000);
  } else {
    nextRetry.set(0);
    Meteor.clearInterval(updateCountdownTimeout);
  }

  if (!Meteor.status().connected && Meteor.status().status !== 'offline' && Meteor.status().retryCount > 0) {
    console.log("Connection to server has been LOST!");
  } else {
    console.log("Connection to server has been RESTORED!");
    // put subscription logic here
  }
});
</code>```

The caveat here is I'm not sure what will happen the first time the app is loaded.  I'm not sure if your subscription logic will run or if it will only run after a reconnect going forward (you can test this out).

3) This one is just theoretical.  It seems like you ought to be able to store your subscription parameter in Session and put your subscription logic inside an autorun.  Upon reconnection, the autorun in theory should run again.  Assuming this is inside of a template somewhere, then it would look like this.

```<code>this.autorun(() => {
  this.subscribe('Members', Session.get('sub_params'));
});
</code>```

4) There are some callbacks you can setup on the client Meteor.connection._stream object that you could potentially use.  The options available are on message, reset, and disconnect.  I have used a callback on message for debugging before (see below).

```<code>Meteor.connection._stream.on('message', function (message) {
  console.log("receive", JSON.parse(message));
});
</code>```

Assuming on reset is fired when a connection is re-established, then you might be able to put your subscription logic there.

```<code>Meteor.connection._stream.on('reset', function () {
  // subscription logic here
});
</code>```

Good luck!

Title: Meteor onConnection client side hook?

Body:
Is there a onConnection hook for client side on Meteor?   This is my issue:
Im trying to detect anytime Meteor reconnects to server to programmatically resubscribe to some data based on a parameter.

Meteor actually resubscribe automatically to my default subscriptions, but I have also a globlal subscription based on a parameter, and it is not reloaded after reconnection:

Meteor.subscribe('Members', fnGetLastEvent());

Im trying to reload it on a Meteor reconnection hook, if it exist.
Thanks in advance.

Body:
I don't have a direct answer for you, but here are a few things you can try to see if they are a fit for your specific use case.

1) Set your own onReconnect callback function on the client side.

Meteor.onReconnect = function() {
  console.log("meteor has reconnected);
  // do stuff
};

I tested this out from Chrome developer tools in the console of a Meteor app that I have.  I set the onReconnect callback, ran Meteor.disconnect(), then ran Meteor.reconnect() and my callback fired.  The only caveat is I'm not sure if this callback is run after the connection has been established or before.

2) Put your subscribe call inside of an autorun that uses Meteor.status() as a reactive data source.  I do a similar check in one of my apps to check if Meteor is not connected and then display a modal informing the user that their data is no longer real-time.  Here is the main logic that I use to detect when Meteor is disconnected vs. reconnected.

var updateCountdownTimeout;
var nextRetry = new ReactiveVar(0);

Tracker.autorun(() => {
  if (Meteor.status().status === 'waiting') {
    updateCountdownTimeout = Meteor.setInterval(() => {
      nextRetry.set(Math.round((Meteor.status().retryTime - (new Date()).getTime()) / 1000));
    }, 1000);
  } else {
    nextRetry.set(0);
    Meteor.clearInterval(updateCountdownTimeout);
  }

  if (!Meteor.status().connected && Meteor.status().status !== 'offline' && Meteor.status().retryCount > 0) {
    console.log("Connection to server has been LOST!");
  } else {
    console.log("Connection to server has been RESTORED!");
    // put subscription logic here
  }
});

The caveat here is I'm not sure what will happen the first time the app is loaded.  I'm not sure if your subscription logic will run or if it will only run after a reconnect going forward (you can test this out).

3) This one is just theoretical.  It seems like you ought to be able to store your subscription parameter in Session and put your subscription logic inside an autorun.  Upon reconnection, the autorun in theory should run again.  Assuming this is inside of a template somewhere, then it would look like this.

this.autorun(() => {
  this.subscribe('Members', Session.get('sub_params'));
});

4) There are some callbacks you can setup on the client Meteor.connection._stream object that you could potentially use.  The options available are on message, reset, and disconnect.  I have used a callback on message for debugging before (see below).

Meteor.connection._stream.on('message', function (message) {
  console.log("receive", JSON.parse(message));
});

Assuming on reset is fired when a connection is re-established, then you might be able to put your subscription logic there.

Meteor.connection._stream.on('reset', function () {
  // subscription logic here
});

Good luck!


问:
How to save Obj-C block in a C struct?
I want to call a C function from my ObjC. I am passing a C function reference (defined in ObjC) in a C struct so that C can call that function. I also want to pass the reference to a completion-block to C, so that when I get a callback, I can call that completion-block. But I do not know how to implement that. I get different errors based on the different typecasting I tried.</p>

```<code>//Abc.m

void myCallback(MyData *data)
{
  //I get the control here!
  //((__bridge void *)(data->completionBlock))([NSString stringWithCString:data->json]); //how to call the completion block?
}

- (void)myMethod:(NSString)input
             completion:(void (^)(NSString * _Nullable response))completionBlock
{
    MyData *data = malloc(sizeof(MyData));
    data->myCallback = myCallback;
    data->completionBlock = (__bridge void *)(completionBlock);//is this correct?
    cFunction(data);
}

//Xyz.c

typedef struct
{
  char *json;
  void (*myCallback)(void *response);
  void *completionBlock;
} MyData;

void cFunction(MyData *data)
{
  data->json = "some response";
  (data->myCallback)(data);
}
</code>```

答:
There are two issues to consider:

Casting: You need to cast to appropriate types, e.g. your commented out (__bridge void *)(data->completionBlock) doesn't give you back a block type so the compiler will reject the call.

Ownership: Blocks are just objects in Objective-C and are managed by ARC for you. In C blocks are manually managed. You must ensure that the block you pass into your C structure will not be released by ARC, and having used it you must ensure that it is freed.

Following your code design let's first define a type to make things easier:

```<code>typedef void (^CompletionBlock)(NSString * _Nullable response);
</code>```

With that your myMethod function starts as before:

```<code>- (void)myMethod:(NSString*)input
      completion:(CompletionBlock)completionBlock
{
   MyData *data = malloc(sizeof(MyData));
   data->myCallback = myCallback;
</code>```

Now you must store your block into your struct while making sure ARC does not release it on the Objective-C side. To do that you use __bridge_retain which returns a retained reference to the block, your code will be responsible for balancing that retain. That can either be done in your C code or you can transfer the ownership back to ARC and let it take care of it. So the remainder of myMethod is:

```<code>   data->completionBlock = (__bridge_retained void *)(completionBlock);
   cFunction(data);
}
</code>```

Now your cFunction just calls your myCallBack function so in this case there is no need to change anything there.

Now to your myCallBack, first we fix the type mismatch and define it to take a void * and then recover the MyData *:

```<code>void myCallback(void *response)
{
   MyData *data = response;
</code>```

Now we need to recover the block. We could just cast it to the block type, but that would leave us with the job of freeing it (using Block_release()) after we've used it; however we can use __bridge_transfer to hand back ownership to ARC so it will manage it:

```<code>   CompletionBlock completionBlock = (__bridge_transfer CompletionBlock)data->completionBlock;
</code>```

Now we get the string out and convert it to an NSString:

```<code>   NSString *result = [NSString stringWithCString:data->json encoding:NSUTF8StringEncoding];
</code>```

And then free the malloc'ed wrapper:

```<code>   free(data);
</code>```

Finally we call the block:

```<code>   completionBlock(result);
}
</code>```

The above followed your design, but there is no need to have your C function call another C function in your Objective-C file to call the block - blocks are a C language feature and supported in .c files by Clang. You can just cast data->completionBlock to the block type, invoke it, and then use Block_release() to free the block.

Further as blocks are C types you can type the struct field completionBlock with a block type and remove a lot of casts (but those cases cost nothing at runtime).

HTH

Title: How to save Obj-C block in a C struct?

Body:
I want to call a C function from my ObjC. I am passing a C function reference (defined in ObjC) in a C struct so that C can call that function. I also want to pass the reference to a completion-block to C, so that when I get a callback, I can call that completion-block. But I do not know how to implement that. I get different errors based on the different typecasting I tried.

//Abc.m

void myCallback(MyData *data)
{
  //I get the control here!
  //((__bridge void *)(data->completionBlock))([NSString stringWithCString:data->json]); //how to call the completion block?
}

- (void)myMethod:(NSString)input
             completion:(void (^)(NSString * _Nullable response))completionBlock
{
    MyData *data = malloc(sizeof(MyData));
    data->myCallback = myCallback;
    data->completionBlock = (__bridge void *)(completionBlock);//is this correct?
    cFunction(data);
}

//Xyz.c

typedef struct
{
  char *json;
  void (*myCallback)(void *response);
  void *completionBlock;
} MyData;

void cFunction(MyData *data)
{
  data->json = "some response";
  (data->myCallback)(data);
}

Body:
There are two issues to consider:

Casting: You need to cast to appropriate types, e.g. your commented out (__bridge void *)(data->completionBlock) doesn't give you back a block type so the compiler will reject the call.

Ownership: Blocks are just objects in Objective-C and are managed by ARC for you. In C blocks are manually managed. You must ensure that the block you pass into your C structure will not be released by ARC, and having used it you must ensure that it is freed.

Following your code design let's first define a type to make things easier:

typedef void (^CompletionBlock)(NSString * _Nullable response);

With that your myMethod function starts as before:

- (void)myMethod:(NSString*)input
      completion:(CompletionBlock)completionBlock
{
   MyData *data = malloc(sizeof(MyData));
   data->myCallback = myCallback;

Now you must store your block into your struct while making sure ARC does not release it on the Objective-C side. To do that you use __bridge_retain which returns a retained reference to the block, your code will be responsible for balancing that retain. That can either be done in your C code or you can transfer the ownership back to ARC and let it take care of it. So the remainder of myMethod is:

   data->completionBlock = (__bridge_retained void *)(completionBlock);
   cFunction(data);
}

Now your cFunction just calls your myCallBack function so in this case there is no need to change anything there.

Now to your myCallBack, first we fix the type mismatch and define it to take a void * and then recover the MyData *:

void myCallback(void *response)
{
   MyData *data = response;

Now we need to recover the block. We could just cast it to the block type, but that would leave us with the job of freeing it (using Block_release()) after we've used it; however we can use __bridge_transfer to hand back ownership to ARC so it will manage it:

   CompletionBlock completionBlock = (__bridge_transfer CompletionBlock)data->completionBlock;

Now we get the string out and convert it to an NSString:

   NSString *result = [NSString stringWithCString:data->json encoding:NSUTF8StringEncoding];

And then free the malloc'ed wrapper:

   free(data);

Finally we call the block:

   completionBlock(result);
}

The above followed your design, but there is no need to have your C function call another C function in your Objective-C file to call the block - blocks are a C language feature and supported in .c files by Clang. You can just cast data->completionBlock to the block type, invoke it, and then use Block_release() to free the block.

Further as blocks are C types you can type the struct field completionBlock with a block type and remove a lot of casts (but those cases cost nothing at runtime).

HTH


问:
Golang. Import only one file from package
Hi all. I am new in GO and need some help. I've got a project with this structure

But let's pretend that I have 100500 items in my logic package. What if I need import only one or two files for the specific package. Can I do it or I only can import a full package?

答:
No, in Go you import packages, not files.  However, the compiler generally only includes in the compiled binary functions and types actually referenced, so even if you include a massive package in your import (which is discouraged anyway), they'll not usually be included in the final binary unless needed.

And as RayfenWindspear pointed out, if a package is large enough that you want to only import a file or two, that's probably a pretty good smell test that you need to refactor that package.


问:
"Google Play services are updating" in Google Maps API
I have an Android app which makes use of Google Maps. All of a sudden, it stopped working in release mode. The Map view tells Google Play services are updating on the emulator and on real devices. Searching on the net everyone talks about the API key file, but this is not my problem!

I have tried every possible different combination of release settings, and I have found out that the problem occurs when I set debuggable = false in the build configuration (with debuggable = true it works). I can't understand why Maps aren't working because, of course, the APK is not debuggable. I have also tried multiple versions of Google Play services, even the latest (10.2.0). No difference.

What can I do? Please help as I can't release any new release on Play Store until I fix this bug.

答:
I had the same problem, and I managed to fix it.
The problem occurs when the minifyEnabled option is set to true (when false the problem does not occur).

In short, what I did was to add the line:

```<code>-keep class com.google.** {*; }
</code>```

into the proguard rules file (proguard-rules.pro), to avoid google play services dependencies from being obfuscated.
At least in my case, the resulting APK doesn't seem to be much bigger if this rule is added.

I think the problem occurs when the use of map components is done from another module (for example in a shared library), but I didn't check it.

Body:
I had the same problem, and I managed to fix it.
The problem occurs when the minifyEnabled option is set to true (when false the problem does not occur).

In short, what I did was to add the line:

-keep class com.google.** {*; }

into the proguard rules file (proguard-rules.pro), to avoid google play services dependencies from being obfuscated.
At least in my case, the resulting APK doesn't seem to be much bigger if this rule is added.

I think the problem occurs when the use of map components is done from another module (for example in a shared library), but I didn't check it.


问:
Excel VBA: determing rows on which the value is found
I am trying to have the row number in which the value was found:

```<code>Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
findrow = Sheets("Work_report").Range("E" & i).Find(Worksheets("Work").Range("A:A").Value, lookat:=xlWhole).Row
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & findrow)
End If
Next i
</code>```

For the row I want to use "findrow" which basically would need to find the row in Work_Report. This is only executed if, from sheet Work the cell value was found in Work_Report, so in order to find the number of the row I am trying to invert the line and have it found back in Work_Report, however this gives me the error of - Object variable or With block variable not set.

Thanks!

答:
you can do it in one shot with exploiting AutoFilter() method's operator xlFilterValues value

```<code>Sub main()
    Dim rep As Worksheet

    Dim criteriaArr As Variant
    With Worksheets("Work_report") '<--| reference "Work_report" sheet
        criteriaArr = Application.Transpose(.Range("E2", .Cells(.Rows.Count, "E").End(xlUp)).Value) '<--| store its column E cells content from row 2 down to last not empty one
    End With

    Set rep = Sheets("Details")
    With Worksheets("Work") '<--| reference "Work" sheet
        With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)) '<--| reference its column A cells from row 1 (header) down to last not empty one
            .AutoFilter Field:=1, Criteria1:=criteriaArr, Operator:=xlFilterValues '<--| filter it with "Work_report" sheet column E content
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any filtered cells other then headers
                With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping header
                    rep.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count).Value = "FT_EXCEL" '<--| write 'rep' sheet column A corresponding cells content
                    With rep.Range("B" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count)
                        .Formula = "=CONCATENATE(Start!$C$5,""AB"",TEXT(ROW(),""00""))" '<--| '<--| write 'rep' sheet column B corresponding cells content
                        .Value = .Value
                    End With
                End With
            End If
        End With
        .AutoFilterMode = False
    End With
End Sub
</code>```

Body:
I am trying to have the row number in which the value was found:

Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
findrow = Sheets("Work_report").Range("E" & i).Find(Worksheets("Work").Range("A:A").Value, lookat:=xlWhole).Row
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
rep.Range("C" & o).Value = Sheets("Work_report").Range("E" & findrow)
End If
Next i

For the row I want to use "findrow" which basically would need to find the row in Work_Report. This is only executed if, from sheet Work the cell value was found in Work_Report, so in order to find the number of the row I am trying to invert the line and have it found back in Work_Report, however this gives me the error of - Object variable or With block variable not set.

Thanks!

Body:
you can do it in one shot with exploiting AutoFilter() method's operator xlFilterValues value

Sub main()
    Dim rep As Worksheet

    Dim criteriaArr As Variant
    With Worksheets("Work_report") '<--| reference "Work_report" sheet
        criteriaArr = Application.Transpose(.Range("E2", .Cells(.Rows.Count, "E").End(xlUp)).Value) '<--| store its column E cells content from row 2 down to last not empty one
    End With

    Set rep = Sheets("Details")
    With Worksheets("Work") '<--| reference "Work" sheet
        With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)) '<--| reference its column A cells from row 1 (header) down to last not empty one
            .AutoFilter Field:=1, Criteria1:=criteriaArr, Operator:=xlFilterValues '<--| filter it with "Work_report" sheet column E content
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any filtered cells other then headers
                With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping header
                    rep.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count).Value = "FT_EXCEL" '<--| write 'rep' sheet column A corresponding cells content
                    With rep.Range("B" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count)
                        .Formula = "=CONCATENATE(Start!$C$5,""AB"",TEXT(ROW(),""00""))" '<--| '<--| write 'rep' sheet column B corresponding cells content
                        .Value = .Value
                    End With
                End With
            End If
        End With
        .AutoFilterMode = False
    End With
End Sub


问:
HttpClient GetAsync not working as expected
When testing my web API with Postman my API get executes fine!

When it comes to running the code with HttpClient in my client application the code executes without error but without the expected result on the server.
What could be happening?

From my client application:

```<code>private string GetResponseFromURI(Uri u)
{
    var response = "";
    HttpResponseMessage result;
    using (var client = new HttpClient())
    {
        Task task = Task.Run(async () =>
        {
            result = await client.GetAsync(u);
            if (result.IsSuccessStatusCode)
            {
                response = await result.Content.ReadAsStringAsync();
            }
        });
        task.Wait();
    }
    return response;
}
</code>```

Here is the API controller:

```<code>[Route("api/[controller]")]
public class CartsController : Controller
{
    private readonly ICartRepository _cartRepo;

    public CartsController(ICartRepository cartRepo)
    {
        _cartRepo = cartRepo;
    }

    [HttpGet]
    public string GetTodays()
    {
        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Add")]
    public string GetIncrement()
    {
        var cart = new CountedCarts();
        _cartRepo.Add(cart);

        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Remove")]
    public string GetDecrement()
    {
        _cartRepo.RemoveLast();
        return _cartRepo.GetTodaysCarts();
    }

}
</code>```

Note these API calls work as expected when called from Postman.

答:
You are doing fire-and-forget approach. In your case, you need to wait for the result.

For example,

```<code>static async Task<string> GetResponseFromURI(Uri u)
{
    var response = "";
    using (var client = new HttpClient())
    {
        HttpResponseMessage result = await client.GetAsync(u);
        if (result.IsSuccessStatusCode)
        {
            response = await result.Content.ReadAsStringAsync();
        }
    }
    return response;
}

static void Main(string[] args)
{
    var t = Task.Run(() => GetResponseFromURI(new Uri("http://www.google.com")));
    t.Wait();

    Console.WriteLine(t.Result);
    Console.ReadLine();
}
</code>```

Body:
When testing my web API with Postman my API get executes fine!

When it comes to running the code with HttpClient in my client application the code executes without error but without the expected result on the server.
What could be happening?

From my client application:

private string GetResponseFromURI(Uri u)
{
    var response = "";
    HttpResponseMessage result;
    using (var client = new HttpClient())
    {
        Task task = Task.Run(async () =>
        {
            result = await client.GetAsync(u);
            if (result.IsSuccessStatusCode)
            {
                response = await result.Content.ReadAsStringAsync();
            }
        });
        task.Wait();
    }
    return response;
}

Here is the API controller:

[Route("api/[controller]")]
public class CartsController : Controller
{
    private readonly ICartRepository _cartRepo;

    public CartsController(ICartRepository cartRepo)
    {
        _cartRepo = cartRepo;
    }

    [HttpGet]
    public string GetTodays()
    {
        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Add")]
    public string GetIncrement()
    {
        var cart = new CountedCarts();
        _cartRepo.Add(cart);

        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Remove")]
    public string GetDecrement()
    {
        _cartRepo.RemoveLast();
        return _cartRepo.GetTodaysCarts();
    }

}

Note these API calls work as expected when called from Postman.

Body:
You are doing fire-and-forget approach. In your case, you need to wait for the result.

For example,

static async Task<string> GetResponseFromURI(Uri u)
{
    var response = "";
    using (var client = new HttpClient())
    {
        HttpResponseMessage result = await client.GetAsync(u);
        if (result.IsSuccessStatusCode)
        {
            response = await result.Content.ReadAsStringAsync();
        }
    }
    return response;
}

static void Main(string[] args)
{
    var t = Task.Run(() => GetResponseFromURI(new Uri("http://www.google.com")));
    t.Wait();

    Console.WriteLine(t.Result);
    Console.ReadLine();
}


问:
visual studio 2017 install break : it not get start

I use the permission of Administrator to install vs_enterprise.exe.
But the install package don't work at all.

OS: win10 professional

The install log in appdata/local/temp/ is as follow:

dd_bootstrapper_20170313103210:

Beginning of the log. Start Time: 13/03/2017 10:32:10
VisualStudio Bootstrapper:13/03/2017 10:32:10: Current Optin root path does not
   exists
VisualStudio Bootstrapper:13/03/2017 10:32:11: Commandline
   arguments =

dd_vs_enterprise_decompression_log.txt:

[3/13/2017, 10:32:4] === Logging started: 2017/03/13 10:32:04 ===
[3/13/2017, 10:32:4] Executable: D:\vs2017\vs_enterprise.exe
   v15.0.26206.0
[3/13/2017, 10:32:4] --- logging level: standard ---

[3/13/2017, 10:32:4] Directory
   'C:\Users\gary\AppData\Local\Temp\b012f31d56525c685e\' has been
   selected for file extraction
[3/13/2017, 10:32:4] Extracting files
   to: C:\Users\gary\AppData\Local\Temp\b012f31d56525c685e\
[3/13/2017,
   10:32:5] Extraction took 484 milliseconds
[3/13/2017, 10:32:5]
   Executing extracted package:
   'vs_bootstrapper_d15\vs_setup_bootstrapper.exe ' with commandline ' '

[3/13/2017, 10:32:11] The entire Box execution exiting with result
   code: 0x0
[3/13/2017, 10:32:11] Launched extracted application
   exiting with result code: 0xc000000d
[3/13/2017, 10:32:11] ===
   Logging stopped: 2017/03/13 10:32:11 ===

Thank You~

答:
I had a similar issue with the VS 2017 installer (similar error message), and I was finally able to resolve my problem after 4 days of troubleshooting with Microsoft Support. I'm developing on a Dell laptop and the support technician believes one of the Dell services was causing issues with the winmgmt service.

Below is a command that failed to run during troubleshooting. After making sure we had an OS restore point saved, we issued the winmgmt /resetRepository command. After that, the VS 2017 Pro installer was able to execute without error.

Here are the exact steps taken by Microsoft Support:

Step 1: Create a Windows system restore point.

Step 2: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

Step 3: Open a Windows Explorer and locate the path to C:\windows\system32\WBEM\ folder and rename the Repository folder to something else like RepositoryOLD (right click and choose 'Rename Folder').

Step 4: restart the computer

Step 5: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

```<code>C:\>net stop winmgmt
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service could not be stopped.
</code>```

Step 6: From the command prompt with administrative rights or elevated privileges, execute the following steps and execute the following this: winmgmt /resetRepository

```<code>C:\>winmgmt /resetRepository
WMI repository has been reset
</code>```

Step 7: restart the computer.

Hope this helps someone else.

Body:
I had a similar issue with the VS 2017 installer (similar error message), and I was finally able to resolve my problem after 4 days of troubleshooting with Microsoft Support. I'm developing on a Dell laptop and the support technician believes one of the Dell services was causing issues with the winmgmt service.

Below is a command that failed to run during troubleshooting. After making sure we had an OS restore point saved, we issued the winmgmt /resetRepository command. After that, the VS 2017 Pro installer was able to execute without error.

Here are the exact steps taken by Microsoft Support:

Step 1: Create a Windows system restore point.

Step 2: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

Step 3: Open a Windows Explorer and locate the path to C:\windows\system32\WBEM\ folder and rename the Repository folder to something else like RepositoryOLD (right click and choose 'Rename Folder').

Step 4: restart the computer

Step 5: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

C:\>net stop winmgmt
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service could not be stopped.

Step 6: From the command prompt with administrative rights or elevated privileges, execute the following steps and execute the following this: winmgmt /resetRepository

C:\>winmgmt /resetRepository
WMI repository has been reset

Step 7: restart the computer.

Hope this helps someone else.


问:
configure webpack to use absolute path instead of relative path
I'm having an issue with setting webpack to use the absolute path. The problem is that I cannot figure out how to get both the load path for my fonts to match the actual spot that it saves the files. This is my folder structure:

```<code>public
  font
     font1
     font2
  css
     index.css
src
  font
     font1
     font2
  css
     index.scss
webpack.config.js
</code>```

This is what my webpack file looks like. When I run webpack, it correctly adds the font files to the right spot in public->font but when I run the server, it tries to fetch the font from:

http://localhost:8080/css/public/font/font1.ttf

instead of:

http://localhost:8080/font/font1.tff

You can see that it is trying to look from the relative path of the css folder instead of the root. How can I fix this? Thanks!

```<code> module.exports = {
    entry: {
        index: './src/javascript/index.js'
    },
    output: {
        filename: './public/javascript/[name].js',
    },
    module: {
        loaders: [
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
                        {
                            test: /\.(eot|svg|ttf|woff|woff2)$/,
                            loader: 'file-loader?name=./public/font/[name].[ext]'
                        },
                        {
                            test: /\.(jpg|png)$/,
                            loader: 'file-loader?name=./public/image/[name].[ext]'
                        }
        ]
    },
    plugins: [
        new ExtractTextPlugin('public/css/index.css')
    ]
};
</code>```

答:
It tries to fetch css/public/font/font1.ttf because the output CSS reference it as ./public/font/font1.ttf as that's the name you gave it from the file-loader. The file-loader respects the output.publicPath option and will add it to the beginning of the assets import path. Setting output.publicPath to / will give you the desired path.

```<code>output: {
    filename: './public/javascript/[name].js',
    publicPath: '/',
},
</code>```

If you don't want to set output.publicPath (although it is recommended), you can also use the file-loader option publicPath, to configure it just for the given rule.

A small improvement you could make to your config is to set output.path to public because you want all files to end up in the public directory, so you don't have to specify it in every filename option. For this to work you'll also have to change output.publicPath to /public/.

The following config produces the same output (also changed the rules to use webpack 2 syntax):

```<code>const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        index: './src/javascript/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'javascript/[name].js',
        publicPath: '/public/',
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file-loader',
                options: {
                    name: 'font/[name].[ext]'
                }
            },
            {
                test: /\.(jpg|png)$/,
                loader: 'file-loader',
                options: {
                    name: 'image/[name].[ext]'
                }
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('css/index.css')
    ]
};
</code>```

Body:
I'm having an issue with setting webpack to use the absolute path. The problem is that I cannot figure out how to get both the load path for my fonts to match the actual spot that it saves the files. This is my folder structure:

public
  font
     font1
     font2
  css
     index.css
src
  font
     font1
     font2
  css
     index.scss
webpack.config.js

This is what my webpack file looks like. When I run webpack, it correctly adds the font files to the right spot in public->font but when I run the server, it tries to fetch the font from:

http://localhost:8080/css/public/font/font1.ttf

instead of:

http://localhost:8080/font/font1.tff

You can see that it is trying to look from the relative path of the css folder instead of the root. How can I fix this? Thanks!

 module.exports = {
    entry: {
        index: './src/javascript/index.js'
    },
    output: {
        filename: './public/javascript/[name].js',
    },
    module: {
        loaders: [
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
                        {
                            test: /\.(eot|svg|ttf|woff|woff2)$/,
                            loader: 'file-loader?name=./public/font/[name].[ext]'
                        },
                        {
                            test: /\.(jpg|png)$/,
                            loader: 'file-loader?name=./public/image/[name].[ext]'
                        }
        ]
    },
    plugins: [
        new ExtractTextPlugin('public/css/index.css')
    ]
};

Body:
It tries to fetch css/public/font/font1.ttf because the output CSS reference it as ./public/font/font1.ttf as that's the name you gave it from the file-loader. The file-loader respects the output.publicPath option and will add it to the beginning of the assets import path. Setting output.publicPath to / will give you the desired path.

output: {
    filename: './public/javascript/[name].js',
    publicPath: '/',
},

If you don't want to set output.publicPath (although it is recommended), you can also use the file-loader option publicPath, to configure it just for the given rule.

A small improvement you could make to your config is to set output.path to public because you want all files to end up in the public directory, so you don't have to specify it in every filename option. For this to work you'll also have to change output.publicPath to /public/.

The following config produces the same output (also changed the rules to use webpack 2 syntax):

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        index: './src/javascript/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'javascript/[name].js',
        publicPath: '/public/',
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file-loader',
                options: {
                    name: 'font/[name].[ext]'
                }
            },
            {
                test: /\.(jpg|png)$/,
                loader: 'file-loader',
                options: {
                    name: 'image/[name].[ext]'
                }
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('css/index.css')
    ]
};


问:
Output string with leading spaces to log, keeping the spaces
How can I print leading spaces to the log?

When I do something like

```<code>data _null_;
  x = '  Hello, world!';
  put x;
run;
</code>```

The result is

```<code>2522  data _null_;
2523    x = '  Hello, world!';
2524    putlog x;
2525  run;

Hello, world!
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds
</code>```

I looked through the PUT documentation, but nothing stood out to me.  It seems like using a format, such as $CHARw., might work.  However, that would require knowing the length of the string ahead of time.

I would like the log output to look like this:

```<code>  Hello, world!  (<--edited by hand to display leading spaces)
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds
</code>```

答:
Use +2 (or however long) works with put (but not putlog).

```<code>data _null_;
  x = '  Hello, world!';
  put +2 x $;
run;
</code>```

With putlog you must add an @ or something similar to trick the compiler:

```<code>data _null_;
  x = '  Hello, world!';
  putlog @ +2 x $;
run;
</code>```

Body:
How can I print leading spaces to the log?

When I do something like

data _null_;
  x = '  Hello, world!';
  put x;
run;

The result is

2522  data _null_;
2523    x = '  Hello, world!';
2524    putlog x;
2525  run;

Hello, world!
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

I looked through the PUT documentation, but nothing stood out to me.  It seems like using a format, such as $CHARw., might work.  However, that would require knowing the length of the string ahead of time.

I would like the log output to look like this:

  Hello, world!  (<--edited by hand to display leading spaces)
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

Body:
Use +2 (or however long) works with put (but not putlog).

data _null_;
  x = '  Hello, world!';
  put +2 x $;
run;

With putlog you must add an @ or something similar to trick the compiler:

data _null_;
  x = '  Hello, world!';
  putlog @ +2 x $;
run;


问:
Generic async Retry with Timeout function in C#
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

```<code>await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);
</code>```

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

答:
Don't reinvent the wheel. Just use Polly which supports exactly the scenario you're talking about as well as all kinds of scenarios for retry and advanced patterns like circuit breaker.

Here's an async example from their docs:

```<code>await Policy
  .Handle<SqlException>(ex => ex.Number == 1205)
  .Or<ArgumentException>(ex => ex.ParamName == "example")
  .RetryAsync()
  .ExecuteAsync(() => DoSomethingAsync());
</code>```

Body:
I have hundreds of calls to various external API's that I want to wrap in a generic async function that is capable of doing retries and handling timeouts.

Basically, I think I need to implement something like this function call:

await Retry(()=>someFunctionAsync(doWorkParams, new CancellationToken()), retryCount, timeout);

How do I define such Retry function?  Also, how do I call this function from Sync code, as a ton of my calls are housed in the sync methods?

Body:
Don't reinvent the wheel. Just use Polly which supports exactly the scenario you're talking about as well as all kinds of scenarios for retry and advanced patterns like circuit breaker.

Here's an async example from their docs:

await Policy
  .Handle<SqlException>(ex => ex.Number == 1205)
  .Or<ArgumentException>(ex => ex.ParamName == "example")
  .RetryAsync()
  .ExecuteAsync(() => DoSomethingAsync());


问:
Adding to an ArrayList using a perameterized constructor
I'm currently writing a code that takes in information from a file, and then fills an array with the object Request (which I've already written in another java file) based on the information in the file. This is what I have so far in my main method

```<code>Scanner userIn = new Scanner(System.in);
System.out.println("Please input the file name that you would like to be read into reqMover");
String thisFile = userIn.next();
FileReader inReader = new FileReader(thisFile);
Scanner inFile = new Scanner(inReader);

ArrayList<Request> newReq = new ArrayList<Request>();

do{
    newReq.add(Request(inFile.nextInt(), inFile.nextInt(),
                       inFile.nextInt(), inFile.nextInt()));
    inFile.nextLine();
}while(inFile.hasNextLine());
</code>```

This code resides in a java file called reqMover. This problem that I'm having is that the compiler is telling me "The method Request(int, int, int, int) is undefined for the type reqMover" even though that method is the constructor I created in the other class. Is there something special I need to do to load the ArrayList using this constructor?

答:
It seems you are calling the Constructor of Request Class
To create the instance or calling annoymus object you need to use new operator.
If not i.e you are not calling the constructor you need to define a method with the signature of

```<code>Access-Specifier return type Request (type param1, type param2, type aram3, type param4){
  //handle your actions
}
</code>```

Body:
I'm currently writing a code that takes in information from a file, and then fills an array with the object Request (which I've already written in another java file) based on the information in the file. This is what I have so far in my main method

Scanner userIn = new Scanner(System.in);
System.out.println("Please input the file name that you would like to be read into reqMover");
String thisFile = userIn.next();
FileReader inReader = new FileReader(thisFile);
Scanner inFile = new Scanner(inReader);

ArrayList<Request> newReq = new ArrayList<Request>();

do{
    newReq.add(Request(inFile.nextInt(), inFile.nextInt(),
                       inFile.nextInt(), inFile.nextInt()));
    inFile.nextLine();
}while(inFile.hasNextLine());

This code resides in a java file called reqMover. This problem that I'm having is that the compiler is telling me "The method Request(int, int, int, int) is undefined for the type reqMover" even though that method is the constructor I created in the other class. Is there something special I need to do to load the ArrayList using this constructor?

Body:
It seems you are calling the Constructor of Request Class
To create the instance or calling annoymus object you need to use new operator.
If not i.e you are not calling the constructor you need to define a method with the signature of

Access-Specifier return type Request (type param1, type param2, type aram3, type param4){
  //handle your actions
}


问:
Prestashop 1.6.1.11 (500) Internal server error (Associations) bytes exhausted
I've had a question posted on the Prestashop forums for some time regarding an issue that I'm not sure how to resolve. I'll post the link below to the original question, any assistance I can get regarding this issue would be greatly appreciated.

Initial Prestashop Forum Question.

Prestashop 1.6.1.11: Everytime I access certain products and try to edit thier associations I receive an error notice;

(500 Internal Server Error)

A server error occurred while loading the tabs: some tabs could not be
  loaded. Please try again by refreshing the page. If you are still
  encountering this problem, please check your server logs or contact
  your hosting provider for assistance.

I completed a few steps to try to identify the error as shown below in my code snippet, a result of which I was able to return a few details regarding the error.

```<code><php

// I enabled dev mode via config/defines.inc.php
if (!defined('_PS_MODE_DEV_')) {
define('_PS_MODE_DEV_', true);
}

?>
</code>```

Re-tracing the steps I tried to reccur the error.

This was my result...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /classes/cache/CacheFs.php on line 69

I took a few steps forward in hopes of correcting this issue but all to no avail. I'll list the steps I've attempted below;

Adjusted my php.ini to allow the full memory limit, I'll post a full copy of which below. (memory_limit = 128M)

Contacted my hosting provider to have the 'xCache' caching module installed on my sever in hopes of worming my around the default caching solution and finding a possible fix. However this is not possible at this time.

Checked for recently installed module issues. (None found)

I have done some further digging on the web but most solutions seem exstensive, such as rebuilding the code to be less memory intensive. Sadly, I'm not confident enough in my ability to reliably resolve this issue with my current knowledge and I'm seeking some advice on how to go about resolving this error.

Regards,
-B

EDIT

After further digging and after disabling caching, my error location has changedto; Adapter/Adapter_EntityMapper.php on line 98.

答:
You have exhausted 128M and also exhausted 1024M, which is ludicrous (actually, 128M is pretty ludicrous in its own right).

This isn't likely to be a standard leak; looks more like a looped allocation. It's almost as if the entity mapper found a link to another entity that, by a commodius vicus of recirculation, brought back to the first entity. When trying to resolve the Entity-Relationship-Attribute graph, each loops allocates more memory in a nested structure, until all available memory is exhausted.

Just as an example, and not even in PHP:

```<code>ProductA: {
    Name: "Phone charger",
    Details: {
         Accessories: {
             ProductB: {
                 Name: "Phone charger cable",
                 Details: {
                     Accessories: {
                         ProductA: {
                             Name: "Phone charger",
                             Details: {
                                 ...
</code>```

Can you verify whether your product attribute structure is identical between one of the products that work, and one that does not?

Body:
I've had a question posted on the Prestashop forums for some time regarding an issue that I'm not sure how to resolve. I'll post the link below to the original question, any assistance I can get regarding this issue would be greatly appreciated.

Initial Prestashop Forum Question.

Prestashop 1.6.1.11: Everytime I access certain products and try to edit thier associations I receive an error notice;

(500 Internal Server Error)

A server error occurred while loading the tabs: some tabs could not be
  loaded. Please try again by refreshing the page. If you are still
  encountering this problem, please check your server logs or contact
  your hosting provider for assistance.

I completed a few steps to try to identify the error as shown below in my code snippet, a result of which I was able to return a few details regarding the error.

<php

// I enabled dev mode via config/defines.inc.php
if (!defined('_PS_MODE_DEV_')) {
define('_PS_MODE_DEV_', true);
}

?>

Re-tracing the steps I tried to reccur the error.

This was my result...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) in /classes/cache/CacheFs.php on line 69

I took a few steps forward in hopes of correcting this issue but all to no avail. I'll list the steps I've attempted below;

Adjusted my php.ini to allow the full memory limit, I'll post a full copy of which below. (memory_limit = 128M)

Contacted my hosting provider to have the 'xCache' caching module installed on my sever in hopes of worming my around the default caching solution and finding a possible fix. However this is not possible at this time.

Checked for recently installed module issues. (None found)

I have done some further digging on the web but most solutions seem exstensive, such as rebuilding the code to be less memory intensive. Sadly, I'm not confident enough in my ability to reliably resolve this issue with my current knowledge and I'm seeking some advice on how to go about resolving this error.

Regards,
-B

EDIT

After further digging and after disabling caching, my error location has changedto; Adapter/Adapter_EntityMapper.php on line 98.

Body:
You have exhausted 128M and also exhausted 1024M, which is ludicrous (actually, 128M is pretty ludicrous in its own right).

This isn't likely to be a standard leak; looks more like a looped allocation. It's almost as if the entity mapper found a link to another entity that, by a commodius vicus of recirculation, brought back to the first entity. When trying to resolve the Entity-Relationship-Attribute graph, each loops allocates more memory in a nested structure, until all available memory is exhausted.

Just as an example, and not even in PHP:

ProductA: {
    Name: "Phone charger",
    Details: {
         Accessories: {
             ProductB: {
                 Name: "Phone charger cable",
                 Details: {
                     Accessories: {
                         ProductA: {
                             Name: "Phone charger",
                             Details: {
                                 ...

Can you verify whether your product attribute structure is identical between one of the products that work, and one that does not?