问:
Memory comsumption of a process initiated by Java ProcessBuilder
Is there a way to limit memory consumption of a process initiated by java processbuilder ?
or
to get the maximum memory used by the process?

I have tried using the following code..but is always returns 0.

```<code>ProcessBuilder p = new ProcessBuilder(command);
before=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
Process pp = p.start();
after=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Used : "+before-after);
</code>```

I am a beginner..please pardon if the question is silly...

答:
ProcessBuilder constructors provide a way to set arguments to the program.

For example you have :

```<code>public ProcessBuilder(String... command)
</code>```

where the command argument vargs contain the program but also its arguments if provided.

And you have also a constructor that provides the same goal but with a List as parameter :

```<code>public ProcessBuilder(List<String> command)
</code>```

In your case, if your program is a Java program, you could write something like that to limit to 512M the maximum memory used by the process :

```<code>ProcessBuilder processBuilder =
        new ProcessBuilder(pathToTheJavaCommand, "-Xmx512m", "-cp", classpath, yourClass);
</code>```

In the case of your program is not a Java program, either your program provides a parameter to set the max memory allocated for it or you shoud use a OS specific feature that limits the consumed memory. But the second case is not necessary fine as it may have critical side effects on the started program if the memory is absolutely required for the program.

At last, Runtime.getRuntime() returns the runtime object associated with the current Java application, not the runtime object of the last launched Process.

Body:
Is there a way to limit memory consumption of a process initiated by java processbuilder ?
or
to get the maximum memory used by the process?

I have tried using the following code..but is always returns 0.

ProcessBuilder p = new ProcessBuilder(command);
before=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
Process pp = p.start();
after=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Used : "+before-after);

I am a beginner..please pardon if the question is silly...

Body:
ProcessBuilder constructors provide a way to set arguments to the program.

For example you have :

public ProcessBuilder(String... command)

where the command argument vargs contain the program but also its arguments if provided.

And you have also a constructor that provides the same goal but with a List as parameter :

public ProcessBuilder(List<String> command)

In your case, if your program is a Java program, you could write something like that to limit to 512M the maximum memory used by the process :

ProcessBuilder processBuilder =
        new ProcessBuilder(pathToTheJavaCommand, "-Xmx512m", "-cp", classpath, yourClass);

In the case of your program is not a Java program, either your program provides a parameter to set the max memory allocated for it or you shoud use a OS specific feature that limits the consumed memory. But the second case is not necessary fine as it may have critical side effects on the started program if the memory is absolutely required for the program.

At last, Runtime.getRuntime() returns the runtime object associated with the current Java application, not the runtime object of the last launched Process.


来源: stackexchange

问:
Adding a textfile with a name to each directory
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

```<code>@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal
</code>```

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

答:
Iterate over all of the subdirectories and create a test.txt file.</p>

```<code>set "folder=%~1"
if not defined folder set "folder=%cd%"

FOR /F "usebackq tokens=*" %%a IN (`DIR /S /B /A:D "%folder%\*"`) DO (
    ECHO test > "%%~a\test.txt"
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

Body:
Iterate over all of the subdirectories and create a test.txt file.

set "folder=%~1"
if not defined folder set "folder=%cd%"

FOR /F "usebackq tokens=*" %%a IN (`DIR /S /B /A:D "%folder%\*"`) DO (
    ECHO test > "%%~a\test.txt"
)


问:
How to add gravity to multiple bodies 'automatically'?
I know how to add gravity to any given object/element. Just add acceleration Y downwards. But "what if want my hero to fly?" or "what if I want to turn gravity off for one particular object? I'll have to set gravity = 0 which will turn off for everyone obviously. I also thought giving every shape their own 'gravity' variable, but I figured that would be too much and it's probably not how it's done...

How would I go from creating shapes

(Using EaseJS)

```<code>function spawnShape(x, y, w, h) {
    var shape = new createjs.Shape();
    shape.graphics.beginFill("black").drawRect(x, y, w, h);
    stage.addChild(shape);
}

spawnShape(20, 250, 600, 30);
spawnShape(200, 150, 5, 5);

stage.update();
</code>```

to adding gravity "automatically"? (every shape inheriting downwards acceleration) I know there's 2D physics engines made but I want to do/understand this myself, and I did try to use PhysicsJS but failed to do so.. I'll probably be using an engine but for now I want to know how to do this :P

答:
I think you understand how to add gravity or not add gravity to an object. As you say, it is just adding acceleration Y to the object.

It sounds like you just need to think out your design a little. Let's say you have a module 'gravity.js' that is responsible for applying gravity to an object.

```<code>/* gravity.js */
const DEFAULT_GRAVITY_ACCELERATION = 1.0;

function applyGravity(shape) {
  const gravity = shape.gravityAcceleration !== undefined ?
    shape.gravityAcceleration : DEFAULT_GRAVITY_ACCELERATION;

  //Do whatever you normally do to update Y acceleration. Code below
  //is just an example.
  shape.addYAcceleration(gravity);
}
</code>```

If you create a shape someplace and want it to be free of gravity, just set the .gravityAcceleration member of that object. BTW, there is nothing special about that "gravityAcceleration" name--it could be whatever you want.

```<code>//Assuming spawnShape returns an object.
var superman = spawnShape(20, 250, 600, 30);
superman.gravityAcceleration = 0; //Override the default gravity.
</code>```

You only need to set the .gravityAcceleration member for shape objects that will defy gravity.

Body:
I know how to add gravity to any given object/element. Just add acceleration Y downwards. But "what if want my hero to fly?" or "what if I want to turn gravity off for one particular object? I'll have to set gravity = 0 which will turn off for everyone obviously. I also thought giving every shape their own 'gravity' variable, but I figured that would be too much and it's probably not how it's done...

How would I go from creating shapes

(Using EaseJS)

function spawnShape(x, y, w, h) {
    var shape = new createjs.Shape();
    shape.graphics.beginFill("black").drawRect(x, y, w, h);
    stage.addChild(shape);
}

spawnShape(20, 250, 600, 30);
spawnShape(200, 150, 5, 5);

stage.update();

to adding gravity "automatically"? (every shape inheriting downwards acceleration) I know there's 2D physics engines made but I want to do/understand this myself, and I did try to use PhysicsJS but failed to do so.. I'll probably be using an engine but for now I want to know how to do this :P

Body:
I think you understand how to add gravity or not add gravity to an object. As you say, it is just adding acceleration Y to the object.

It sounds like you just need to think out your design a little. Let's say you have a module 'gravity.js' that is responsible for applying gravity to an object.

/* gravity.js */
const DEFAULT_GRAVITY_ACCELERATION = 1.0;

function applyGravity(shape) {
  const gravity = shape.gravityAcceleration !== undefined ?
    shape.gravityAcceleration : DEFAULT_GRAVITY_ACCELERATION;

  //Do whatever you normally do to update Y acceleration. Code below
  //is just an example.
  shape.addYAcceleration(gravity);
}

If you create a shape someplace and want it to be free of gravity, just set the .gravityAcceleration member of that object. BTW, there is nothing special about that "gravityAcceleration" name--it could be whatever you want.

//Assuming spawnShape returns an object.
var superman = spawnShape(20, 250, 600, 30);
superman.gravityAcceleration = 0; //Override the default gravity.

You only need to set the .gravityAcceleration member for shape objects that will defy gravity.


问:
Can't pass to onclick in angular directive
look at the following angular directive:

```<code>angular.module("mySystem").directive("pageFooter", function () {
    return {
        restrict: "E",
        scope: { footerhref: '&' },
        template: <button onclick="{{footerhref}}">{{footerhref}}</button>
    }
});

<page-footer footerhref="location.href='\Home.html'" />
</code>```

Could somebody tell me why the footerhref doesn't pass through into the onclick but it does for the button content? (I don't want it in the content. I've just added that an example).

And is this possible to fix?

If I just create a button like below it works:

```<code> <button onclick="location.href = '\Home.html'">Using onclick without Angular</button>
</code>```

This is how I'm trying to get the angular directive to render.

答:
onclick expects a function call and not an expression that resolves to a string.

You would have to use & instead of @ since we are passing in a executable line of code rather than a string.

You will have to use ng-click instead of onclick. The reason why onclick will not work, based on the documentation is:

Interpolations for HTML DOM event attributes are disallowed.  Please
  use the ng- versions (such as ng-click instead of onclick) instead.

Also, change templateUrl to template since you are providing the template inline

You will have to set the location reference in the $scope since you are trying to access location from the UI markup <page-footer footerhref="location.href='\Home.html'" />

Here is a working plunker.

```<code>app.directive("pageFooter", function ($compile) {
    return {
        restrict: "E",
        scope: { footerhref: '&', caption: '@' },
        template: '<button ng-click="footerhref()">{{caption}}</button>'
    }
});

<page-footer footerhref="location.href='\Home.html'" caption="Home"></page-footer>

$scope.location = location; // In your controller
</code>```

Body:
look at the following angular directive:

angular.module("mySystem").directive("pageFooter", function () {
    return {
        restrict: "E",
        scope: { footerhref: '&' },
        template: <button onclick="{{footerhref}}">{{footerhref}}</button>
    }
});

<page-footer footerhref="location.href='\Home.html'" />

Could somebody tell me why the footerhref doesn't pass through into the onclick but it does for the button content? (I don't want it in the content. I've just added that an example).

And is this possible to fix?

If I just create a button like below it works:

 <button onclick="location.href = '\Home.html'">Using onclick without Angular</button>

This is how I'm trying to get the angular directive to render.

Body:
onclick expects a function call and not an expression that resolves to a string.

You would have to use & instead of @ since we are passing in a executable line of code rather than a string.

You will have to use ng-click instead of onclick. The reason why onclick will not work, based on the documentation is:

Interpolations for HTML DOM event attributes are disallowed.  Please
  use the ng- versions (such as ng-click instead of onclick) instead.

Also, change templateUrl to template since you are providing the template inline

You will have to set the location reference in the $scope since you are trying to access location from the UI markup <page-footer footerhref="location.href='\Home.html'" />

Here is a working plunker.

app.directive("pageFooter", function ($compile) {
    return {
        restrict: "E",
        scope: { footerhref: '&', caption: '@' },
        template: '<button ng-click="footerhref()">{{caption}}</button>'
    }
});

<page-footer footerhref="location.href='\Home.html'" caption="Home"></page-footer>

$scope.location = location; // In your controller


问:
How to initialize msvcrt.dll?
If I do a LoadLibrary("msvcrt.dll") do I need to initialize the CRT somehow? Section 2 in the following document seems to say that I do, but I just get an undefined symbol error for _CRT_INIT when I try to call _CRT_INIT:

http://support.microsoft.com/kb/94248

Edit: I should have said that this is for a program that dynamically loads all the dlls that it uses, hence the call to LoadLibrary("msvcrt.dll").

答:
Call DllMain() in it.  If it relies on the C runtime, it will call CRT_INIT.

But a far better question is if a program is using something in msvcrt, there's no need to explicitly load the dll and initialize it, so why are you doing this?

ContentLicense: CC BY-SA 2.5

Title: How to initialize msvcrt.dll?


答:
No, the processes started using ProcessBuilder are operating system processes and there is no way to control the way to limit their resources from JVM/using Java APIs. You could however try to limit resources, after getting PID of the Process using operating system APIs (for example, cgroups on Linux).

Also, this:

```<code>after = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
</code>```

is not related to ProcessBuilder (apart from some allocation Java is making for ProcessBuilder object) the way you think. It returns memory of Java Runtime, not the process you have started using ProcessBuilder.

Title: Memory comsumption of a process initiated by Java ProcessBuilder

Body:
No, the processes started using ProcessBuilder are operating system processes and there is no way to control the way to limit their resources from JVM/using Java APIs. You could however try to limit resources, after getting PID of the Process using operating system APIs (for example, cgroups on Linux).

Also, this:

after = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

is not related to ProcessBuilder (apart from some allocation Java is making for ProcessBuilder object) the way you think. It returns memory of Java Runtime, not the process you have started using ProcessBuilder.


问:
<f:viewParam>: Ignore wrong parameters silently
We just started to migrate an older jsf 1 project to jsf version 2.3 with new requirements. Currently I am working on pages that use viewparams. what would be the right way to silently ignore wrong parameter-types?

for example with this definition for page searchResults.xhtml:

```<code><f:metadata>
   <f:viewParam name="lastPrice"
             value="#{ReportAgentBean.lastPrice}" converter="javax.faces.Double"/>

   <f:viewParam name="currentPrice"
             value="#{ReportAgentBean.currentPrice}" converter="javax.faces.Double"/>

   <f:viewParam name="listPrice"
             value="#{ReportAgentBean.listPrice}" converter="javax.faces.Double"/>
</f:metadata>
</code>```

what would be the best approach to ignore invalid parameters or just handle them as null if someone fires a request like:

http://www.ourapp.com/reports/searchResults?lastPrice=undefined?currentPrice=INVALIDSTRING

which ideally would result in:

http://www.ourapp.com/reports/searchResults

thanks for any hint.

答:
As far as I know, the default faces converters you use cannot accept/ignore invalid values passed to it and ignore them.

For this to work, you need to create your own custom converters, do the casting to the right type in there and if the casting is successful, return the cast value and if it fails, return some default.

This is what you'd normally do for more complex param/converter combinations where just the presence of an id would read a full complex object from somewhere

This whole concept is also used in the OmniFaces @Param annotation which might be an interesting solution to. They set the fields to null if conversion fails. See the demo on that page too.

Body:
We just started to migrate an older jsf 1 project to jsf version 2.3 with new requirements. Currently I am working on pages that use viewparams. what would be the right way to silently ignore wrong parameter-types?

for example with this definition for page searchResults.xhtml:

<f:metadata>
   <f:viewParam name="lastPrice"
             value="#{ReportAgentBean.lastPrice}" converter="javax.faces.Double"/>

   <f:viewParam name="currentPrice"
             value="#{ReportAgentBean.currentPrice}" converter="javax.faces.Double"/>

   <f:viewParam name="listPrice"
             value="#{ReportAgentBean.listPrice}" converter="javax.faces.Double"/>
</f:metadata>

what would be the best approach to ignore invalid parameters or just handle them as null if someone fires a request like:

http://www.ourapp.com/reports/searchResults?lastPrice=undefined?currentPrice=INVALIDSTRING

which ideally would result in:

http://www.ourapp.com/reports/searchResults

thanks for any hint.

ContentLicense: CC BY-SA 4.0


问:
How to implements a null-safe Restrictions builder?
I'm screwing up with the implementation of a method that should take two parameters:

a Criteria

and a list of Criterion

My code actually is:

```<code>public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {

    final List<Criterion> validCriterion = new ArrayList<Criterion>(conditions.length);

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }

    if (validCriterion.size() == 0) {
        return;
    } else {
        if (validCriterion.size() == 1) {
            criteria.add(validCriterion.get(0));
        } else {
            //Can't convert list to ... varargs
            criteria.add(Restrictions.or( *** validCriterion *** ));
        }
    }

}
</code>```

I can't find any way to convert an ArrayList to  varargs but specially I'm looking for a better solution, like any existing HibernateUtils library or any Restriction's method, I didn't know, that create a null-safe Restrictions.

Thanks.

答:
I dont think Hibernate has special utility to check for null. If it needed to do that it would just add the check inside Restrictions class or classes that it passes the Criterion array.
Given that the Hibernate javadoc does not say anything about null in the public static Disjunction or(Criterion... predicates) I would assume that it is not expecting null in the predicates array.

In general libraries dont handle null values in the collections unless they explicitly specify how they are going to threat nulls.

Now back to your code. Maybe you need to avoid passing null Criterion in the first place. Check everywhere addNullSafeOrCondition is used and see if you can avoid passing null Criterion.

If you can do that then you dont need to define addNullSafeOrCondition and can directly use criteria.add(Restrictions.or(....)) method.

If not then I would change addNullSafeOrCondition to be like this:

Java 8 version:

```<code>public static void addNullSafeOrCondition(Criteria criteria, Criterion... conditions) {
    Criterion[] validCriterions = Arrays.stream(conditions).filter( c -> c != null ).toArray( Criterion[]::new );
    if (validCriterions.length == 0) return;
    criteria.add( Restrictions.or(validCriterions) );
}
</code>```

Java 7 version:

```<code>public static void addNullSafeOrCondition(Criteria criteria, Criterion... conditions) {
    List<Criterion> validCriterions = new ArrayList<>();
    for (Criterion c : conditions) if (c != null) validCriterions.add(c);

    if ( validCriterions.isEmpty() ) return;

    criteria.add( Restrictions.or( validCriterions.toArray( new Criterion[ validCriterions.size() ] ) ) );
}
</code>```

Body:
I'm screwing up with the implementation of a method that should take two parameters:

a Criteria

and a list of Criterion

My code actually is:

public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {

    final List<Criterion> validCriterion = new ArrayList<Criterion>(conditions.length);

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }

    if (validCriterion.size() == 0) {
        return;
    } else {
        if (validCriterion.size() == 1) {
            criteria.add(validCriterion.get(0));
        } else {
            //Can't convert list to ... varargs
            criteria.add(Restrictions.or( *** validCriterion *** ));
        }
    }

}

I can't find any way to convert an ArrayList to  varargs but specially I'm looking for a better solution, like any existing HibernateUtils library or any Restriction's method, I didn't know, that create a null-safe Restrictions.

Thanks.

Body:
I dont think Hibernate has special utility to check for null. If it needed to do that it would just add the check inside Restrictions class or classes that it passes the Criterion array.
Given that the Hibernate javadoc does not say anything about null in the public static Disjunction or(Criterion... predicates) I would assume that it is not expecting null in the predicates array.

In general libraries dont handle null values in the collections unless they explicitly specify how they are going to threat nulls.

Now back to your code. Maybe you need to avoid passing null Criterion in the first place. Check everywhere addNullSafeOrCondition is used and see if you can avoid passing null Criterion.

If you can do that then you dont need to define addNullSafeOrCondition and can directly use criteria.add(Restrictions.or(....)) method.

If not then I would change addNullSafeOrCondition to be like this:

Java 8 version:

public static void addNullSafeOrCondition(Criteria criteria, Criterion... conditions) {
    Criterion[] validCriterions = Arrays.stream(conditions).filter( c -> c != null ).toArray( Criterion[]::new );
    if (validCriterions.length == 0) return;
    criteria.add( Restrictions.or(validCriterions) );
}

Java 7 version:

public static void addNullSafeOrCondition(Criteria criteria, Criterion... conditions) {
    List<Criterion> validCriterions = new ArrayList<>();
    for (Criterion c : conditions) if (c != null) validCriterions.add(c);

    if ( validCriterions.isEmpty() ) return;

    criteria.add( Restrictions.or( validCriterions.toArray( new Criterion[ validCriterions.size() ] ) ) );
}


问:
How to add multiple small ROI (Region of interest) to form an image in numpy?
I have a list of small ROI (Region of interest) of an image, represented by numpy array. How can I add or stitch the ROI together to form a larger image (numpy array)? Each ROI is 50x50 and I want it to stitch together into 500x400 image.
I know how to do it using basic loops, but is there a numpy function that I can use?

Thank you.

答:
You can use np.vstack or np.hstack depending on how you want them stitched.

An example of np.vstack:

```<code>>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
       [2, 3, 4]])
</code>```

And, an example for np.hstack:

```<code>>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
</code>```

My advice is to stitch all the ROIs horizontally, and then stitch the resultant rows vertically.

So, you first stitch 8 50x50 ROIs horizontally using np.hstack to form a row. Do this 10 times to get 10 rows, each of dimension 50x400.

Now, stitch all the resultant rows vertically using np.vstack to get your image of dimension 500x400.

Let me know if I've gotten anything wrong.

Body:
You can use np.vstack or np.hstack depending on how you want them stitched.

An example of np.vstack:

>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
       [2, 3, 4]])

And, an example for np.hstack:

>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])

My advice is to stitch all the ROIs horizontally, and then stitch the resultant rows vertically.

So, you first stitch 8 50x50 ROIs horizontally using np.hstack to form a row. Do this 10 times to get 10 rows, each of dimension 50x400.

Now, stitch all the resultant rows vertically using np.vstack to get your image of dimension 500x400.

Let me know if I've gotten anything wrong.


问:
"No provisioned iPhone OS device is connected" after update to 4.0
I updated my iPhone to the new OS 4.0 and went to build my iPhone app and everything built ok, but the message I got at the end was "No provisioned iPhone OS device is connected". Looking at the Xcode organiser, it shows my connected device with an amber icon next to it, and all my provisioning profiles show up as "Installed" but also with an amber icon.

Is there something I need to do to make the existing provisioning profiles work since updating to OS 4.0?

I have XCode 3.1.3, and 10.5.8 OS. I can not install XCode 3.2.3, because for that I would need 10.6.2 OS which I do not have.

So, how do I continue developing and debugging as I used to before I said "yes" to the update dialog on my iPhone, without buying a new OS or new iPhone?

Thank you for your help.

EDIT1:
I do not want to develop for iOS 4.0.

答:
There are two things you need to do:

Make sure your XCode is up-to-date.

Reboot your iOS.

For some reason updating the OS makes it confused as to its provisioning profile until it it reboots.


问:
How to send values set to pojo references to another activity and displayed in adapter view in android
I have parsed the json response using the pojo classes and I want these values to be carried to another activity and there I want to show them in adapter view.

FeedPojo.java

```<code>public class FeedPojo {
private static String id;
    private static String partnerId;
    private static String type;
    private static String name;
    private static String description;
    private static String start;
    private static String text;
    private static String photoUrl;
    private static String videoUrl;
    public FeedPojo(String id,String type,String name,String description,String start){

            this.setId(id);
            this.setType(type);
            this.setName(name);
            this.setDescription(description);
            this.setStart(start);
    }
public FeedPojo(String id,String text,String photoUrl,String videoUrl,String isNew){

        this.setId(id);
        this.setText(text);
        this.setPhotoUrl(photoUrl);
        this.setVideoUrl(videoUrl);
        this.setIsNew(isNew);

    }
}
</code>```

MainActiviy.java

```<code>    FeedPojo feedPojoNews = new FeedPojo(
promoJsonObject.getString("id"),                                                                                promoJsonObject.getString("text"),                                                                promoJsonObject.getString("photoUrl"),                                                                promoJsonObject.getString("videoUrl"),                                                                promoJsonObject.getString("isNew"));
    Log.d(TAG, "FeedPojoNewsId" + feedPojoNews.getId());                                                Log.d(TAG, "FeedPojoNewsText" + feedPojoNews.getText());                                                Log.d(TAG, "FeedPojoNewsPhotoUrl" + feedPojoNews.getPhotoUrl());                                                Log.d(TAG, "FeedPojoNewsVideoUrl" + feedPojoNews.getVideoUrl());                                                Log.d(TAG, "FeedPojoNewsisNew" + feedPojoNews.getIsNew());           FeedPojo feedPojoPartnerGn = new FeedPojo(promoJsonObject.getString("id"),
    promoJsonObject.getString("text"),                                                                        promoJsonObject.getString("photoUrl"),                                                                    promoJsonObject.getString("videoUrl"),                                                                                Log.d(TAG, "FeedPojoPartnerId" + feedPojoPartnerGn.getId());
    Log.d(TAG, "FeedPojoPartnerImageurl" + feedPojoPartnerGn.getPhotoUrl());
    Log.d(TAG, "FeedPojoPartnerbuyUrl" + feedPojoPartnerGn.getVideoUrl());
</code>```

答:
implement Serializable

```<code>public class FeedPojo implements Serializable {
private static String id;
    private static String partnerId;
    private static String type;
    private static String name;
    private static String description;
    private static String start;
    private static String text;
    private static String photoUrl;
    private static String videoUrl;
    public FeedPojo(String id,String type,String name,String description,String start){

            this.setId(id);
            this.setType(type);
            this.setName(name);
            this.setDescription(description);
            this.setStart(start);
    }
public FeedPojo(String id,String text,String photoUrl,String videoUrl,String isNew){

        this.setId(id);
        this.setText(text);
        this.setPhotoUrl(photoUrl);
        this.setVideoUrl(videoUrl);
        this.setIsNew(isNew);

    }
}
</code>```

then put data in bundle like this

```<code> Bundle bundle = new Bundle();
  bundle.putSerializable("DATA", feedPojoNews);
  Intent intent = new
  Intent(MainActivity.this,SecondActivity.class);
  intent.putExtras(bundle);
  startActivity(intent);
</code>```

In second Activity Extract data like this

```<code>Intent intent = this.getIntent();
 Bundle bundle = intent.getExtras();
 FeedPojo feedPojo= (FeedPojo ) bundle.getSerializable("DATA");
</code>```

Body:
I have parsed the json response using the pojo classes and I want these values to be carried to another activity and there I want to show them in adapter view.

FeedPojo.java

public class FeedPojo {
private static String id;
    private static String partnerId;
    private static String type;
    private static String name;
    private static String description;
    private static String start;
    private static String text;
    private static String photoUrl;
    private static String videoUrl;
    public FeedPojo(String id,String type,String name,String description,String start){

            this.setId(id);
            this.setType(type);
            this.setName(name);
            this.setDescription(description);
            this.setStart(start);
    }
public FeedPojo(String id,String text,String photoUrl,String videoUrl,String isNew){

        this.setId(id);
        this.setText(text);
        this.setPhotoUrl(photoUrl);
        this.setVideoUrl(videoUrl);
        this.setIsNew(isNew);

    }
}

MainActiviy.java

    FeedPojo feedPojoNews = new FeedPojo(
promoJsonObject.getString("id"),                                                                                promoJsonObject.getString("text"),                                                                promoJsonObject.getString("photoUrl"),                                                                promoJsonObject.getString("videoUrl"),                                                                promoJsonObject.getString("isNew"));
    Log.d(TAG, "FeedPojoNewsId" + feedPojoNews.getId());                                                Log.d(TAG, "FeedPojoNewsText" + feedPojoNews.getText());                                                Log.d(TAG, "FeedPojoNewsPhotoUrl" + feedPojoNews.getPhotoUrl());                                                Log.d(TAG, "FeedPojoNewsVideoUrl" + feedPojoNews.getVideoUrl());                                                Log.d(TAG, "FeedPojoNewsisNew" + feedPojoNews.getIsNew());           FeedPojo feedPojoPartnerGn = new FeedPojo(promoJsonObject.getString("id"),
    promoJsonObject.getString("text"),                                                                        promoJsonObject.getString("photoUrl"),                                                                    promoJsonObject.getString("videoUrl"),                                                                                Log.d(TAG, "FeedPojoPartnerId" + feedPojoPartnerGn.getId());
    Log.d(TAG, "FeedPojoPartnerImageurl" + feedPojoPartnerGn.getPhotoUrl());
    Log.d(TAG, "FeedPojoPartnerbuyUrl" + feedPojoPartnerGn.getVideoUrl());

Body:
implement Serializable

public class FeedPojo implements Serializable {
private static String id;
    private static String partnerId;
    private static String type;
    private static String name;
    private static String description;
    private static String start;
    private static String text;
    private static String photoUrl;
    private static String videoUrl;
    public FeedPojo(String id,String type,String name,String description,String start){

            this.setId(id);
            this.setType(type);
            this.setName(name);
            this.setDescription(description);
            this.setStart(start);
    }
public FeedPojo(String id,String text,String photoUrl,String videoUrl,String isNew){

        this.setId(id);
        this.setText(text);
        this.setPhotoUrl(photoUrl);
        this.setVideoUrl(videoUrl);
        this.setIsNew(isNew);

    }
}

then put data in bundle like this

 Bundle bundle = new Bundle();
  bundle.putSerializable("DATA", feedPojoNews);
  Intent intent = new
  Intent(MainActivity.this,SecondActivity.class);
  intent.putExtras(bundle);
  startActivity(intent);

In second Activity Extract data like this

Intent intent = this.getIntent();
 Bundle bundle = intent.getExtras();
 FeedPojo feedPojo= (FeedPojo ) bundle.getSerializable("DATA");


问:
why not quotation mark around period
I am beginner in Java. As I was going through the book, I got stuck on this problem. My question is why there are single quotes instead of double quotes around this period. When we want to print a string, we use double quotes.

答:
In Java, we use '' to delimit a char and "" to delimit a String.

In this particular case, you need a char because you are comparing '.' with the result of a call to the charAt method - which is always a char.  That is to say, sentence.charAt(lastCharPosition) has to be a char, so it can only be '.' and never ".".

If you wanted a String, (which you don't in this case), you could write ".".

Title: why not quotation mark around period


问:
how to get docker container to read from stdin?
I have a script that I want to use to use Sigil (based on Go's template engine) to populate template files

I'm using a dockerized sigil for this via:

```<code>docker run -v ${TEMPLATE_DIR}:/tmp/sigil mikegrass/gliderlabs_sigil-docker/sigil -f prometheus-configmap.yaml -p API_SERVER=$api_server_url > $TEMP_FILE
</code>```

This seems a bit clunky with having to map a volume, so I'd rather use STDIN to pass in the file....

So what I'd like is

```<code>cat ./prometheus-configmap.yaml | docker run mikegrass/gliderlabs_sigil-docker -p API_SERVER=$api_server_url > $TEMP_FILE
</code>```

Unfortunately this doesn't work, I get no output.

Googling around I see possible solutions but haven't gotten any to work...

答:
You need to run the container in interactive mode with --interactive or -i:

```<code>cat ./prometheus-configmap.yaml | docker run -i mikegrass/gliderlabs_sigil-docker -p API_SERVER=$api_server_url > $TEMP_FILE
</code>```

Body:
I have a script that I want to use to use Sigil (based on Go's template engine) to populate template files

I'm using a dockerized sigil for this via:

docker run -v ${TEMPLATE_DIR}:/tmp/sigil mikegrass/gliderlabs_sigil-docker/sigil -f prometheus-configmap.yaml -p API_SERVER=$api_server_url > $TEMP_FILE

This seems a bit clunky with having to map a volume, so I'd rather use STDIN to pass in the file....

So what I'd like is

cat ./prometheus-configmap.yaml | docker run mikegrass/gliderlabs_sigil-docker -p API_SERVER=$api_server_url > $TEMP_FILE

Unfortunately this doesn't work, I get no output.

Googling around I see possible solutions but haven't gotten any to work...

Body:
You need to run the container in interactive mode with --interactive or -i:

cat ./prometheus-configmap.yaml | docker run -i mikegrass/gliderlabs_sigil-docker -p API_SERVER=$api_server_url > $TEMP_FILE


问:
Swift 3 - FTP Upload
I have added the Rebekka touch framework to my Swift 3 project in order to upload files via FTP.

I have used the swift 3 conversion tool in xCode and I'm left with just one error

Value of type 'NSMutableData' has no member 'count'

And here's where it occurs:

```<code>let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.count)
</code>```

Full Function:

```<code>override func streamEventEnd(_ aStream: Stream) -> (Bool, NSError?) {
    var offset = 0
    let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.count)
    let totalBytes = CFIndex(self.inputData!.length)
    var parsedBytes = CFIndex(0)
    let entity = UnsafeMutablePointer<Unmanaged<CFDictionary>?>.allocate(capacity: 1)
    var resources = [ResourceItem]()
    repeat {
        parsedBytes = CFFTPCreateParsedResourceListing(nil, bytes.advancedBy(offset), totalBytes - offset, entity)
        if parsedBytes > 0 {
            let value = entity.pointee?.takeUnretainedValue()
            if let fptResource = value {
                resources.append(self.mapFTPResources(fptResource))
            }
            offset += parsedBytes
        }
    } while parsedBytes > 0
    self.resources = resources
    entity.deinitialize()
    return (true, nil)
}
</code>```

Does anybody know the swift 3 equivalent of self.inputData!.count ?

答:
I am using Swift3.
I did the following changes in the source code of Rebekka framework, specifically, the file ResourceListOperation.swift. (Note: advanced(by:..), .length).

```<code>fileprivate var inputData: NSMutableData?
var resources: [ResourceItem]?

override func streamEventEnd(_ aStream: Stream) -> (Bool, NSError?) {
    var offset = 0
    let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.length)
    let totalBytes = CFIndex(self.inputData!.length)
    var parsedBytes = CFIndex(0)
    let entity = UnsafeMutablePointer<Unmanaged<CFDictionary>?>.allocate(capacity: 1)
    var resources = [ResourceItem]()
    repeat {
        parsedBytes = CFFTPCreateParsedResourceListing(nil, bytes.advanced(by: offset), totalBytes - offset, entity)
        if parsedBytes > 0 {
            let value = entity.pointee?.takeUnretainedValue()
            if let fptResource = value {
                resources.append(self.mapFTPResources(fptResource))
            }
            offset += parsedBytes
        }
    } while parsedBytes > 0
    self.resources = resources
    entity.deinitialize()
    return (true, nil)
}
</code>```

Here is what I used in my application to list the directory after importing RebekkaTouch framework:

```<code>    var configuration = SessionConfiguration()
    configuration.host = "<ip-address:followed-by-port>"
    configuration.username = "uname"
    configuration.password = "password"
    configuration.encoding = String.Encoding.utf8
    self.session = Session(configuration: configuration)
    self.session.list("/") {
        (resources, error) -> Void in
        print("List directory with result:\n\(String(describing: resources)), error: \(String(describing: error))\n\n")
    }
</code>```

Title: Swift 3 - FTP Upload

Body:
I have added the Rebekka touch framework to my Swift 3 project in order to upload files via FTP.

I have used the swift 3 conversion tool in xCode and I'm left with just one error

Value of type 'NSMutableData' has no member 'count'

And here's where it occurs:

let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.count)

Full Function:

override func streamEventEnd(_ aStream: Stream) -> (Bool, NSError?) {
    var offset = 0
    let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.count)
    let totalBytes = CFIndex(self.inputData!.length)
    var parsedBytes = CFIndex(0)
    let entity = UnsafeMutablePointer<Unmanaged<CFDictionary>?>.allocate(capacity: 1)
    var resources = [ResourceItem]()
    repeat {
        parsedBytes = CFFTPCreateParsedResourceListing(nil, bytes.advancedBy(offset), totalBytes - offset, entity)
        if parsedBytes > 0 {
            let value = entity.pointee?.takeUnretainedValue()
            if let fptResource = value {
                resources.append(self.mapFTPResources(fptResource))
            }
            offset += parsedBytes
        }
    } while parsedBytes > 0
    self.resources = resources
    entity.deinitialize()
    return (true, nil)
}

Does anybody know the swift 3 equivalent of self.inputData!.count ?

Body:
I am using Swift3.
I did the following changes in the source code of Rebekka framework, specifically, the file ResourceListOperation.swift. (Note: advanced(by:..), .length).

fileprivate var inputData: NSMutableData?
var resources: [ResourceItem]?

override func streamEventEnd(_ aStream: Stream) -> (Bool, NSError?) {
    var offset = 0
    let bytes = self.inputData!.bytes.bindMemory(to: UInt8.self, capacity: self.inputData!.length)
    let totalBytes = CFIndex(self.inputData!.length)
    var parsedBytes = CFIndex(0)
    let entity = UnsafeMutablePointer<Unmanaged<CFDictionary>?>.allocate(capacity: 1)
    var resources = [ResourceItem]()
    repeat {
        parsedBytes = CFFTPCreateParsedResourceListing(nil, bytes.advanced(by: offset), totalBytes - offset, entity)
        if parsedBytes > 0 {
            let value = entity.pointee?.takeUnretainedValue()
            if let fptResource = value {
                resources.append(self.mapFTPResources(fptResource))
            }
            offset += parsedBytes
        }
    } while parsedBytes > 0
    self.resources = resources
    entity.deinitialize()
    return (true, nil)
}

Here is what I used in my application to list the directory after importing RebekkaTouch framework:

    var configuration = SessionConfiguration()
    configuration.host = "<ip-address:followed-by-port>"
    configuration.username = "uname"
    configuration.password = "password"
    configuration.encoding = String.Encoding.utf8
    self.session = Session(configuration: configuration)
    self.session.list("/") {
        (resources, error) -> Void in
        print("List directory with result:\n\(String(describing: resources)), error: \(String(describing: error))\n\n")
    }


问:
Applying synsets to pandas
This seems like such a simple question but I'd like to avoid looping if possible. I have the following data set in a panda column:

```<code>df['token']:
0     [If, you, can, only, visit, one, museum, in, N...
1     [Do, n't, let, the, neighborhood, ,, exterior,...
2     [Momofuku, Milk, Bar, is, one, of, those, plac...
3     [Have, you, been, here, ?, Tell, us, about, it...
4     [Add, the, Palmer, Trading, Company, to, your,...
5     [Porchetta, is, fast, and, simple, food, ., No...
</code>```

Name: token, dtype: object

I'd like to apply wordnet wordnet.synsets functional to each value in the list ( if, you, can etc) and only use the first result given back for example:

```<code> exterior [Synset('outside.n.01'), Synset('outside.n.02'), Synset('exterior.a.01')]
</code>```

I'd like to be able to use apply to use only the first result: Synset('outside.n.01')

答:
From your comments, I think what you are looking for is a way to replace each of the words with the first result from calling synsets on the word, Is that correct?  You just need a function that wraps synsets that accepts a list of words, and returns the first element of what synset returns for each one of those:

```<code>def first(wordlist):
    # wordlist is a list of words, i.e. ['sun', 'shine', 'spotless']
    return [synsets(word)[0] for word in wordlist]
</code>```

Then use applymap to run it on each element of the DataFrame:

```<code>df.applymap(first)
</code>```

Is that what you're trying to do?

Title: Applying synsets to pandas

Body:
This seems like such a simple question but I'd like to avoid looping if possible. I have the following data set in a panda column:

df['token']:
0     [If, you, can, only, visit, one, museum, in, N...
1     [Do, n't, let, the, neighborhood, ,, exterior,...
2     [Momofuku, Milk, Bar, is, one, of, those, plac...
3     [Have, you, been, here, ?, Tell, us, about, it...
4     [Add, the, Palmer, Trading, Company, to, your,...
5     [Porchetta, is, fast, and, simple, food, ., No...

Name: token, dtype: object

I'd like to apply wordnet wordnet.synsets functional to each value in the list ( if, you, can etc) and only use the first result given back for example:

 exterior [Synset('outside.n.01'), Synset('outside.n.02'), Synset('exterior.a.01')]

I'd like to be able to use apply to use only the first result: Synset('outside.n.01')

Body:
From your comments, I think what you are looking for is a way to replace each of the words with the first result from calling synsets on the word, Is that correct?  You just need a function that wraps synsets that accepts a list of words, and returns the first element of what synset returns for each one of those:

def first(wordlist):
    # wordlist is a list of words, i.e. ['sun', 'shine', 'spotless']
    return [synsets(word)[0] for word in wordlist]

Then use applymap to run it on each element of the DataFrame:

df.applymap(first)

Is that what you're trying to do?


问:
Simple Nested For Loop
I'm trying to paste "Area1" 50 times, and "Area2" 50 time right below "Area1" in the same column. My codes run the first 50 times, and replace the first 50 rows when running Area=2. How do I make "Area2" start on a new row, under "Area1"? Thank you :))</p>

```<code>For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area
</code>```

答:
There are many ways to do this.  A few of them would be:

```<code>For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells((Area - 1) * 50 + Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area
</code>```

or

```<code>For Area = 1 To 2
    For Row = (Area - 1) * 50 + 1 To (Area - 1) * 50 + 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area
</code>```

or changing Area to be zero-based

```<code>For Area = 0 To 1
    For Row = 1 To 50
        Sheets("A").Cells(Area * 50 + Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area
</code>```

or avoiding loops

```<code>Sheets("A").Cells(1, 2).Resize(50, 1) = Sheets("A").Cells(2, 31)
Sheets("A").Cells(51, 2).Resize(50, 1) = Sheets("A").Cells(2, 31)
</code>```

or, because you are copying the same value to the destination cells, simply

```<code>Sheets("A").Cells(1, 2).Resize(100, 1) = Sheets("A").Cells(2, 31)
</code>```

Title: Simple Nested For Loop

Body:
I'm trying to paste "Area1" 50 times, and "Area2" 50 time right below "Area1" in the same column. My codes run the first 50 times, and replace the first 50 rows when running Area=2. How do I make "Area2" start on a new row, under "Area1"? Thank you :))

For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area

Body:
There are many ways to do this.  A few of them would be:

For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells((Area - 1) * 50 + Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area

or

For Area = 1 To 2
    For Row = (Area - 1) * 50 + 1 To (Area - 1) * 50 + 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area

or changing Area to be zero-based

For Area = 0 To 1
    For Row = 1 To 50
        Sheets("A").Cells(Area * 50 + Row, 2) = Sheets("A").Cells(2, 31)
    Next Row
Next Area

or avoiding loops

Sheets("A").Cells(1, 2).Resize(50, 1) = Sheets("A").Cells(2, 31)
Sheets("A").Cells(51, 2).Resize(50, 1) = Sheets("A").Cells(2, 31)

or, because you are copying the same value to the destination cells, simply

Sheets("A").Cells(1, 2).Resize(100, 1) = Sheets("A").Cells(2, 31)


问:
Android: how to shift a Bitmap?
I would like to "shift" a Bitmap by a certain x and y offset.  By shift, I mean, If I have a 300x500 bitmap, and I shift it by a y offset of -50, I would expect every pixel to move up 50 pixels, and a 300x50 pixel rectangle to be blank, along the bottom of the Bitmap.  The below code works great if shiftX and shiftY are negative, but doesn't work at all for positive values.  I have no idea why?

```<code>Rect srcRect = new Rect(-shiftX, -shiftY, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(shiftX, shiftY);

Canvas bitmapCanvas = new Canvas(mBitmap);
bitmapCanvas.drawBitmap(mBitmap, srcRect, destRect, null);
</code>```

I've tried many different versions of this.  It seems that trying to translate a Bitmap with a positive y always produces garbage.  In this simpler example, a negative shiftY gives expected behavior, but a positive shiftY gives a garbage result:

```<code> Canvas bitmapCanvas = new Canvas(mBitmap);
 bitmapCanvas.drawBitmap(mBitmap, 0, shiftY, null);
</code>```

*Update. This is solved by the below code.  However, this is not memory efficient.  Any suggestions for a better solution?

```<code>Canvas bitmapCanvas = new Canvas(mBitmap);
Bitmap tempBitmap = mBitmap.copy(CONFIG.ARGB_8888, false);
bitmapCanvas.drawBitmap(tempBitmap, 0, shiftY, null);
</code>```

答:
I can't reproduce this with your code.
I have tried it with an offset of 50 and -50 and both works as expected.

My code inside the drawing method:

```<code>// negative value: -50
Rect srcRect = new Rect(-(-50), -(-50), mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(-50, -50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);
</code>```

or with positive:

```<code>// positive value: 50
Rect srcRect = new Rect(-50, -50, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(50, 50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);
</code>```

Title: Android: how to shift a Bitmap?

Body:
I would like to "shift" a Bitmap by a certain x and y offset.  By shift, I mean, If I have a 300x500 bitmap, and I shift it by a y offset of -50, I would expect every pixel to move up 50 pixels, and a 300x50 pixel rectangle to be blank, along the bottom of the Bitmap.  The below code works great if shiftX and shiftY are negative, but doesn't work at all for positive values.  I have no idea why?

Rect srcRect = new Rect(-shiftX, -shiftY, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(shiftX, shiftY);

Canvas bitmapCanvas = new Canvas(mBitmap);
bitmapCanvas.drawBitmap(mBitmap, srcRect, destRect, null);

I've tried many different versions of this.  It seems that trying to translate a Bitmap with a positive y always produces garbage.  In this simpler example, a negative shiftY gives expected behavior, but a positive shiftY gives a garbage result:

 Canvas bitmapCanvas = new Canvas(mBitmap);
 bitmapCanvas.drawBitmap(mBitmap, 0, shiftY, null);

*Update. This is solved by the below code.  However, this is not memory efficient.  Any suggestions for a better solution?

Canvas bitmapCanvas = new Canvas(mBitmap);
Bitmap tempBitmap = mBitmap.copy(CONFIG.ARGB_8888, false);
bitmapCanvas.drawBitmap(tempBitmap, 0, shiftY, null);

Body:
I can't reproduce this with your code.
I have tried it with an offset of 50 and -50 and both works as expected.

My code inside the drawing method:

// negative value: -50
Rect srcRect = new Rect(-(-50), -(-50), mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(-50, -50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);

or with positive:

// positive value: 50
Rect srcRect = new Rect(-50, -50, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(50, 50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);


问:
How to check if a string value is in a correct time format?
Is there a possibility to check wether a string is in a valid time format or not?</p>

```<code>Examples:
12:33:25 --> valid
03:04:05 --> valid
3:4:5    --> valid
25:60:60 --> invalid
</code>```

答:
If you didn't want to write methods, you could always check and see if converts successfully.  If needed you can use a bool to show whether or not it was valid.</p>

```<code>bool passed = false;
string s = String.Empty;
DateTime dt;
try{
     s = input; //Whatever you are getting the time from
     dt = Convert.ToDateTime(s);
     s = dt.ToString("HH:mm"); //if you want 12 hour time  ToString("hh:mm")
     passed = true;
}
catch(Exception ex)
{

}
</code>```

Body:
Is there a possibility to check wether a string is in a valid time format or not?

Examples:
12:33:25 --> valid
03:04:05 --> valid
3:4:5    --> valid
25:60:60 --> invalid

Body:
If you didn't want to write methods, you could always check and see if converts successfully.  If needed you can use a bool to show whether or not it was valid.

bool passed = false;
string s = String.Empty;
DateTime dt;
try{
     s = input; //Whatever you are getting the time from
     dt = Convert.ToDateTime(s);
     s = dt.ToString("HH:mm"); //if you want 12 hour time  ToString("hh:mm")
     passed = true;
}
catch(Exception ex)
{

}


问:
Need help improving the architecture of a functional command system
Given a set of commands whose Execute() method can be called concurrently, is there a way to unit test the command classes to ensure that other maintainers of the code don't add member data (other than readonly members passed to the constructor)?

Example:
When the code starts, create a mapping between scripted actions and commands that can service the action:

```<code>actionCommandTable =
[“Translate”, new TranslateCommand(appcontext)],
[“Scale”, new ScaleCommand(appcontext)],
[“Assignment” new AssignmentCommand(appcontext, expressionEvaluator)]
</code>```

Then at runtime:

```<code>actionCommandTable[“Translate”].Execute(actionDataContext);
</code>```

The translate command:

```<code>public class TranslateAction : ActionCommand {
        //read-only interface
        private readonly AliasProvider aliasMap;
        //bad - need to prevent this instance from being added - will be overwritten unexpectedly
        private int transientValue;
        public TranslateAction(IAppContext appContext) {
            aliasMap = appContext.AliasMap;
        }
        public override async Task Execute(ActionDataContext actionDataContext) {
            //assign to transientValue
            //do some work
            //await an animation
            //do more work
            //read from transientValue
        }

    }
</code>```

In this example, all the work in Execute is ok if it doesn't work on shared members.

actionDataContext is intended to be the target of transient statefull data.

答:
You can use reflection to ensure all fields and properties are read only. However for validating if assignments are correct, you may have to validate command value assignment based on your requirement

```<code>    public void ValidateAllFieldsAreInitOnly(Type sut)
    {
        foreach(var field in sut.GetFields(BindingFlags.NonPublic |
                                     BindingFlags.Instance |
                                     BindingFlags.Static |
                                     BindingFlags.Public))
        {
            Assert.IsTrue(field.IsInitOnly);
        }

        foreach (var property in sut.GetProperties(BindingFlags.NonPublic |
                                     BindingFlags.Instance |
                                     BindingFlags.Static |
                                     BindingFlags.Public))
        {
            // returns true if the property has a set accessor, even if the accessor is private, internal
            Assert.IsFalse(property.CanWrite);

            // OR can use depending on requirement

            // The MethodInfo object representing the Set method for this property if the set accessor is public, or null if the set accessor is not public.
            Assert.IsNull(property.GetSetMethod());
        }
    }
</code>```

Note this will not catch scenarios when someone declare property as read only however initialize it in wrong manner ex -

Test will be green for

```<code>public class GoodCommand
{

    private readonly string privateField1;

    private readonly string privateField2;
    public GoodCommand(string field1, string field2)
    {
        privateField1 = field1;
        privateField2 = field2;
    }
}
</code>```

Test will catch (red)

```<code>public class BadCommand
{

    private readonly string privateField1;

    private string privateField2;
    public BadCommand(string field1)
    {
        privateField1 = field1;
        privateField2 = "testingbadCommand";
    }
}
</code>```

For this case test is green because proper assignment checking may vary based on requirement. You can catch this scenario also by validating if value assigned is as expected.

```<code>public class SmartBadCommand
{
    private readonly string privateField1;

    private readonly string privateField2;
    public SmartBadCommand(string field1)
    {
        privateField1 = field1;
        privateField2 = "testingbadCommand";
    }
}
</code>```

Hope this help.

Body:
Given a set of commands whose Execute() method can be called concurrently, is there a way to unit test the command classes to ensure that other maintainers of the code don't add member data (other than readonly members passed to the constructor)?

Example:
When the code starts, create a mapping between scripted actions and commands that can service the action:

actionCommandTable =
[“Translate”, new TranslateCommand(appcontext)],
[“Scale”, new ScaleCommand(appcontext)],
[“Assignment” new AssignmentCommand(appcontext, expressionEvaluator)]

Then at runtime:

actionCommandTable[“Translate”].Execute(actionDataContext);

The translate command:

public class TranslateAction : ActionCommand {
        //read-only interface
        private readonly AliasProvider aliasMap;
        //bad - need to prevent this instance from being added - will be overwritten unexpectedly
        private int transientValue;
        public TranslateAction(IAppContext appContext) {
            aliasMap = appContext.AliasMap;
        }
        public override async Task Execute(ActionDataContext actionDataContext) {
            //assign to transientValue
            //do some work
            //await an animation
            //do more work
            //read from transientValue
        }

    }

In this example, all the work in Execute is ok if it doesn't work on shared members.

actionDataContext is intended to be the target of transient statefull data.

Body:
You can use reflection to ensure all fields and properties are read only. However for validating if assignments are correct, you may have to validate command value assignment based on your requirement

    public void ValidateAllFieldsAreInitOnly(Type sut)
    {
        foreach(var field in sut.GetFields(BindingFlags.NonPublic |
                                     BindingFlags.Instance |
                                     BindingFlags.Static |
                                     BindingFlags.Public))
        {
            Assert.IsTrue(field.IsInitOnly);
        }

        foreach (var property in sut.GetProperties(BindingFlags.NonPublic |
                                     BindingFlags.Instance |
                                     BindingFlags.Static |
                                     BindingFlags.Public))
        {
            // returns true if the property has a set accessor, even if the accessor is private, internal
            Assert.IsFalse(property.CanWrite);

            // OR can use depending on requirement

            // The MethodInfo object representing the Set method for this property if the set accessor is public, or null if the set accessor is not public.
            Assert.IsNull(property.GetSetMethod());
        }
    }

Note this will not catch scenarios when someone declare property as read only however initialize it in wrong manner ex -

Test will be green for

public class GoodCommand
{

    private readonly string privateField1;

    private readonly string privateField2;
    public GoodCommand(string field1, string field2)
    {
        privateField1 = field1;
        privateField2 = field2;
    }
}

Test will catch (red)

public class BadCommand
{

    private readonly string privateField1;

    private string privateField2;
    public BadCommand(string field1)
    {
        privateField1 = field1;
        privateField2 = "testingbadCommand";
    }
}

For this case test is green because proper assignment checking may vary based on requirement. You can catch this scenario also by validating if value assigned is as expected.

public class SmartBadCommand
{
    private readonly string privateField1;

    private readonly string privateField2;
    public SmartBadCommand(string field1)
    {
        privateField1 = field1;
        privateField2 = "testingbadCommand";
    }
}

Hope this help.


问:
Number goes wrong in to database in PHP
I have a situation where I have to add a phone number to the database.
If I enter number something like: 868150705 It goes OK to database
If I enter something like this: 3706150705 It goes to database with value 2147483647

With this input I take the value out of form

```<code><input type="text" class="demoInputBox" maxlength="20" name="telefonas" value="<?php if(isset($info['tel_nr'])) echo $info['tel_nr']; ?>">
</code>```

And with this query I put it into database (I have the $username)

```<code>$telnr = $_POST['telefonas'];
$db_handle = new mysqli("localhost", "root", "xxx", "Database");
$query = "UPDATE table SET tel_nr = '$telnr' WHERE username = '$username'";
$result = $db_handle->query($query);
</code>```

My field tel_nr has the below format:

tel_nr   int(20)

Can you help me with this strange magic? Btw I know this code is unsafe but the project isn't live at the moment. Just test things.

答:
You're trying to put integer greater than int limit to the database. I'd suggest using VARCHAR for this (phone number isn't integer anyway - consider something like +420 730 500 600). Also, you are not escaping the data you get before trying to put it in the database, so it is vulnerable to SQL injection.

Hope this helps you, comment if you have any questions

Title: Number goes wrong in to database in PHP

Body:
I have a situation where I have to add a phone number to the database.
If I enter number something like: 868150705 It goes OK to database
If I enter something like this: 3706150705 It goes to database with value 2147483647

With this input I take the value out of form

<input type="text" class="demoInputBox" maxlength="20" name="telefonas" value="<?php if(isset($info['tel_nr'])) echo $info['tel_nr']; ?>">

And with this query I put it into database (I have the $username)

$telnr = $_POST['telefonas'];
$db_handle = new mysqli("localhost", "root", "xxx", "Database");
$query = "UPDATE table SET tel_nr = '$telnr' WHERE username = '$username'";
$result = $db_handle->query($query);

My field tel_nr has the below format:

tel_nr   int(20)

Can you help me with this strange magic? Btw I know this code is unsafe but the project isn't live at the moment. Just test things.


问:
Error(1,1)illegalcharacter '\ufeff' when compiling on android studio
I got an Eclipse project source code(I was told that on Android Studio, maybe they just confused), and I start to migrating the code to android studio refers to

http://developer.android.com/sdk/installing/migrate.html

But it doesn't work.
so I import the project from path directly and it transfers to the android-studio project automatically, but still, something wrong when I am compiling.

Error:(1, 1) error: illegalcharacter: '\ufeff'

the error position refers to

package com.bla.blabla;

Please help me, thanks

答: Close android studio and reopen it. It works for me. Furthermore this could happen if you are copying a comment from youtube for example and pasting it into your project</p>


问:
$_SERVER['PHP_SELF'] intermittently returning two leading forward slashes
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

```<code>header ('Location: test/foo.bar')
</code>```

foo.bar includes:

```<code>$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
</code>```

(Additionally, I cannot replicate it on demand. )

答: You could try using $_SERVER['SCRIPT_NAME'].  Take note that PHP_SELF is vulnerable to a few types of attack, so be careful when using it.  You have to treat it as if it was user supplied input.</p>

Body:
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

header ('Location: test/foo.bar')

foo.bar includes:

$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);

(Additionally, I cannot replicate it on demand. )


问:
How can I convert VRLM files to 3D PDF ? (python or freeware)
I would take an answer for either way, either using Python libraries or a freeware utility.
I have come across U3D-2-PDF but it seems that the project was abandoned and follow the instructions did not work (receiving an error)</p>

答: It is not free, but you can get a free trial at Tetra4d.com for their Converter tool. You can convert all major CAD formats to 3D PDF. </p>


问:
Why Python tries to compute some calculations in multiprocessing in advance
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

```<code>import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')
</code>```

Now if I print some low power of 10 in each function:

```<code>print(5 ** 10000000)
</code>```

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does

答: The peephole optimizer is trying to constant-fold the 5**10000000000 calculation. This happens before any worker processes launch.

Body:
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')

Now if I print some low power of 10 in each function:

print(5 ** 10000000)

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does


问:
Computational Efficiency of Forward Mode Automatic vs Numeric vs Symbolic Differentiation
I am trying to solve a problem of finding the roots of a function using the Newton-Raphson (NR) method in the C language. The functions in which I would like to find the roots are mostly polynomial functions but may also contain trigonometric and logarithmic.

The NR method requires finding the differential of the function. There are 3 ways to implement differentiation:

Symbolic

Numerical

Automatic (with sub types being forward mode and reverse mode. For this particular question, I would like to focus on forward mode)

I have thousands of these functions all requiring finding roots in the quickest time possible.

From the little that I do know, Automatic differentiation is in general quicker than symbolic because it handles the problem of "expression swell" alot more efficiently.

My question therefore is, all other things being equal, which method of differentiation is more computationally efficient: Automatic Differentiation (and more specifically, forward mode) or Numeric differentiation?

答: If your functions are truly all polynomials, then symbolic derivatives are dirt simple. Letting the coefficients of the polynomial be stored in an array with entries p[k] = a_k, where index k corresponds to the coefficient of x^k, then the derivative is represented by the array with entries dp[k] = (k+1) p[k+1]. For multivariable polynomial, this extends straightforwardly to multidimensional arrays. If your polynomials are not in standard form, e.g. if they include terms like (x-a)^2 or ((x-a)^2-b)^3 or whatever, a little bit of work is needed to transform them into standard form, but this is something you probably should be doing anyways.


问:
How to export acquisition channel from GA?
I use Google Analytics to track an acquisition channel for android and ios users. How can I export a list of users with user's ID and acquisition channel? Programmatically via Query explorer or manual exporting alternatives are welcome.
I can export a list of users without acquisition channel field in User Explorer. But this field is presented on detailed page.</p>

答:
The one of the possible ways is

1. Create a custom dimension in GA to store User ID. User ID might be your own generated key of user.

2. Sending this User ID to GA from your mobile app.

3. Build a query to selecting needed information in GA reporting.

More information here https://www.mugo.ca/Blog/Tracking-individual-users-in-Google-Analytics


答:
I would recommend switching to a BIGINT for the tel_nr since it is 64bit by default and int is 32 bit (2147483647=2^31-1). the 20 in INT(20) specifies the number of characters mysql displays so in your case with zero fill on it would display 2147483647 preceded by 10 zeros

UPDATE:
found where i had read it
https://stackoverflow.com/a/4769436/6054257

Title: Number goes wrong in to database in PHP


问:
Infopath form loading error
we have migrated a site from sharepoint 2010 to office365. I had a infopath form previously now the form in office365 is giving me a loading error.Can anyone help me thanks in advance</p>

答: What is the error you are getting? I know our issue was in a SP List where we had a dropdown item that was still pointing to the old SP and a rule on form load to query this old SP List and wouldnt open. I had to create a Find and replace powershell command to overcome this. If this sounds the same as what you are finding let me know and I will respond with a detailed how to!</p>

Title: Infopath form loading error


问:
Excel VBA: Convert Cells to Range using Address
I am building a module to import text into an Excel workbook. After it imports, I want to format the data as a table. The problem I have is that the import will never have the same range.

I'm using the following code, but it throws an error, Run-time error '424': Object required.

```<code>Sub ImportRange()

  Dim ws As Worksheet
  Dim lRow As Long
  Dim lCol As Long
  Dim rng As Range

  Set ws = ThisWorkbook.Worksheets("Import")

  lRow = ws.UsedRange.Row - 1 + ws.UsedRange.Rows.Count
  lCol = ws.UsedRange.Column - 1 + ws.UsedRange.Columns.Count

  Set rng = ws.Cells(lRow, lCol).Address(True, True)

  'MsgBox Cells(lRow, lCol).Address(True, True)

End Sub
</code>```

I've done quite a bit of searching, but I have been unable to find an answer or figure out how I should be doing this.

The end result would look something like this in the code with the start of the range always being set to $A$1:

```<code>ws.ListObjects.Add(xlSrcRange, Range("$A$1:$AM$90"), , xlYes).Name = _
    "Import"
</code>```

答:
If your goal is to set a range to the used range on a sheet, it can be done simpler:

```<code>Set rng = ws.UsedRange
</code>```

Obviously, you need to make sure that the usedrange on that sheet properly represents your imported data.

To convert the range to a table:

```<code>Dim Import_Table As ListObject
Set Import_Table = ws.ListObjects.Add(SourceType:=xlSrcRange, Source:=rng, XlListObjectHasHeaders:=xlYes)
Import_Table.Name = "Import"
</code>```

Note: the code is for Excel 2010. For later versions, replace XlListObjectHasHeaders with HasHeaders

Body:
I am building a module to import text into an Excel workbook. After it imports, I want to format the data as a table. The problem I have is that the import will never have the same range.

I'm using the following code, but it throws an error, Run-time error '424': Object required.

Sub ImportRange()

  Dim ws As Worksheet
  Dim lRow As Long
  Dim lCol As Long
  Dim rng As Range

  Set ws = ThisWorkbook.Worksheets("Import")

  lRow = ws.UsedRange.Row - 1 + ws.UsedRange.Rows.Count
  lCol = ws.UsedRange.Column - 1 + ws.UsedRange.Columns.Count

  Set rng = ws.Cells(lRow, lCol).Address(True, True)

  'MsgBox Cells(lRow, lCol).Address(True, True)

End Sub

I've done quite a bit of searching, but I have been unable to find an answer or figure out how I should be doing this.

The end result would look something like this in the code with the start of the range always being set to $A$1:

ws.ListObjects.Add(xlSrcRange, Range("$A$1:$AM$90"), , xlYes).Name = _
    "Import"

Body:
If your goal is to set a range to the used range on a sheet, it can be done simpler:

Set rng = ws.UsedRange

Obviously, you need to make sure that the usedrange on that sheet properly represents your imported data.

To convert the range to a table:

Dim Import_Table As ListObject
Set Import_Table = ws.ListObjects.Add(SourceType:=xlSrcRange, Source:=rng, XlListObjectHasHeaders:=xlYes)
Import_Table.Name = "Import"

Note: the code is for Excel 2010. For later versions, replace XlListObjectHasHeaders with HasHeaders


问:
Bayesian networks tutorial
For a beginner, which is the best book to start with for studying Bayesian Networks? </p>

答: I would recommend "Probabilistic Graphical Models" by Daphne Koller and Nir Friedman. Its an excellent starter-to-intermediate handbook on both directed (Bayesian Networks) and undirected (Markov Networks) graphical models. The examples given are elaborate and easy to understand.</p>

Title: Bayesian networks tutorial

LastEditorDisplayName: Dima


问:
Python 3: How to write to the same file from multiple processes without messing it up?
I have a program that can be started or stopped at any moment. The program is used to download data from web pages. First, a user will define a bunch of web pages in a .csv file, then save that .csv file, then start the program. That program will read the .csv file and turn it into a list of jobs. Next, the jobs are split among 5 separate downloader functions that work in parallel but may take different times to download.

After a downloader (which there are 5 of) finished downloading a web page, I need it to open the .csv file and remove the link. This way, as time passes, the .csv file will get smaller and smaller. The issue is that sometimes two download functions will try to update the .csv file at the same time and will cause the program to crash. How can I deal with this?

答:
Look into locking files in python. Locking a file will make the next process wait until the file is unlocked to modify it. Locking files is platform specific so you will have to use whichever method works for the os you are on. If you need to figure out the os use a switch statement like this.

```<code>import os

def my_lock(f):
    if os.name == "posix":
        # Unix or OS X specific locking here
    elif os.name == "nt":
        # Windows specific locking here
    else:
        print "Unknown operating system, lock unavailable"
</code>```

Then I would look at this article  and figure out exactly how you want to implement your lock.

Body:
Look into locking files in python. Locking a file will make the next process wait until the file is unlocked to modify it. Locking files is platform specific so you will have to use whichever method works for the os you are on. If you need to figure out the os use a switch statement like this.

import os

def my_lock(f):
    if os.name == "posix":
        # Unix or OS X specific locking here
    elif os.name == "nt":
        # Windows specific locking here
    else:
        print "Unknown operating system, lock unavailable"

Then I would look at this article  and figure out exactly how you want to implement your lock.


问:
document.cookie returns only PHPSESSID=*random number*
I'm trying to get a cookie I have set but all I'm getting is the PHPSESSID.

I set my cookie in a separate PHP page with:

```<code>setcookie("username", $sentname, time()+(60*60*24*30),NULL,NULL,NULL,false);
</code>```

I can then find it through firefox settings.

When I try to access it using JavaScript on a different page I use:

```<code><script>

        $(document).ready(function(){
        var cookie = document.cookie;

        alert(cookie);
        });

</script>
</code>```

which then returns:

```<code>PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4
</code>```

It should return all the cookies, only "username" so far, I have set in a key paired string. I tried using the jquery plugin for cookies and it returned the same thing. I also couldn't find this problem elsewhere online.

答:
Not sure if I should delete the question but one of the related links gave me the answer.

The cookie path must be set to '/' to be accessible from all subdomains. so I changed it too:

```<code>setcookie("username", $sentname, time()+(60*60*24*30),'/',NULL,NULL,false);
</code>```

which gives me:

```<code>PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4; username=asdf
</code>```

Body:
I'm trying to get a cookie I have set but all I'm getting is the PHPSESSID.

I set my cookie in a separate PHP page with:

setcookie("username", $sentname, time()+(60*60*24*30),NULL,NULL,NULL,false);

I can then find it through firefox settings.

When I try to access it using JavaScript on a different page I use:

which then returns:

PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4

It should return all the cookies, only "username" so far, I have set in a key paired string. I tried using the jquery plugin for cookies and it returned the same thing. I also couldn't find this problem elsewhere online.

Body:
Not sure if I should delete the question but one of the related links gave me the answer.

The cookie path must be set to '/' to be accessible from all subdomains. so I changed it too:

setcookie("username", $sentname, time()+(60*60*24*30),'/',NULL,NULL,false);

which gives me:

PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4; username=asdf


问:
How add list<object> with NpgsqlDataReader() C#
I do not know what I am doing wrong, when I add the values from my database to a list<object> it always returns the list with the total of objects but all the values are those of the last record that was made in the loop while.

This is my code:

```<code>public List<object> getdata(string storedProcedure)
    {
        List<object> list = new List<object>();
        try
        {
            using (var conn = new NpgsqlConnection(connstring))
            {
                conn.Open();
                NpgsqlTransaction tran = conn.BeginTransaction();
                NpgsqlDataReader reader;
                var cmd = new NpgsqlCommand(storedProcedure, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                reader = cmd.ExecuteReader();

                int fieldCount = reader.FieldCount;
                object[] fieldValues = new object[fieldCount];
                while (reader.Read())
                {
                    int instances = reader.GetValues(fieldValues);
                    for (int fieldCounter = 0; fieldCounter < fieldCount; fieldCounter++)
                    {
                        if (Convert.IsDBNull(fieldValues[fieldCounter]))
                            fieldValues[fieldCounter] = "NA";
                    }
                    list.Add(fieldValues);
                }
                reader.Close();
                tran.Commit();
                conn.Close();
                return list;
            }
        }
        catch (Exception ex)
        {
        }
        return list;
    }
</code>```

This is what I get in all positions, it is the last value:

答:
You need to move the declaration and initialization of your object array inside the loop

```<code>  ....
  while (reader.Read())
  {
      object[] fieldValues = new object[fieldCount];
      ....
  }
</code>```

The problem that you experience is caused by the fact that when you initialize the array outside the loop and reuse it at every loop of the datareader, you replace the previous content with the content of the current record.

But when you add the array to the list of objects you add the same reference to initial array where only the content has been changed. Obviously when you reach the last record there is only one array while the list contains n reference to the same memory area. So you display n time the same last record.

Moving the initialization inside the loop provides the list with a new reference at each loop and each reference maintain the data of the record received during the loop.

Body:
I do not know what I am doing wrong, when I add the values from my database to a list<object> it always returns the list with the total of objects but all the values are those of the last record that was made in the loop while.

This is my code:

public List<object> getdata(string storedProcedure)
    {
        List<object> list = new List<object>();
        try
        {
            using (var conn = new NpgsqlConnection(connstring))
            {
                conn.Open();
                NpgsqlTransaction tran = conn.BeginTransaction();
                NpgsqlDataReader reader;
                var cmd = new NpgsqlCommand(storedProcedure, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                reader = cmd.ExecuteReader();

                int fieldCount = reader.FieldCount;
                object[] fieldValues = new object[fieldCount];
                while (reader.Read())
                {
                    int instances = reader.GetValues(fieldValues);
                    for (int fieldCounter = 0; fieldCounter < fieldCount; fieldCounter++)
                    {
                        if (Convert.IsDBNull(fieldValues[fieldCounter]))
                            fieldValues[fieldCounter] = "NA";
                    }
                    list.Add(fieldValues);
                }
                reader.Close();
                tran.Commit();
                conn.Close();
                return list;
            }
        }
        catch (Exception ex)
        {
        }
        return list;
    }

This is what I get in all positions, it is the last value:

Body:
You need to move the declaration and initialization of your object array inside the loop

  ....
  while (reader.Read())
  {
      object[] fieldValues = new object[fieldCount];
      ....
  }

The problem that you experience is caused by the fact that when you initialize the array outside the loop and reuse it at every loop of the datareader, you replace the previous content with the content of the current record.

But when you add the array to the list of objects you add the same reference to initial array where only the content has been changed. Obviously when you reach the last record there is only one array while the list contains n reference to the same memory area. So you display n time the same last record.

Moving the initialization inside the loop provides the list with a new reference at each loop and each reference maintain the data of the record received during the loop.


问:
Unable to Creating Work Profile (Profile owner) in Some Android 5.0+ devices?
I am facing one problem and i am not getting solution on internet. My problem is- in some devices like samsung and motorola which have android 5.0+ version i am unable to create work profile(TestDPC app on playstore). What's the reason please if anybody know explain it please.
This is the code checked by android at time of work profile creation-

```<code>  PackageManager pm=getPackageManager();
    System.out.println(" can create profile="+ pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));
</code>```

Is There an option to change that thing so that i can create a work profile in every device.

Thank you

答:
There could be multiple reasons why a phone with Android 5.0+ would not support work profiles. The most common reason is too little ram. Google recommends a minimum of 1.5 GB of ram to support work profiles, but less ram may still work just with performance degradation.

I don't believe there is a work around for your situation, other than re-compiling the OS adding at a minimum the hardware feature android.software.managed_users. But obtaining the source may be difficult for a Motorola or Samsung phone.

In addition, the phone must not be configured as a low RAM device, i.e. ro.config.low_ram. And if only one user is supported, Google provides additional patches to support a managed profile for that single user. Google has much more detailed documentation for OEMs to implement an Android for Work device.

Body:
I am facing one problem and i am not getting solution on internet. My problem is- in some devices like samsung and motorola which have android 5.0+ version i am unable to create work profile(TestDPC app on playstore). What's the reason please if anybody know explain it please.
This is the code checked by android at time of work profile creation-

  PackageManager pm=getPackageManager();
    System.out.println(" can create profile="+ pm.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));

Is There an option to change that thing so that i can create a work profile in every device.

Thank you


问:
How to run a graph algorithm concurrently in Java using multi-core parallelism
I want to run an algorithm on large graphs concurrently, using multi-core parallelism. I have been working on it for a while, but haven't been able to come up with a good solution.

This is the naive algorithm:

```<code>W - a very large number
double weight = 0

while(weight < W)

    - v : get_random_node_from(Graph)

    - weight += calculate(v)
</code>```

I looked into fork-and-join, but can't figure out a way to divide this problem into smaller subproblems.

Then I tried using Java 8 streams, for which I need to create a lambda expression. When I tried doing something like this:

double weight = 0
Callable<Object> task = () -> {
    can not update weight here, as it needs to be final
}

My question is, is it possible to update a variable like weight in a lambda method? Or is there a better way in which this problem can be solved?

The closest I have got is by using ExecutorService, but run into the problems of synchronization.

------------EDIT--------------

Here is the detailed algorithm:

In a nutshell, what I am trying to do, is traverse a massive graph, perform an operation on randomly selected nodes(as long as weight < W) and update a global structure Index.

This is taking too long as it doesn't utilize the full power of the CPU.

Ideally, all threads/processes on multiple cores would perform the operations on the randomly selected nodes, and update the shared weight and Index.

Note: It doesn't matter if different threads pick up the same node, as it's random without replacement.

Algorithm:

function Serial () {

```<code>List<List<Integer>> I (shared data structure which I want to update)
double weight

//// Task which I want to parallelize

while(weight < W) {

    v : get_random_node_from(Graph)

    bfs(v, affected_nodes) ...// this will fill up affected_nodes by v

    foreach(affected_node in affected_nodes) {

         // update I related to affected_node
         // and do other computation
    }

    weight += affected_nodes.size()

}

///////// Parallelization ends here

use_index(I) // I is passed now to some other method(not important) to get further results

}
</code>```

The important thing is, all threads update the same I and weight.

Thanks.

答:
Well you could wrap that weight into an array of a single element, it's sort of a know trick for this kind of stuff; even done internally by java, like this:

```<code>weight[0] = weight[0] + calculate(v);
</code>```

But there are problems with this, since you are going to run it in parallel. You will not get the result you want since weight[0] is not thread-safe. And you could use some sort of synchronization, but java already has a great solution for that : DoubleAdder that scales far better in contended environments (and multiple cpus).

A trivial and small example:

```<code>DoubleAdder weight = new DoubleAdder();

private static int calculate(int v) {
    return v + 1;
}

Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
            .parallel()
            .forEach(x -> {
                int y = calculate(x);
                weight.add(y);
            });

System.out.println(weight); // 54
</code>```

Then there is the problem of the randomizer that you are going to choose for this: get_random_node_from(Graph). You need to get a random Node indeed, but at the same time you need to get all of them exactly once.
But you might not need it if you can flatten all the nodes into a single List let's say.

The problem here is that Graphs are usually traversed in a recursive way, you don't know the exact size of it:

```<code>while(parent.hasChildren) {
     traverse children and so on...
}
</code>```

This will parallelize bad under Streams, you can look yourself at Spliterators#spliteratorUnknownSize. It will grow arithmetically from 1024; that's why my suggestion of flattening the Nodes into a single List, with known size; that will parallelize much better.

Body:
I want to run an algorithm on large graphs concurrently, using multi-core parallelism. I have been working on it for a while, but haven't been able to come up with a good solution.

This is the naive algorithm:

W - a very large number
double weight = 0

while(weight < W)

    - v : get_random_node_from(Graph)

    - weight += calculate(v)

I looked into fork-and-join, but can't figure out a way to divide this problem into smaller subproblems.

Then I tried using Java 8 streams, for which I need to create a lambda expression. When I tried doing something like this:

double weight = 0
Callable<Object> task = () -> {
    can not update weight here, as it needs to be final
}

My question is, is it possible to update a variable like weight in a lambda method? Or is there a better way in which this problem can be solved?

The closest I have got is by using ExecutorService, but run into the problems of synchronization.

------------EDIT--------------

Here is the detailed algorithm:

In a nutshell, what I am trying to do, is traverse a massive graph, perform an operation on randomly selected nodes(as long as weight < W) and update a global structure Index.

This is taking too long as it doesn't utilize the full power of the CPU.

Ideally, all threads/processes on multiple cores would perform the operations on the randomly selected nodes, and update the shared weight and Index.

Note: It doesn't matter if different threads pick up the same node, as it's random without replacement.

Algorithm:

function Serial () {

List<List<Integer>> I (shared data structure which I want to update)
double weight

//// Task which I want to parallelize

while(weight < W) {

    v : get_random_node_from(Graph)

    bfs(v, affected_nodes) ...// this will fill up affected_nodes by v

    foreach(affected_node in affected_nodes) {

         // update I related to affected_node
         // and do other computation
    }

    weight += affected_nodes.size()

}

///////// Parallelization ends here

use_index(I) // I is passed now to some other method(not important) to get further results

}

The important thing is, all threads update the same I and weight.

Thanks.

Body:
Well you could wrap that weight into an array of a single element, it's sort of a know trick for this kind of stuff; even done internally by java, like this:

weight[0] = weight[0] + calculate(v);

But there are problems with this, since you are going to run it in parallel. You will not get the result you want since weight[0] is not thread-safe. And you could use some sort of synchronization, but java already has a great solution for that : DoubleAdder that scales far better in contended environments (and multiple cpus).

A trivial and small example:

DoubleAdder weight = new DoubleAdder();

private static int calculate(int v) {
    return v + 1;
}

Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
            .parallel()
            .forEach(x -> {
                int y = calculate(x);
                weight.add(y);
            });

System.out.println(weight); // 54

Then there is the problem of the randomizer that you are going to choose for this: get_random_node_from(Graph). You need to get a random Node indeed, but at the same time you need to get all of them exactly once.
But you might not need it if you can flatten all the nodes into a single List let's say.

The problem here is that Graphs are usually traversed in a recursive way, you don't know the exact size of it:

while(parent.hasChildren) {
     traverse children and so on...
}

This will parallelize bad under Streams, you can look yourself at Spliterators#spliteratorUnknownSize. It will grow arithmetically from 1024; that's why my suggestion of flattening the Nodes into a single List, with known size; that will parallelize much better.