问:
Use netpbm to upscale an image
I have a 72 dpi tiff that I'm trying to upsize to a 300 dpi tiff. I can do it from within image programs such as Gimp or even OS X built in preview. For some reason I can't seem to figure out how to do it in netbpm. I tried the following command line:

tifftopnm < sample1.tif | pamditherbw -threshold -value 0.5 | pamscale 4.2 | pamtopnm | pnmtotiff > sample1.out.tif

This produces a image that is 4.2 times the size of my original image but the output is still 72 dpi. How do I increase the actual pixels/inch of the image using netbpm, or is it even possible? I've tried pamenlarge too, which gives the same result. I also used the -xresolution and -yresolution parameters for pnmtotiff and it seems to just change the tag of the resolution, but doesn't actually enlarge the image.

答:
Well I couldn't quite figure this out with netpbm so I switched over to ImageMagick and it is rather simple. What I was trying to achieve above in image magick:

convert sample1.tif -resample 300 -threshold 50% sample1.out.tif

OwnerDisplayName: Ish

Title: Use netpbm to upscale an image

LastEditorDisplayName: Ish


来源: stackexchange

问:
Calculations with Rails3
Hey, need help to setup calculations in Rails3.

First off, I should write the logic in my model right? (transaction)

Then, let's assume I want to insert subtotal and total into the Db. What approach are you recommending?
Here is what I would do as a starting point.

In my model: Subtotal = amount

```<code>def subtotal
  @subtotal = :amount #table column
end
</code>```

In my model: total = subtotal + tax

```<code>def total
 @total = :subtotal + :tax #again referring to table column
end
</code>```

答:
I'd probably create subtotal and total attributes (include these in a create_ or change_table migration) and then set them in a callback like 'before_save.'

See:

http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview

ContentLicense: CC BY-SA 2.5

Title: Calculations with Rails3

Body:
Hey, need help to setup calculations in Rails3.

First off, I should write the logic in my model right? (transaction)

Then, let's assume I want to insert subtotal and total into the Db. What approach are you recommending?
Here is what I would do as a starting point.

In my model: Subtotal = amount

def subtotal
  @subtotal = :amount #table column
end

In my model: total = subtotal + tax

def total
 @total = :subtotal + :tax #again referring to table column
end


问:
PHP Fatal error: Mage_{mymodule}_Helper_Data not found
I have created my own shipping method with a custom module.
I have tested it on my staging copy of my website and it works perfectly.
But for some reason, the same code doesnt work on my production website.

The error that I found is:

"PHP Fatal error:  Class 'Mage_Ship_Helper_Data' not found in /var/www/html/app/Mage.php on line 549,"

The worse is that I dont use any helper in my module. I have created it only to respect the normal flow of magento modules.

This is a snapshot of my config.xml

```<code> <global>
    <helpers>
        <ship>
            <class>Excellence_Ship_Helper</class>
        </ship>
    </helpers>
</global>
</code>```

And this is my helper Data.php file: (as you can see, very simple)

```<code>class Excellence_Ship_Helper_Data extends Mage_Core_Helper_Abstract
{

}
</code>```

I have refresh the Magento Cache, I have deleted the Helper block on my config.xml and refresh again the cache but the problem persist.

答: Have you flushed your Magento & Browser Cache? If not, please do it.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created my own shipping method with a custom module.
I have tested it on my staging copy of my website and it works perfectly.
But for some reason, the same code doesnt work on my production website.

The error that I found is:

"PHP Fatal error:  Class 'Mage_Ship_Helper_Data' not found in /var/www/html/app/Mage.php on line 549,"

The worse is that I dont use any helper in my module. I have created it only to respect the normal flow of magento modules.

This is a snapshot of my config.xml

 <global>
    <helpers>
        <ship>
            <class>Excellence_Ship_Helper</class>
        </ship>
    </helpers>
</global>

And this is my helper Data.php file: (as you can see, very simple)

class Excellence_Ship_Helper_Data extends Mage_Core_Helper_Abstract
{

}

I have refresh the Magento Cache, I have deleted the Helper block on my config.xml and refresh again the cache but the problem persist.


问:
Setting up Swagger (ASP.NET Core) using the Authorization headers (Bearer)
I have a Web API (ASP.NET Core) and I am trying to adjust the swagger to make the calls from it.
The calls must contains the Authorization header and I am using Bearer authentication.
The calls from third party apps like Postman, etc. go fine.
But I am having the issue with setting up the headers for swagger (for some reason I don't receive the headers). This is how it looks like now:</p>

```<code>  "host": "localhost:50352",
  "basePath": "/" ,
  "schemes": [
    "http",
    "https"
  ],
 "securityDefinitions":  {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "HTTP/HTTPS Bearer"
    }
  },
  "paths": {
    "/v1/{subAccountId}/test1": {
      "post": {
        "tags": [
          "auth"
        ],
        "operationId": "op1",
        "consumes": ["application/json", "application/html"],
        "produces": ["application/json", "application/html"],
        "parameters": [
          {
            "name": "subAccountId",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "security":[{
          "Bearer": []
        }],
        "responses": {
          "204": {
            "description": "No Content"
          },
          "400": {
            "description": "BadRequest",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "401": {
            "description": "Unauthorized",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "500": {
            "description": "InternalServerError",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          }
        },
        "deprecated": false
      }
    },
</code>```

答: Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header, I have answered here.</p>

Body:
I have a Web API (ASP.NET Core) and I am trying to adjust the swagger to make the calls from it.
The calls must contains the Authorization header and I am using Bearer authentication.
The calls from third party apps like Postman, etc. go fine.
But I am having the issue with setting up the headers for swagger (for some reason I don't receive the headers). This is how it looks like now:

  "host": "localhost:50352",
  "basePath": "/" ,
  "schemes": [
    "http",
    "https"
  ],
 "securityDefinitions":  {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "HTTP/HTTPS Bearer"
    }
  },
  "paths": {
    "/v1/{subAccountId}/test1": {
      "post": {
        "tags": [
          "auth"
        ],
        "operationId": "op1",
        "consumes": ["application/json", "application/html"],
        "produces": ["application/json", "application/html"],
        "parameters": [
          {
            "name": "subAccountId",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "security":[{
          "Bearer": []
        }],
        "responses": {
          "204": {
            "description": "No Content"
          },
          "400": {
            "description": "BadRequest",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "401": {
            "description": "Unauthorized",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "500": {
            "description": "InternalServerError",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          }
        },
        "deprecated": false
      }
    },


问:
Visual Studio wrap selection in quotes?
Is there is a way to wrap a selected text block with quotes? In visual studio I have not found a extension or plugin I am just looking for a simple way to do it. Is there a way to add that functionality?</p>

答:
You can use the following command (C# language) with my Visual Commander extension to wrap a selected text block with quotes:</p>

```<code>public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        ts.Text = '"' + ts.Text + '"';
    }
}
</code>```

Title: Visual Studio wrap selection in quotes?

Body:
You can use the following command (C# language) with my Visual Commander extension to wrap a selected text block with quotes:

public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        ts.Text = '"' + ts.Text + '"';
    }
}


问:
(MASM32) How would I create a macro to obtain a string from user input?
I am still pretty new to Assembly and currently taking an introductory class at my local community college.

One of the requirements for our assignments was to use macros to print text and take in user input.

I am pretty sure my printing code is right:

```<code>displayString MACRO message:REQ
  lea  eax, message
  push eax
  call printf
  add esp, 4
ENDM
</code>```

I am confused though on how I would go about getting the user input. Here is what I have so far:

```<code>obtainString MACRO input:REQ, msgformat:REQ
  lea eax, input
  push eax
  lea eax, msgformat
  push eax
  call scanf
  add esp, 8
ENDM
</code>```

Because the macro is a separate file, I am pretty sure the variables do not transfer to my main file. I am just wondering how would I transfer the contents of 'input' from the macros file to a variable in my main file.
Thank you.

Side note: For some reason my project will not compile because it cannot find the macros file although it is in the same folder as the main file.

答:
input is not a variable, it's a macro parameter. Macros are essentially just a text replacement feature. So when you write something like:

```<code>obtainString foo, bar
</code>```

the assembler will replace that line with:

```<code>lea eax, foo
push eax
lea eax, bar
push eax
call scanf
add esp, 8
</code>```

So there's nothing to "transfer". Whatever label you pass as the first argument to obtainString is where the user input will be written to.

Body:
I am still pretty new to Assembly and currently taking an introductory class at my local community college.

One of the requirements for our assignments was to use macros to print text and take in user input.

I am pretty sure my printing code is right:

displayString MACRO message:REQ
  lea  eax, message
  push eax
  call printf
  add esp, 4
ENDM

I am confused though on how I would go about getting the user input. Here is what I have so far:

obtainString MACRO input:REQ, msgformat:REQ
  lea eax, input
  push eax
  lea eax, msgformat
  push eax
  call scanf
  add esp, 8
ENDM

Because the macro is a separate file, I am pretty sure the variables do not transfer to my main file. I am just wondering how would I transfer the contents of 'input' from the macros file to a variable in my main file.
Thank you.

Side note: For some reason my project will not compile because it cannot find the macros file although it is in the same folder as the main file.

Body:
input is not a variable, it's a macro parameter. Macros are essentially just a text replacement feature. So when you write something like:

obtainString foo, bar

the assembler will replace that line with:

lea eax, foo
push eax
lea eax, bar
push eax
call scanf
add esp, 8

So there's nothing to "transfer". Whatever label you pass as the first argument to obtainString is where the user input will be written to.


问:
Android opengles 2d culling
Anyone have links to tutorials on this topic? I cannot seem to find any related to 2d culling. Or if anyone here could explain how it's done. I use gluOrtho2D and gluLookAt currently.</p>

答:
GL shouldn't be drawing outside of the clipping planes that you defined in gluOrtho2D

One way to convince yourself of this is to compare the frame rate you get when you display a portion of the map vs. zooming out and displaying the entire map.

For larger scenes, this may not be enough.  In that case, determine which polygons are completely outside of the viewing frustum with code like in:

http://web.archive.org/web/20030207104008/http://www.markmorley.com/opengl/frustumculling.html

Title: Android opengles 2d culling


问:
Merge two array of objects with same keys, some object won't have the same value?

I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

```<code>var g= [
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];

var c= [
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];
</code>```

      My expected output should be :

```<code> var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]
</code>```

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

```<code>var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c);

finalData
</code>```

答:
You could use a Map for keeping same id in the same object and Object.assign for creating independent objects.

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = g.concat(c).reduce(function (r, o) {
        var temp;
        if (map.has(o.id)) {
            Object.assign(map.get(o.id), o);
        } else {
            temp = Object.assign({}, o);
            map.set(temp.id, temp);
            r.push(temp);
        }
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Version without reduce and without concat.

function merge(o) {
    var temp;
    if (map.has(o.id)) {
        Object.assign(map.get(o.id), o);
        return;
    }
    temp = Object.assign({}, o);
    map.set(temp.id, temp);
    result.push(temp);
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = [];

[g, c].forEach(function (a) {
    a.forEach(merge);
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

With dynamic key.

function mergeBy(key, data) {
    return Array.from(data
        .reduce((m, o) => m.set(o[key], { ...m.get(o[key]), ...o }), new Map)
        .values()
    );
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    result = mergeBy('id', [...g, ...c]);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

var g= [
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];

var c= [
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];

      My expected output should be :

 var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c);

finalData

Body:
You could use a Map for keeping same id in the same object and Object.assign for creating independent objects.

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = g.concat(c).reduce(function (r, o) {
        var temp;
        if (map.has(o.id)) {
            Object.assign(map.get(o.id), o);
        } else {
            temp = Object.assign({}, o);
            map.set(temp.id, temp);
            r.push(temp);
        }
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

Version without reduce and without concat.

function merge(o) {
    var temp;
    if (map.has(o.id)) {
        Object.assign(map.get(o.id), o);
        return;
    }
    temp = Object.assign({}, o);
    map.set(temp.id, temp);
    result.push(temp);
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    map = new Map,
    result = [];

[g, c].forEach(function (a) {
    a.forEach(merge);
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

With dynamic key.

function mergeBy(key, data) {
    return Array.from(data
        .reduce((m, o) => m.set(o[key], { ...m.get(o[key]), ...o }), new Map)
        .values()
    );
}

var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
    c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
    result = mergeBy('id', [...g, ...c]);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

ContentLicense: CC BY-SA 4.0


问:
SSJS remove item from an array
In ssjs I have an array that contains jsonobjects. this array is stored in a scope variable and displayed in a repeat control:

```<code><xp:repeat id="rptAssessors" value="#{sessionScope.tmpAssessors}" var="obj" indexVar="idx">
</code>```

From the repeat control I would like to add the option to remove individual items from the array e.g. via onclick event on a button for each row:

```<code><xp:eventHandler event="onclick" submit="true" refreshMode="partial" immediate="true" refreshId="dlgContent"> <xp:this.action> <xp:executeScript
 script="#{javascript:removeAssessor(idx);}"> </xp:executeScript> </xp:this.action></xp:eventHandler>
</code>```

My removeAssessor function looks as followed:

```<code>function removeAssessor(idx){

    var jsonObjArr = sessionScope.get("tmpAssessors");

    print("before elements " + jsonObjArr.length)
    print(idx + 1)
    jsonObjArr.splice(idx,1);
    print("after elements " + jsonObjArr.length)

    sessionScope.put("tmpAssessors",jsonObjArr);

}
</code>```

I notice the splice() method does not work. I read on an xsnippet that this method does not work in SSJS and an alternative is posted as an xsnippet but this is for arrays containing strings

https://openntf.org/XSnippets.nsf/snippet.xsp?id=remove-an-entry-from-an-array-of-strings

Anyone can tell me how to remove an item from the array that is not a string?

答:
Array.splice does work in SSJS, but not in the "inline way" you might be used to from CSJS: In CSJS the modification is done inline (no new array is created) and the removed elements are returned. In SSJS, the original array is not modified and the return value is a copy of the array excluding the spliced elements.

If you replace jsonObjArr.splice(idx,1); with jsonObjArr=jsonObjArr.splice(idx,1); your code should work fine.

Title: SSJS remove item from an array

Body:
In ssjs I have an array that contains jsonobjects. this array is stored in a scope variable and displayed in a repeat control:

<xp:repeat id="rptAssessors" value="#{sessionScope.tmpAssessors}" var="obj" indexVar="idx">

From the repeat control I would like to add the option to remove individual items from the array e.g. via onclick event on a button for each row:

<xp:eventHandler event="onclick" submit="true" refreshMode="partial" immediate="true" refreshId="dlgContent"> <xp:this.action> <xp:executeScript
 script="#{javascript:removeAssessor(idx);}"> </xp:executeScript> </xp:this.action></xp:eventHandler>

My removeAssessor function looks as followed:

function removeAssessor(idx){

    var jsonObjArr = sessionScope.get("tmpAssessors");

    print("before elements " + jsonObjArr.length)
    print(idx + 1)
    jsonObjArr.splice(idx,1);
    print("after elements " + jsonObjArr.length)

    sessionScope.put("tmpAssessors",jsonObjArr);

}

I notice the splice() method does not work. I read on an xsnippet that this method does not work in SSJS and an alternative is posted as an xsnippet but this is for arrays containing strings

https://openntf.org/XSnippets.nsf/snippet.xsp?id=remove-an-entry-from-an-array-of-strings

Anyone can tell me how to remove an item from the array that is not a string?


问:
Search ArrayList for certain character in string
What is the correct syntax for searching an ArrayList of strings for a single character?  I want to check each string in the array for a single character.
Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string.
I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists.  None of them do quite what I need.
P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.

--- Edit ---

As per MightyPork's recommendations arraylist revised to use simple string type.  This also made it compatible with hoosssein's solution which is included.

```<code>public void ArrayInput() {
    String FileName;                            // set file variable
    FileName = fileName.getText();              // get file name

    ArrayList<String> fileContents = new ArrayList<String>();       // create arraylist

    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
        String line = null;

        while ((line = reader.readLine()) != null) {
            if(line.length() > 0) {                         // don't include blank lines
                line = line.trim();                         // remove whitespaces
                fileContents.add(line);                     // add to array
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }

        String oldstr;
        String newstr;

        oldstr = "}";
        newstr = "!!!!!";

        for(int i = 0; i < fileContents.size(); i++) {
            if(fileContents.contains(oldstr)) {
                fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }
                                // close file
    }

    catch (IOException ex) {    // E.H. for try
        JOptionPane.showMessageDialog(null, "File not found.  Check name and directory.");
    }
}
</code>```

答:
Another way by using iterator

```<code>public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Naman");
        list.add("Aman");
        list.add("Nikhil");
        list.add("Adarsh");
        list.add("Shiva");
        list.add("Namit");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next.startsWith("Na")) {
                System.out.println(next);
            }
        }
    }
</code>```

Body:
What is the correct syntax for searching an ArrayList of strings for a single character?  I want to check each string in the array for a single character.
Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string.
I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists.  None of them do quite what I need.
P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.

--- Edit ---

As per MightyPork's recommendations arraylist revised to use simple string type.  This also made it compatible with hoosssein's solution which is included.

public void ArrayInput() {
    String FileName;                            // set file variable
    FileName = fileName.getText();              // get file name

    ArrayList<String> fileContents = new ArrayList<String>();       // create arraylist

    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
        String line = null;

        while ((line = reader.readLine()) != null) {
            if(line.length() > 0) {                         // don't include blank lines
                line = line.trim();                         // remove whitespaces
                fileContents.add(line);                     // add to array
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }

        String oldstr;
        String newstr;

        oldstr = "}";
        newstr = "!!!!!";

        for(int i = 0; i < fileContents.size(); i++) {
            if(fileContents.contains(oldstr)) {
                fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }
                                // close file
    }

    catch (IOException ex) {    // E.H. for try
        JOptionPane.showMessageDialog(null, "File not found.  Check name and directory.");
    }
}

Body:
Another way by using iterator

public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Naman");
        list.add("Aman");
        list.add("Nikhil");
        list.add("Adarsh");
        list.add("Shiva");
        list.add("Namit");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next.startsWith("Na")) {
                System.out.println(next);
            }
        }
    }


问:
Where to open file in a Perl module

Below is a toy version of a module I'm writing. This example faithfully demonstrates the problem I having.

I have a file bed_in.txt

2L      0       4953
2L      16204   16284
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635
2L      19894   21366
2L      21582   21583
2L      47501   52365
2L      4698700 4709369
```

<p>that I want to use to filter values in an array.</p>

<p>I want to check whether the second column of <code>bed_in.txt</code> matches any value in</p>

<pre class="lang-none prettyprint-override"><code>my @lines = qw/ 16204 40 200 149 19445 178 /;
</code>```

push this to an array if so.

My final output for this data should be the two elements in @lines that are also in the second column of bed_in.txt

2L      0       4953
2L      16204   16284 # 16204 == 16204
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635 # 19445 == 19445
```

<p>But where should I open my file?</p>

<p>Should this happen in the script that calls my module <code>run_fileOpen.pl</code>, or in the module itself? </p>

<p>In either case, I am not getting the correct output, and my module appears to be called for only the first element of <code>@lines</code></p>

<h3>parseFile.pm</h3>

<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl

package parseFile;
use strict;
use warnings;

use FindBin qw/ $Bin /;
use lib File::Spec->catdir($FindBin::Bin, '..', 'bin/');

use Data::Printer;

open my $bed, '<', 'bed_in.txt';

sub check_lines {
  my ($line, $filter_ref) = @_;
  my @filter_reasons = @{ $filter_ref };

  my $lines_to_filter_ref = filter_lines($line, $bed, \@filter_reasons);

  return($lines_to_filter_ref);
}

sub filter_lines {
  my ($line, $bed_file, $lines_to_filter) = @_;

  my @filter = @{ $lines_to_filter };

  while(<$bed_file>){
    chomp;
    my $start = (split)[1];
    # print "line: $line  start: $start\n";
    if ($line == $start ) {

      push @filter, "Filter as equal: $start, $line [$_]";
    }
  }
  # p(@filter);
  return(\@filter);
}

1;
</code>```

run_parseFile.pl

#!/usr/bin/perl

use strict;
use warnings;

use parseFile;

my @lines = qw/ 16204 40 200 149 19445 178 /;

foreach(@lines){
  my @filter_reasons = 'reason 1';
  my $lines2filter = parseFile::check_lines($_, \@filter_reasons);
  @filter_reasons = @{ $lines2filter };
  print "$_\n" foreach @filter_reasons;
}
```

<h3>Output</h3>

<pre class="lang-none prettyprint-override"><code>reason 1
Filter as equal: 16204, 16204 [2L   16204   16284]
reason 1
reason 1
reason 1
reason 1
reason 1
</code>```

When I add a print statement to the while loop in filter_lines I can see that only the first element is being run:

line: 16204  start: 0
line: 16204  start: 16204
line: 16204  start: 16612
line: 16204  start: 17086
line: 16204  start: 18757
line: 16204  start: 19040
line: 16204  start: 19445
line: 16204  start: 19894
line: 16204  start: 21582
line: 16204  start: 47501
line: 16204  start: 4698700
```

Is this an appropriate way to deal with opening my bed_in.txt file, or should I open it in the run_parseFile.pl script? Or is there something else entirely wrong with my code?

答:
Here's how I would write this. As I said, I prefer an object-oriented solution

The new constructor requires a file name as its parameter. It opens the file, reads the information into a hash, and blesses to make the object

The only method is check_lines, which expects a value and a reason string. It simply interrogates the hash for the given value and returns a one- or two-element array according to whether the value was found

It is best to limit the scope of this object as otherwise the hash will be kept in memory after it is required. So I've enclosed all the operations that require the object in a block. The object will be automatically destroyed when it goes out of scope at the end of the block

BedInFilter.pm

package BedInFilter;

use strict;
use warnings 'all';

use Carp 'croak';

sub new {
    my $class = shift;
    my ( $bed_file ) = @_;

    my %self;

    open my $fh, '<', $bed_file
            or croak qq{Unable to open "$bed_file" for input: $!};

    while ( <$fh> ) {

        next unless /\S/;
        chomp;

        my $val = ( split )[1];
        $self{$val} = $_;
    }

    bless \%self, $class;
}

sub check_lines {
    my $self = shift;
    my ( $val, $reason ) = @_;

    my $result = [ $reason ];

    my $line = $self->{$val};

    push @$result, "Filter as equal: $val, $val [$line]" if $line;

    $result;
}

1;
```

<h3>bed_in.pl</h3>

<pre class="lang-perl prettyprint-override"><code>use strict;
use warnings 'all';

use BedInFilter;

my @values = qw/ 16204 40 200 149 19445 178 /;

{
    my $filter = BedInFilter->new( 'bed_in.txt' );

    for my $val ( @values ) {

        my $reason = 'reason1';

        my $result = $filter->check_lines( $val, $reason );

        print "@$result\n";
    }
}
</code>```

output

reason1 Filter as equal: 16204, 16204 [2L      16204   16284]
reason1
reason1
reason1
reason1 Filter as equal: 19445, 19445 [2L      19445   19635]
reason1
```

Title: Where to open file in a Perl module

Body:
Below is a toy version of a module I'm writing. This example faithfully demonstrates the problem I having.

I have a file bed_in.txt

2L      0       4953
2L      16204   16284
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635
2L      19894   21366
2L      21582   21583
2L      47501   52365
2L      4698700 4709369

that I want to use to filter values in an array.

I want to check whether the second column of bed_in.txt matches any value in

my @lines = qw/ 16204 40 200 149 19445 178 /;

push this to an array if so.

My final output for this data should be the two elements in @lines that are also in the second column of bed_in.txt

2L      0       4953
2L      16204   16284 # 16204 == 16204
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635 # 19445 == 19445

But where should I open my file?

Should this happen in the script that calls my module run_fileOpen.pl, or in the module itself?

In either case, I am not getting the correct output, and my module appears to be called for only the first element of @lines

parseFile.pm

#!/usr/bin/perl

package parseFile;
use strict;
use warnings;

use FindBin qw/ $Bin /;
use lib File::Spec->catdir($FindBin::Bin, '..', 'bin/');

use Data::Printer;

open my $bed, '<', 'bed_in.txt';

sub check_lines {
  my ($line, $filter_ref) = @_;
  my @filter_reasons = @{ $filter_ref };

  my $lines_to_filter_ref = filter_lines($line, $bed, \@filter_reasons);

  return($lines_to_filter_ref);
}

sub filter_lines {
  my ($line, $bed_file, $lines_to_filter) = @_;

  my @filter = @{ $lines_to_filter };

  while(<$bed_file>){
    chomp;
    my $start = (split)[1];
    # print "line: $line  start: $start\n";
    if ($line == $start ) {

      push @filter, "Filter as equal: $start, $line [$_]";
    }
  }
  # p(@filter);
  return(\@filter);
}

1;

run_parseFile.pl

#!/usr/bin/perl

use strict;
use warnings;

use parseFile;

my @lines = qw/ 16204 40 200 149 19445 178 /;

foreach(@lines){
  my @filter_reasons = 'reason 1';
  my $lines2filter = parseFile::check_lines($_, \@filter_reasons);
  @filter_reasons = @{ $lines2filter };
  print "$_\n" foreach @filter_reasons;
}

Output

reason 1
Filter as equal: 16204, 16204 [2L   16204   16284]
reason 1
reason 1
reason 1
reason 1
reason 1

When I add a print statement to the while loop in filter_lines I can see that only the first element is being run:

line: 16204  start: 0
line: 16204  start: 16204
line: 16204  start: 16612
line: 16204  start: 17086
line: 16204  start: 18757
line: 16204  start: 19040
line: 16204  start: 19445
line: 16204  start: 19894
line: 16204  start: 21582
line: 16204  start: 47501
line: 16204  start: 4698700

Is this an appropriate way to deal with opening my bed_in.txt file, or should I open it in the run_parseFile.pl script? Or is there something else entirely wrong with my code?

Body:
Here's how I would write this. As I said, I prefer an object-oriented solution

The new constructor requires a file name as its parameter. It opens the file, reads the information into a hash, and blesses to make the object

The only method is check_lines, which expects a value and a reason string. It simply interrogates the hash for the given value and returns a one- or two-element array according to whether the value was found

It is best to limit the scope of this object as otherwise the hash will be kept in memory after it is required. So I've enclosed all the operations that require the object in a block. The object will be automatically destroyed when it goes out of scope at the end of the block

BedInFilter.pm

package BedInFilter;

use strict;
use warnings 'all';

use Carp 'croak';

sub new {
    my $class = shift;
    my ( $bed_file ) = @_;

    my %self;

    open my $fh, '<', $bed_file
            or croak qq{Unable to open "$bed_file" for input: $!};

    while ( <$fh> ) {

        next unless /\S/;
        chomp;

        my $val = ( split )[1];
        $self{$val} = $_;
    }

    bless \%self, $class;
}

sub check_lines {
    my $self = shift;
    my ( $val, $reason ) = @_;

    my $result = [ $reason ];

    my $line = $self->{$val};

    push @$result, "Filter as equal: $val, $val [$line]" if $line;

    $result;
}

1;

bed_in.pl

use strict;
use warnings 'all';

use BedInFilter;

my @values = qw/ 16204 40 200 149 19445 178 /;

{
    my $filter = BedInFilter->new( 'bed_in.txt' );

    for my $val ( @values ) {

        my $reason = 'reason1';

        my $result = $filter->check_lines( $val, $reason );

        print "@$result\n";
    }
}

output

reason1 Filter as equal: 16204, 16204 [2L      16204   16284]
reason1
reason1
reason1
reason1 Filter as equal: 19445, 19445 [2L      19445   19635]
reason1


问:
Moving things position within a container in wpf
I have this problem, I want to adjust the position of an image or the hole canvas inside my container which is a 'border', it is more likely a translate transform but depending on the user by moving this element around to adjust it to the suitable position, because my program needs an accurate coordinates.  </p>

答: Had something similar, just placed the canvas in another canvas so i could move it around more easily.</p>


问:
Rails JSON Parameter not parsed
I have a registration form in ReactJS and want to to send the user data (name, email, password) in JSON format to my rails API. Rails then does not parse my JSON data into parameters.

Routes

```<code>Rails.application.routes.draw do
    get '/list_users' => 'users#index'
    post '/register_user' => 'users#register'
end
</code>```

User Controller

```<code>class UsersController < ApplicationController
    def index
        @users = User.all
        render json: @users
    end

    def register
        puts params.inspect
        @user = User.new(name: 'TEST', :email => params[:email], :password => params[:password])
        #@user = User.new(name: 'User', email: 'controller@user.com', password: 'password') (this works)
        @user.save
    end
end
</code>```

puts params.inspect outputs:

```<code><ActionController::Parameters {"controller"=>"users", "action"=>"register"} permitted: false>
</code>```

Registration form

```<code>postData(){
    var myHeaders = new Headers();
    myHeaders.append('Accept', 'application/json')
    myHeaders.append('Content-Type', 'application/json');

    var data = JSON.stringify({
        name: "Test",
        email: "test@post.com",
        password: "password"
    })

    fetch("http://127.0.0.1:3000/register_user",{
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: data
    })
    .then(function(res){ return res.json(); })
    .then(function(data){ alert( JSON.stringify( data ) ) })
    .catch( (ex) => {
        console.log("Fetch failed" + ex);
    });
}
</code>```

parameter wrapping for JSON is enabled in the config.
Thanks for the help!

答:
configuring Rack::Cors to accept OPTIONS did the trick, like sideshowbarker explainend in his comment.

application.rb

```<code>config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end
</code>```

and in the frontend

```<code>mode: 'cors'
</code>```

Title: Rails JSON Parameter not parsed

Body:
I have a registration form in ReactJS and want to to send the user data (name, email, password) in JSON format to my rails API. Rails then does not parse my JSON data into parameters.

Routes

Rails.application.routes.draw do
    get '/list_users' => 'users#index'
    post '/register_user' => 'users#register'
end

User Controller

class UsersController < ApplicationController
    def index
        @users = User.all
        render json: @users
    end

    def register
        puts params.inspect
        @user = User.new(name: 'TEST', :email => params[:email], :password => params[:password])
        #@user = User.new(name: 'User', email: 'controller@user.com', password: 'password') (this works)
        @user.save
    end
end

puts params.inspect outputs:

<ActionController::Parameters {"controller"=>"users", "action"=>"register"} permitted: false>

Registration form

postData(){
    var myHeaders = new Headers();
    myHeaders.append('Accept', 'application/json')
    myHeaders.append('Content-Type', 'application/json');

    var data = JSON.stringify({
        name: "Test",
        email: "test@post.com",
        password: "password"
    })

    fetch("http://127.0.0.1:3000/register_user",{
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: data
    })
    .then(function(res){ return res.json(); })
    .then(function(data){ alert( JSON.stringify( data ) ) })
    .catch( (ex) => {
        console.log("Fetch failed" + ex);
    });
}

parameter wrapping for JSON is enabled in the config.
Thanks for the help!

Body:
configuring Rack::Cors to accept OPTIONS did the trick, like sideshowbarker explainend in his comment.

application.rb

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

and in the frontend

mode: 'cors'


问:
Corda generateSpend pay coins add memo
Hi Is there a way to use Cash.generateSpend and allocate a message memo together with it?

My use case is simple, where when i spend the case i would like to tag the cash into some generic categories for example, manually-transferred or auto-transferred to a specific party.
I've been going through https://docs.corda.net/api/kotlin/corda/net.corda.finance.contracts.asset/-cash/index.html but there were no methods to add a tagging to the asset transferred purpose.

The main purpose is so when i query my history transactions i could see the movement of my funds.

答:
You would need to write a custom SQL query to join the two tables (using the transaction id as join key) - vault_states/vault_fungible_states and vault_transaction_notes - by using the serviceHub.jdbcSession().

Please fee free to add a Feature Request if you would like us to extend the Vault Query API to provide a query criteria method to perform this automatically. Please add here:
https://github.com/corda/corda/issues

Title: Corda generateSpend pay coins add memo


问:
Cropped area rectangle show where previously cropped area like whats app
I'm developing Photoshop type app in which crop tools is using to crop image and i'm using default crop intent, when i cropped image i get bundle in which i got Rect(0,0-2,122) left,top,right,bottom but my point is when i cropped first time and again i cropped the cropper show its previously cropped area not default area and in crop intent.

```<code>CropIntent.putExtra("outputX", imageWidth);
CropIntent.putExtra("outputY", imageHeight);
CropIntent.putExtra("aspectX", 100);
CropIntent.putExtra("aspectY", -100);
CropIntent.putExtra("spotlightX", 10);
CropIntent.putExtra("spotlightY", -10);
</code>```

I pass l,t,r,b like this, i know this is wrong but i tried aspect x and aspect y are ratios but spot light is what, i don't know. can i place cropper at previously cropped area on same image.

答:
You can use this library from here

and use below method two recover the ratio  on the image and call it where your image is to be cropped and remember when Activity is switched do not finish it.

```<code> public void updateCurrentCropViewOptions() {
    CropImageViewOptions options = new CropImageViewOptions();
    options.scaleType = mCropImageView.getScaleType();
    options.cropShape = mCropImageView.getCropShape();
    options.guidelines = mCropImageView.getGuidelines();
    options.aspectRatio = mCropImageView.getAspectRatio();
    options.fixAspectRatio = mCropImageView.isFixAspectRatio();
    options.showCropOverlay = mCropImageView.isShowCropOverlay();
    options.showProgressBar = mCropImageView.isShowProgressBar();
    options.autoZoomEnabled = mCropImageView.isAutoZoomEnabled();
    options.maxZoomLevel = mCropImageView.getMaxZoom();
    options.flipHorizontally = mCropImageView.isFlippedHorizontally();
    options.flipVertically = mCropImageView.isFlippedVertically();
}
</code>```

Body:
I'm developing Photoshop type app in which crop tools is using to crop image and i'm using default crop intent, when i cropped image i get bundle in which i got Rect(0,0-2,122) left,top,right,bottom but my point is when i cropped first time and again i cropped the cropper show its previously cropped area not default area and in crop intent.

CropIntent.putExtra("outputX", imageWidth);
CropIntent.putExtra("outputY", imageHeight);
CropIntent.putExtra("aspectX", 100);
CropIntent.putExtra("aspectY", -100);
CropIntent.putExtra("spotlightX", 10);
CropIntent.putExtra("spotlightY", -10);

I pass l,t,r,b like this, i know this is wrong but i tried aspect x and aspect y are ratios but spot light is what, i don't know. can i place cropper at previously cropped area on same image.

Body:
You can use this library from here

and use below method two recover the ratio  on the image and call it where your image is to be cropped and remember when Activity is switched do not finish it.

 public void updateCurrentCropViewOptions() {
    CropImageViewOptions options = new CropImageViewOptions();
    options.scaleType = mCropImageView.getScaleType();
    options.cropShape = mCropImageView.getCropShape();
    options.guidelines = mCropImageView.getGuidelines();
    options.aspectRatio = mCropImageView.getAspectRatio();
    options.fixAspectRatio = mCropImageView.isFixAspectRatio();
    options.showCropOverlay = mCropImageView.isShowCropOverlay();
    options.showProgressBar = mCropImageView.isShowProgressBar();
    options.autoZoomEnabled = mCropImageView.isAutoZoomEnabled();
    options.maxZoomLevel = mCropImageView.getMaxZoom();
    options.flipHorizontally = mCropImageView.isFlippedHorizontally();
    options.flipVertically = mCropImageView.isFlippedVertically();
}


问:
Unable to locate element using xpath from Auto suggest dropdown
I am trying to locate an element from an autosuggestion list using xpath but getting InvalidSelectorException. Below is my code:-

```<code>WebDriverWait wait=new WebDriverWait(driver, 10);
driver.findElement(By.xpath(".//*[@id='EngagementCode']")).sendKeys("111");
   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//[@id='typeahead-5-5946-option-0']/a"))).click();
</code>```

Also please suggest How can I find it using different method if possible.

Please find HTML

```<code> <ul id="typeahead-5-5946" class="dropdown-menu ng-isolate-scope" ng-show="isOpen() && !moveInProgress" ng-style="{top: position().top+'px', left: position().left+'px'}" style="display: block; top: 34px; left: 15px;" role="listbox" aria-hidden="false" typeahead-popup="" matches="matches" active="activeIdx" select="select(activeIdx)" move-in-progress="moveInProgress" query="query" position="position">
<!-- ngRepeat: match in matches track by $index -->
<li id="typeahead-5-5946-option-0" class="ng-scope active" ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }" ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option">
<a class="ng-binding ng-scope" href="" tabindex="-1" ng-bind-html="match.label | typeaheadHighlight:query">
xxx
<strong>111</strong>
x  - xxx services_xxx
</a>
</li>
<!-- end ngRepeat: match in matches track by $index -->
</code>```

答:
To click(select) the autosuggestion 111, you can use the following block of code :

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement elem = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[@class='ng-scope active']/a[@class='ng-binding ng-scope']/strong")));
elem.click();
</code>```

Body:
I am trying to locate an element from an autosuggestion list using xpath but getting InvalidSelectorException. Below is my code:-

WebDriverWait wait=new WebDriverWait(driver, 10);
driver.findElement(By.xpath(".//*[@id='EngagementCode']")).sendKeys("111");
   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//[@id='typeahead-5-5946-option-0']/a"))).click();

Also please suggest How can I find it using different method if possible.

Please find HTML

xxx
111
x  - xxx services_xxx

Body:
To click(select) the autosuggestion 111, you can use the following block of code :

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement elem = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[@class='ng-scope active']/a[@class='ng-binding ng-scope']/strong")));
elem.click();


问:
can't retrieve woocommerce product data in react-native
I'm just trying to get sample product data from woocommerce API.

this is my code:

```<code>import React, { Component } from 'react';
import {
    AppRegistry,
    Text,
    View
} from 'react-native';
import Api from './WooCommerce/Api.js'

export default class FetchExample extends Component{
    constructor() {
        super();

    }
    render() {
        return (
            <View>
                <Text>{this.state.date.name}</Text>

            </View>
        );
    }
    componentWillMount() {
        this.setState.date = Api.get('products/122609')

    }
}

AppRegistry.registerComponent('fetchExample', () => FetchExample);
</code>```

And here is a error:

答:
Initialise your state with default values inside of your constructor:

```<code>this.state = { date: '...' };
</code>```

Then change your state updating logic from direct assignment to this.setState, since direct assignment will lead to unexpected behaviour:

```<code>this.setState({ date: Api.get('products/122609') });
</code>```

Body:
I'm just trying to get sample product data from woocommerce API.

this is my code:

import React, { Component } from 'react';
import {
    AppRegistry,
    Text,
    View
} from 'react-native';
import Api from './WooCommerce/Api.js'

export default class FetchExample extends Component{
    constructor() {
        super();

    }
    render() {
        return (
            <View>
                <Text>{this.state.date.name}</Text>

            </View>
        );
    }
    componentWillMount() {
        this.setState.date = Api.get('products/122609')

    }
}

AppRegistry.registerComponent('fetchExample', () => FetchExample);

And here is a error:

Body:
Initialise your state with default values inside of your constructor:

this.state = { date: '...' };

Then change your state updating logic from direct assignment to this.setState, since direct assignment will lead to unexpected behaviour:

this.setState({ date: Api.get('products/122609') });


问:
How can I return the difference between two lists?
I have two array lists e.g.

```<code>List<Date> a;
contains : 10/10/2014, 10/11/2016

List<Date> b;
contains : 10/10/2016
</code>```

How can i do a check between list a and b so the value that is missing in b is returned?e.g. 10/10/2014

答:
You can use CollectionUtils from Apache Commons Collections 4.0:</p>

```<code>new ArrayList<>(CollectionUtils.subtract(a, b))
</code>```

Body:
I have two array lists e.g.

List<Date> a;
contains : 10/10/2014, 10/11/2016

List<Date> b;
contains : 10/10/2016

How can i do a check between list a and b so the value that is missing in b is returned?e.g. 10/10/2014

Body:
You can use CollectionUtils from Apache Commons Collections 4.0:

new ArrayList<>(CollectionUtils.subtract(a, b))


问:
"Toggle fullscreen view" event for Google Maps
Is there a way to capture event where a user clicks toggle fullscreen view button on the map?

答:
Here is the solution which worked for me:

const onFullScreen = (cb) => {
    const eventNames = [
        'fullscreenchange',
        'webkitfullscreenchange',
        'mozfullscreenchange'
    ];

    eventNames.map(e => document.addEventListener(e, (event) => {
         const isFullScreen = document['fullScreen'] ||
               document['mozFullScreen'] || document['webkitIsFullScreen'];

         return cb({ isFullScreen, event });
    }));
};
```


问:
Getting DOM of object user clicks on
Ok people can make a list on my website by pushing the ADD button. the code to do this is as follows (using jquery):

```<code><script type="text/javascript">
 function voegToe(){
 $('#sortable1').append("<li class='ui-state-default'>" + $('#product').html() + $('#eiwit').html() + " <button id='voegtoe' class='zoek' type='button' onClick='deleteObject();'>del</button></li>");
 }
</script>
</code>```

so pushing the button adds a LI element in the UL#sortable1 which also has a delete button in it. Now I want to make an event that when the users clicks the delete button of a certain list item, that list items is removed from the list.

How can I do this? because now when a list is made, all the li id's or classes are the same, so I can't use that to specify which element should be removed. So how can I say: delete only the LI of which the delete button was pressed?

```<code>    <script type="text/javascript">
     function voegToe(){
      $('??????').remove();
     }
    </script>
</code>```

答:
```<code>$('.zoek').live('click', function() {
    $(this).parent().remove();
});
</code>```

Title: Getting DOM of object user clicks on

Body:
Ok people can make a list on my website by pushing the ADD button. the code to do this is as follows (using jquery):

so pushing the button adds a LI element in the UL#sortable1 which also has a delete button in it. Now I want to make an event that when the users clicks the delete button of a certain list item, that list items is removed from the list.

How can I do this? because now when a list is made, all the li id's or classes are the same, so I can't use that to specify which element should be removed. So how can I say: delete only the LI of which the delete button was pressed?


问:
How do I update a String value into MySQL Datetime in java code using PreparedStatement?
I have a date/time value in String form like "11/28/2017 4:00:49 PM" in my java code. Now how can I take this same value to MySQL column of type datetime?

Please note, I'm using PreparedStatement to insert the record in MySQL DB.

Here are the few ways I tried...

```<code>DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy KK:mm:ss a");
ps.setString(outputFormat.format(inputFormat.parse(rs.getString(1))));
</code>```

I used the above code and I'm getting the below exception...

```<code>com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '08-09-0017 02:46:57 AM' for column 'column_name' at row 1
</code>```

If I use the below code, I'm getting only Date but time with AM/PM is lost

```<code>ps.setDate(inputFormat.parse(rs.getString(1)));
</code>```

If I use the below code, I'm getting only Time but without AM/PM and Date

```<code>ps.setTime(inputFormat.parse(rs.getString(1).getTime()));
</code>```

If I use the below code, I get error

```<code>ps.setDate(1, (java.sql.Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("11/28/2017 4:00:49 PM"));

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
</code>```

答:
java.util.Date date1=new java.util.Date();

```<code>    java.sql.Date currentdate=new java.sql.Date(date1.getTime());
    java.sql.Time currenttime=new java.sql.Time(date1.getTime());
</code>```

prepareStatement.setDate(1,currentDate);
prepareStatement.setTime(2,currentTime);

see this code it will current Date and Time

Body:
I have a date/time value in String form like "11/28/2017 4:00:49 PM" in my java code. Now how can I take this same value to MySQL column of type datetime?

Please note, I'm using PreparedStatement to insert the record in MySQL DB.

Here are the few ways I tried...

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy KK:mm:ss a");
ps.setString(outputFormat.format(inputFormat.parse(rs.getString(1))));

I used the above code and I'm getting the below exception...

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '08-09-0017 02:46:57 AM' for column 'column_name' at row 1

If I use the below code, I'm getting only Date but time with AM/PM is lost

ps.setDate(inputFormat.parse(rs.getString(1)));

If I use the below code, I'm getting only Time but without AM/PM and Date

ps.setTime(inputFormat.parse(rs.getString(1).getTime()));

If I use the below code, I get error

ps.setDate(1, (java.sql.Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("11/28/2017 4:00:49 PM"));

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

Body:
java.util.Date date1=new java.util.Date();

    java.sql.Date currentdate=new java.sql.Date(date1.getTime());
    java.sql.Time currenttime=new java.sql.Time(date1.getTime());

prepareStatement.setDate(1,currentDate);
prepareStatement.setTime(2,currentTime);

see this code it will current Date and Time


问:
Jquery $(window).on("load"... and chrome extensions
I'm making a chrome extension, I need to add a few listeners and classes to elements when my popup load.

So far, I've did this :

```<code>$("body").ready(main());
</code>```

where I added things to the elements in my main function, problem is, elements doesn't exist when main is run, so it doesn't work.

I've looked and found that $(window).load() should be used. I tried, but got jquery errors. I've looked and found that $(window).on("load",main()) should work instead. I tried, and it "worked" just like my $("body").ready(...
For some ready, even the "window on load" thing doesn't wait for my elements to be fully loaded.
Simple test I'm trying to do is :

```<code>function main(){
    console.log($("#toto").attr("id"));
}
</code>```

When I open the popup of my extension, it returns "undefined" in the console, but if I paste the same code, it returns "toto".
How could I make this work please ?

答:
You could try this:

```<code>$(document).ready(function(){
//your code here
var id = $("#toto").attr("id");
console.log(id);
});
</code>```

you can use a separate function if you want but you have to define the function first:

```<code>function main(){
    console.log($("#toto").attr("id"));
}
$(document).ready(main());
</code>```

Body:
I'm making a chrome extension, I need to add a few listeners and classes to elements when my popup load.

So far, I've did this :

$("body").ready(main());

where I added things to the elements in my main function, problem is, elements doesn't exist when main is run, so it doesn't work.

I've looked and found that $(window).load() should be used. I tried, but got jquery errors. I've looked and found that $(window).on("load",main()) should work instead. I tried, and it "worked" just like my $("body").ready(...
For some ready, even the "window on load" thing doesn't wait for my elements to be fully loaded.
Simple test I'm trying to do is :

function main(){
    console.log($("#toto").attr("id"));
}

When I open the popup of my extension, it returns "undefined" in the console, but if I paste the same code, it returns "toto".
How could I make this work please ?

Body:
You could try this:

$(document).ready(function(){
//your code here
var id = $("#toto").attr("id");
console.log(id);
});

you can use a separate function if you want but you have to define the function first:

function main(){
    console.log($("#toto").attr("id"));
}
$(document).ready(main());


问:
search in the first 300 rows in sql
I'm using MS SQL Server Management Studio R2

suppose I have a table tableX with infinite records count,
and that table has a column colX, and the there's only 2 records in the whole table that have this colX not null,

what should the query look like?

I used

```<code>select top 10 * from tableX where colX isnot null
</code>```

but it took forever executing the query

it there a way to search in the first 300 rows only?
thanks

答:
None of these worked for me. I used

```<code>query.setMaxResults(300)
</code>```

It is the same as LIMIT in SQL but worked for me from Java code.

Title: search in the first 300 rows in sql

Body:
I'm using MS SQL Server Management Studio R2

suppose I have a table tableX with infinite records count,
and that table has a column colX, and the there's only 2 records in the whole table that have this colX not null,

what should the query look like?

I used

select top 10 * from tableX where colX isnot null

but it took forever executing the query

it there a way to search in the first 300 rows only?
thanks

Body:
None of these worked for me. I used

query.setMaxResults(300)

It is the same as LIMIT in SQL but worked for me from Java code.


问:
Javascript: Splice Multidimensional Object
I'm having this Object/Array Structure :

```<code>Obj = {
    "User": {
        "user1": [{
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
        }],

        "user2": [{
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
        },
        {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
        }],

        "user3": [{
            "desc": "whatever",
            "Id": 972878784
        }]
    }
}
</code>```

I want to filter out different values, dynamically (fixed in this example)
and if there are no Ids left, I want to delete the whole user Array.

For example, if I want to filter out the 2nd Array Element of user2:

```<code> for(var users in Obj) {
     for(var Ids in Obj[users]) {
         if(Obj[users][Ids].Id == 963346122){
             Obj[users][Ids].splice(0, 1); // ERROR HERE
         }
     }
     if(Obj[users][Ids] == undefined) {
         delete Obj[users];
     }
 }
</code>```

I get this Error:

User[users][Ids].splice(0, 1) is not a function

How to splice only the Array Element that I'm addressing, not the complete user2 Array?

答:
Use array.prototye.filter to remove user from array and use delete to remove the whole user array in case there is no element left:

var obj = {
    "User": {
        "user1": [
          {
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
          }
        ],
        "user2": [
          {
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
          },
          {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
          }
        ],
        "user3": [
          {
            "desc": "whatever",
            "Id": 972878784
          }
        ]
      }
    };

function deleteUser(id) {
    Object.keys(obj.User).forEach(user => {
        obj.User[user] = obj.User[user].filter(u => u.Id !== id);
        if (obj.User[user].length === 0) {
            delete obj.User[user];
        }
    });
}
deleteUser(963346121);
console.log(obj);
deleteUser(972878784);
console.log(obj);```

Body:
I'm having this Object/Array Structure :

Obj = {
    "User": {
        "user1": [{
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
        }],

        "user2": [{
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
        },
        {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
        }],

        "user3": [{
            "desc": "whatever",
            "Id": 972878784
        }]
    }
}

I want to filter out different values, dynamically (fixed in this example)
and if there are no Ids left, I want to delete the whole user Array.

For example, if I want to filter out the 2nd Array Element of user2:

 for(var users in Obj) {
     for(var Ids in Obj[users]) {
         if(Obj[users][Ids].Id == 963346122){
             Obj[users][Ids].splice(0, 1); // ERROR HERE
         }
     }
     if(Obj[users][Ids] == undefined) {
         delete Obj[users];
     }
 }

I get this Error:

User[users][Ids].splice(0, 1) is not a function

How to splice only the Array Element that I'm addressing, not the complete user2 Array?


问:
'App not Installed' Error on Android
I have a program working in the Android Emulator. Every now and again I have been creating a signed .apk and exporting it to my HTC Desire to test. It has all been fine.

On my latest exported .apk I get the error message 'App not installed' when I try to install the .apk. It runs fine on the emulators.

As I have mainly been testing on the emulators and only every now and again exporting to a real phone I am not sure when this happened. What is the likely cause of it not installing on a physical phone but running fine in the emulators?

I have tried rebooting the phone & removing the existing .apk, does not fix the fault.

答:
I faced the issue when I update my android from 2.3.2 to 3.0.1 . If this is the case the IDE will automatically considers the following points.

1.You cannot install an app with android:testOnly="true" by conventional means, such as from an Android file manager or from a download off of a Web site

2.Android Studio sets android:testOnly="true" on APKs that are run from

if you run your app directly connecting the device to your system, apk will install and run no problem.

if you sent this apk by copy from build out put and debug folder it will never install in the device.

Solution :go Build ---> Build APK(s) ---> copy the apk file share to your team

then your problem will solve.

Title: 'App not Installed' Error on Android


问:
How can I kill a whole process tree with Perl?
What's the best way to kill a process and all its child processes from a Perl script? It should run at least under Linux and Solaris, and not require installation of any additional packages.

My guess would be to get a list of all processes and their parents by parsing files in /proc or by parsing the output of ps (neither of which seems portable between Linux and Solaris); and then killing all processes in the tree (which seems prone to race conditions).

I could live with the race conditions in this particular case, but how do I portably get the process list?

答:
I adapted and hacked "rkill" to do the job, it was easy.

https://gitlab.com/pslist/pslist/blob/master/pslist

This is part of "pslist" package in e.g. ubuntu.

OwnerDisplayName: oliver

LastEditorDisplayName: brian d foy


问:
Python Tkinter label is not displaying correct ASCII values
The Hex value is converted into ASCII and displaying through Python tk library.And using Tkinter LabelFrame.

```<code>from Tkinter import *

root = Tk()

labelframe = LabelFrame(root, text="")
labelframe.pack(fill="both", expand="yes")

response = '62 F1 11 62 00 00 32 2D 31 34 45 30 39 39 2D 4D 41 30 31'
BResponse = response.replace(' ', '')
BResponse = BResponse.decode('hex')
BResponse = BResponse[3:]

left = Label(labelframe, text="ASCII Conversion::" +' '+ BResponse)
left.pack()

root.mainloop()
</code>```

Getting value: only first character.b

I am expecting the ASCII conversion b  2-14E099-MA01

Is tkinter support the ASCII value?

答:
The problem does not seem to be related to Tkinter at all. When I print the repr of the string, I get 'b\x00\x002-14E099-MA01', which seems correct given the two 00 bytes in positions 4 and 5. If you want those to be rendered as space, you could replace them accordingly:

```<code>>>> BResponse[3:].replace("\x00", " ")
'b  2-14E099-MA01'
</code>```

Update: There seems to have been a sort of misunderstanding: 00 is not a space, but a NULL byte. A space would be 32, i.e. 20 in Hex (not to be confused with the 32 you have, which is 50, i.e. 2).

```<code>>>> ord(" ")
32
>>> int("32", 16)
50
>>> chr(50)
'2'
</code>```

Body:
The Hex value is converted into ASCII and displaying through Python tk library.And using Tkinter LabelFrame.

from Tkinter import *

root = Tk()

labelframe = LabelFrame(root, text="")
labelframe.pack(fill="both", expand="yes")

response = '62 F1 11 62 00 00 32 2D 31 34 45 30 39 39 2D 4D 41 30 31'
BResponse = response.replace(' ', '')
BResponse = BResponse.decode('hex')
BResponse = BResponse[3:]

left = Label(labelframe, text="ASCII Conversion::" +' '+ BResponse)
left.pack()

root.mainloop()

Getting value: only first character.b

I am expecting the ASCII conversion b  2-14E099-MA01

Is tkinter support the ASCII value?

Body:
The problem does not seem to be related to Tkinter at all. When I print the repr of the string, I get 'b\x00\x002-14E099-MA01', which seems correct given the two 00 bytes in positions 4 and 5. If you want those to be rendered as space, you could replace them accordingly:

>>> BResponse[3:].replace("\x00", " ")
'b  2-14E099-MA01'

Update: There seems to have been a sort of misunderstanding: 00 is not a space, but a NULL byte. A space would be 32, i.e. 20 in Hex (not to be confused with the 32 you have, which is 50, i.e. 2).

>>> ord(" ")
32
>>> int("32", 16)
50
>>> chr(50)
'2'


问:
Database Date: How to auto increment the date automatically in a table?
I created a Database called DatesOfYear

```<code> CREATE TABLE DATESOFYEAR
 (
 MyName varchar(15),
 MyDate date
 );
</code>```

and i inserted a value in it

```<code> INSERT INTO DATESOFYEAR VALUES ('FName','1-JAN-2017');
</code>```

The output is

```<code> MYNAME     MYDATE
 FName      1-JAN-2017
</code>```

How do i increment the MyDate from 1-JAN-2017 up until the end of year which is 31-DEC-2017, the output that i want to see is

```<code> MYNAME     MYDATE
 FName      1-JAN-2017
 ....          ....
 FName      31-DEC-2017
</code>```

答:
One option:

```<code>DECLARE @StartDate date, @EndDate Date;
SELECT @StartDate = '20170101', @EndDate = '20171231';

WITH Dates AS(
    SELECT @StartDate AS MyDate
    UNION ALL
    SELECT DATEADD(DAY, 1,MyDate)
    FROM Dates
    WHERE DATEADD(DAY, 1,MyDate) <= @EndDate)
SELECT *
FROM Dates
OPTION (MAXRECURSION 366);
</code>```

You can then, if you wish, INSERT that dataset into another table, or use it as is.

Body:
I created a Database called DatesOfYear

 CREATE TABLE DATESOFYEAR
 (
 MyName varchar(15),
 MyDate date
 );

and i inserted a value in it

 INSERT INTO DATESOFYEAR VALUES ('FName','1-JAN-2017');

The output is

 MYNAME     MYDATE
 FName      1-JAN-2017

How do i increment the MyDate from 1-JAN-2017 up until the end of year which is 31-DEC-2017, the output that i want to see is

 MYNAME     MYDATE
 FName      1-JAN-2017
 ....          ....
 FName      31-DEC-2017

Body:
One option:

DECLARE @StartDate date, @EndDate Date;
SELECT @StartDate = '20170101', @EndDate = '20171231';

WITH Dates AS(
    SELECT @StartDate AS MyDate
    UNION ALL
    SELECT DATEADD(DAY, 1,MyDate)
    FROM Dates
    WHERE DATEADD(DAY, 1,MyDate) <= @EndDate)
SELECT *
FROM Dates
OPTION (MAXRECURSION 366);

You can then, if you wish, INSERT that dataset into another table, or use it as is.


问:
Convert Week Name to Date SQL
I am trying to convert the week numbers to actual dates based on my query:

Example: week 1 2017 should be converted to January 2, 2017

```<code>SELECT CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126) AS week_name,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate]
AND [Deleted] = 0 and [StageID] = 'D' AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate()) GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate]) ORDER BY DATEPART(YEAR,[DeliveryDate]) ASC, DATEPART(WEEK,[DeliveryDate]) ASC;
</code>```

This part:

```<code>CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126)
</code>```

came from this link.

But I check my data and I think it's not correct. I compared one to an Epoch Converter. For example: week 25 2017 should be June 19, 2017 but it's displaying June 26, 2017 and when I checked the date in the Epoch converter, it should be week 26 2017 and so on.

UPDATE

I have found a way to get what I want having this part:

```<code>CONVERT(varchar(10),dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4 - datepart(dw, dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4) + 1, 126)
</code>```

It gives me the week dates as Sundays but I want the week to start on Mondays so I added SET DATEFIRST 1. But right after adding it to my query, it forwards to the next monday. I was expecting it to be: June 18, 2017 (Sunday) into June 19, 2017 (Monday) but I get June 26, 2017 (Monday) instead.

What's wrong with my query?

答:
this is just and example on what i understood.
you can give various sample data and explain your outout.</p>

```<code>    declare @i varchar(50)='week 1 2017'

      select weekNumber,FOY,dateadd(day,-6,dateadd(week,cast(weekNumber as int),cast(FOY as datetime)))ReqDate
 from
 (
select substring(ltrim(replace(@i,'week','')),0,CHARINDEX(' ',ltrim(replace(@i,'week','')))) weekNumber,
right(@i,4) +'-01-01'FOY

)t4
</code>```

Title: Convert Week Name to Date SQL

Body:
I am trying to convert the week numbers to actual dates based on my query:

Example: week 1 2017 should be converted to January 2, 2017

SELECT CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126) AS week_name,
AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days FROM [CARGODB].[dbo].[Cargo_Transactions]
WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate]
AND [Deleted] = 0 and [StageID] = 'D' AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate()) GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate]) ORDER BY DATEPART(YEAR,[DeliveryDate]) ASC, DATEPART(WEEK,[DeliveryDate]) ASC;

This part:

CONVERT(nvarchar(10),DATEADD(day,DATEPART(WEEK,[DeliveryDate])*7-(DATEPART(WEEKDAY,CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01')-2),CAST(DATEPART(YEAR,[DeliveryDate]) as nvarchar(4))+'-01-01'),126)

came from this link.

But I check my data and I think it's not correct. I compared one to an Epoch Converter. For example: week 25 2017 should be June 19, 2017 but it's displaying June 26, 2017 and when I checked the date in the Epoch converter, it should be week 26 2017 and so on.

UPDATE

I have found a way to get what I want having this part:

CONVERT(varchar(10),dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4 - datepart(dw, dateadd (week, DATEPART(WEEK, [DeliveryDate]), dateadd (year, DATEPART(YEAR, [DeliveryDate])-1900, 0)) - 4) + 1, 126)

It gives me the week dates as Sundays but I want the week to start on Mondays so I added SET DATEFIRST 1. But right after adding it to my query, it forwards to the next monday. I was expecting it to be: June 18, 2017 (Sunday) into June 19, 2017 (Monday) but I get June 26, 2017 (Monday) instead.

What's wrong with my query?

Body:
this is just and example on what i understood.
you can give various sample data and explain your outout.

    declare @i varchar(50)='week 1 2017'

      select weekNumber,FOY,dateadd(day,-6,dateadd(week,cast(weekNumber as int),cast(FOY as datetime)))ReqDate
 from
 (
select substring(ltrim(replace(@i,'week','')),0,CHARINDEX(' ',ltrim(replace(@i,'week','')))) weekNumber,
right(@i,4) +'-01-01'FOY

)t4


问:
How to find all user list in Accurev? Is the there any API or CLI for fetching all user of SCM Accurev?
How to find all user list in Accurev? Is the there any API or CLI for fetching all user of Version control Accurev?

I am trying to track all the user in tool.

答:
Run the following command to list users in AccuRev.

accurev show users


问:
android grid view place items from right to left
I'm working on an android application with arabic version.

In one of the interfaces, I have gridView. So to display items in the correct order, I have to display items in the GridView from the right to the left (and of corse from the top to the bottom).
To do that, I tried to add these attributes in the GridView :

```<code>android:gravity="right"
android:layout_gravity="right"
</code>```

Unfortunately, items still displayed from the left to the right.

any idea to do it in the right way ?

答:
In addition to the above answer:

```<code>android:layoutDirection="rtl"
</code>```

Ideally, if you want to make it rtl aware, so only rtl in locales where it should be:

```<code>android:layoutDirection="locale"
</code>```

You can also make it follow the containing layout

```<code>android:layoutDirection="inherit"
</code>```

Body:
I'm working on an android application with arabic version.

In one of the interfaces, I have gridView. So to display items in the correct order, I have to display items in the GridView from the right to the left (and of corse from the top to the bottom).
To do that, I tried to add these attributes in the GridView :

android:gravity="right"
android:layout_gravity="right"

Unfortunately, items still displayed from the left to the right.

any idea to do it in the right way ?

Body:
In addition to the above answer:

android:layoutDirection="rtl"

Ideally, if you want to make it rtl aware, so only rtl in locales where it should be:

android:layoutDirection="locale"

You can also make it follow the containing layout

android:layoutDirection="inherit"


问:
When to use overloaded assignment operator?

Possible Duplicate:

  What is The Rule of Three?

When you require to define to your own assignment operator?

答:
Generally, you'll need to define your own assignment operator under the same circumstances when you need to define your own copy constructor - i.e. when a default copy won't cut it.  This happens in cases when your object manages dynamically allocated memory or other resources which need to be specially copied.

For example, if you have a class which manages a pointer that points to dynamically allocated memory, the default assignment operator will simply copy the pointer.  Generally, this is not what you want - you want each object instance to have its own internal copy of the allocated data, and so you'll need a special assignment operator that allocates its own memory and performs a copy.  This is, for example, what std::vector needs to do when copied or assigned.


问:
Android Studio cannot be initialized (0xc0000005)
I have just installed Android Studio in my new notebook running Windows 10 -  64 bits with Java SE 8 152, but it suddently it stopped working, like, every time I try to run the Android Studio, the error message below appears:

"The application cannot be initialized correctly (0xc0000005)"

I've already tried to reinstall, run as admin, deactivate the antivirus... nothing worked.

答: I had similar problem and disabling "Force randomization for images (Mandatory ASLR)" for studio64.exe in Windows Defender Security Center > App & browser control > Exploit protection > "Program settings" tab fixed this (you have to point to exact binary file with full path as using just executable name doesn't seem to work).</p>


问:
Why can't I access a button added to a custom info window added to a marker in Google Maps?
I'm creating a small app that will help a user find a sports club. Based on the type of sport picked from a spinner in the previous activity a number of markers representing different clubs will be shown on a map.(See screenshot below)

Results after a type of sport is clicked in a spinner

I've attempted to add a button to an information window (contains a title, and a snippet) of a marker in Google Maps that will start another activity. It will produce a toast pop up for now. At the moment I'm producing the following result:

App Screenshot (unable to embed image as reputation too low)

The issue I'm having is that I cannot interact with the button in the info window when I try to click the button the whole information window gets clicked instead (leads to the window changing from a white to a grey background to show it was clicked). This happens whether I try to click the button or any other section of the information window.

Grey background to signify info window was clicked

To do this I created an XML layout file (custom_window_info.xml) that would be displayed in the map activity in the event of a marker being clicked. It displays the title, snippet and the button method declared in the MapActivity.java class.

I then created a java class (CustomInfoWindowAdapter.java) that provided the java functionality for the layout file mentioned above, e.g. assigning the values to the title and snippet text fields, the getInfoWindow() and getInfoContents() methods, etc.

I'm not sure If I've approached this the wrong way entirely or I'm making a little mistake. Any tips/suggestions?

custom_window_info.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:padding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/title"
                android:layout_gravity="center_horizontal"
                android:ellipsize="end"
                android:maxLines="1"
                android:textColor="#000"
                android:textSize="14sp"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:id="@+id/snippet"
                android:maxLines="5" />

            <Button
                android:id="@+id/joinCLub"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="ClubButtonClick"
                android:text="Join Club"
                android:visibility="visible" />
        </LinearLayout>
    </LinearLayout>
</code>```

CustomInfoWindowAdapter.java

```<code>public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

private final View mWindow;
private Context mContext;

public CustomInfoWindowAdapter(Context context) {
    this.mContext = mContext;
    this.mWindow = LayoutInflater.from(context).inflate(R.layout.custom_info_window, null);
}

private void rendowWindowText(Marker marker, View v){

    String title = marker.getTitle();
    TextView clubtitle = (TextView) v.findViewById(R.id.title);

    if(!title.equals(" ")){
        clubtitle.setText(title);
    }

    String snippet = marker.getSnippet();
    TextView clubsnippet = (TextView) v.findViewById(R.id.snippet);

    if(!title.equals(" ")){
        clubsnippet.setText(snippet);
    }
}

@Override
public View getInfoWindow(Marker marker) {
    rendowWindowText(marker, mWindow);
    return mWindow;
}

@Override
public View getInfoContents(Marker marker) {
    rendowWindowText(marker, mWindow);
    return mWindow;
}

  }
</code>```

MapActivity.java

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

  private GoogleMap mMap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
  }

  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Assigning coordinates to a club (I've left out the 4 other markers to reduce the code)
    LatLng vincentsGAA = new LatLng(53.374042,-6.2300634);

    // Adding marker to map with the coordinates declared above, a title for the name of the club and a snippet for the address
    mMap.addMarker(new MarkerOptions().position(vincentsGAA).title("St Vincents GFC").snippet("Malahide Road, Dublin"));

    //Assigning the default coordinates to Dublin, Ireland when the map opens
    LatLng dublin = new LatLng(53.3242381,-6.385785);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dublin, 10));

    // Sets the custom info window to this map activity's markers
    mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity.this));
  }

  // This is the back button in the top right of the map activity that will
  // bring the user back to the previous activity that had the spinner that
  // allows the user to pick the type of sport they want to see clubs for
  public void ButtonClick(View v) {

     Intent intent1 = new Intent(this, Welcome_Activity.class);
     startActivity(intent1);

  }
}
</code>```

答:
Actually, it not possible, Google Map renders the content of your custom InfoWindow into an image and displays it to you as an Image. Therefore you set a click Listener only to the whole window and not to the Views inside it.

Your only choice is to set the ClickListener to the whole InfoWindow and popup a Dialog with clickable content you want, and not do it directly inside the InfoWindow.

From Google Docs: https://developers.google.com/maps/documentation/android/marker#info_windows

Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (e.g., after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However, you can listen to a generic click event on the whole info window as described in the section below.`

Body:
I'm creating a small app that will help a user find a sports club. Based on the type of sport picked from a spinner in the previous activity a number of markers representing different clubs will be shown on a map.(See screenshot below)

Results after a type of sport is clicked in a spinner

I've attempted to add a button to an information window (contains a title, and a snippet) of a marker in Google Maps that will start another activity. It will produce a toast pop up for now. At the moment I'm producing the following result:

App Screenshot (unable to embed image as reputation too low)

The issue I'm having is that I cannot interact with the button in the info window when I try to click the button the whole information window gets clicked instead (leads to the window changing from a white to a grey background to show it was clicked). This happens whether I try to click the button or any other section of the information window.

Grey background to signify info window was clicked

To do this I created an XML layout file (custom_window_info.xml) that would be displayed in the map activity in the event of a marker being clicked. It displays the title, snippet and the button method declared in the MapActivity.java class.

I then created a java class (CustomInfoWindowAdapter.java) that provided the java functionality for the layout file mentioned above, e.g. assigning the values to the title and snippet text fields, the getInfoWindow() and getInfoContents() methods, etc.

I'm not sure If I've approached this the wrong way entirely or I'm making a little mistake. Any tips/suggestions?

custom_window_info.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:padding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/title"
                android:layout_gravity="center_horizontal"
                android:ellipsize="end"
                android:maxLines="1"
                android:textColor="#000"
                android:textSize="14sp"
                android:textStyle="bold"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:id="@+id/snippet"
                android:maxLines="5" />

            <Button
                android:id="@+id/joinCLub"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="ClubButtonClick"
                android:text="Join Club"
                android:visibility="visible" />
        </LinearLayout>
    </LinearLayout>

CustomInfoWindowAdapter.java

public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

private final View mWindow;
private Context mContext;

public CustomInfoWindowAdapter(Context context) {
    this.mContext = mContext;
    this.mWindow = LayoutInflater.from(context).inflate(R.layout.custom_info_window, null);
}

private void rendowWindowText(Marker marker, View v){

    String title = marker.getTitle();
    TextView clubtitle = (TextView) v.findViewById(R.id.title);

    if(!title.equals(" ")){
        clubtitle.setText(title);
    }

    String snippet = marker.getSnippet();
    TextView clubsnippet = (TextView) v.findViewById(R.id.snippet);

    if(!title.equals(" ")){
        clubsnippet.setText(snippet);
    }
}

@Override
public View getInfoWindow(Marker marker) {
    rendowWindowText(marker, mWindow);
    return mWindow;
}

@Override
public View getInfoContents(Marker marker) {
    rendowWindowText(marker, mWindow);
    return mWindow;
}

  }

MapActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

  private GoogleMap mMap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
  }

  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Assigning coordinates to a club (I've left out the 4 other markers to reduce the code)
    LatLng vincentsGAA = new LatLng(53.374042,-6.2300634);

    // Adding marker to map with the coordinates declared above, a title for the name of the club and a snippet for the address
    mMap.addMarker(new MarkerOptions().position(vincentsGAA).title("St Vincents GFC").snippet("Malahide Road, Dublin"));

    //Assigning the default coordinates to Dublin, Ireland when the map opens
    LatLng dublin = new LatLng(53.3242381,-6.385785);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dublin, 10));

    // Sets the custom info window to this map activity's markers
    mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity.this));
  }

  // This is the back button in the top right of the map activity that will
  // bring the user back to the previous activity that had the spinner that
  // allows the user to pick the type of sport they want to see clubs for
  public void ButtonClick(View v) {

     Intent intent1 = new Intent(this, Welcome_Activity.class);
     startActivity(intent1);

  }
}