问:
Handle empty body parse error in fetch
I have some endpoint, which return response with no body. But in other api endpoints its returns body, so we handle our response like this:

```<code>//...api request
.then((response) => {
return response.json().then((json) => ({ json, response }));
}).then(({ json, response }) => {
if (!response.ok || (typeof(json) === 'boolean' && !json)) {
  json.code = response.status;
  return Promise.reject(json);
}
if (schema) {
  return { json: getNormalizedResponse(json, schema), status: response.status};
}
return { json, status: response.status};
});
</code>```

So it always raise error when we tries parse response with no body. How can I handle this moment?

UPD: It raises error on

```<code>return response.json().then((json) => ({ json, response }));
</code>```

string.

答:
I think you should change the order of check in your condition below. You also should check first that json should not be undefined or null.

```<code>if (!response.ok || (json && typeof(json) === 'boolean')) {
</code>```

Edit:

You should check the response at first place and then return should be modified like below:

```<code>.then((response) => {
  const json = response.json();
  return ( json ? response.json().then((json) => ({ json, response })) : '' );
}).then(({ json, response }) => {
if (!response.ok || (typeof(json) === 'boolean' && !json)) {
  json.code = response.status;
  return Promise.reject(json);
}
if (schema) {
  return { json: getNormalizedResponse(json, schema), status: response.status};
}
return { json, status: response.status};
});
</code>```

I am not sure what would you want to return in case response.json is undefined, so please modify it as per your need.

Title: Handle empty body parse error in fetch

Body:
I have some endpoint, which return response with no body. But in other api endpoints its returns body, so we handle our response like this:

//...api request
.then((response) => {
return response.json().then((json) => ({ json, response }));
}).then(({ json, response }) => {
if (!response.ok || (typeof(json) === 'boolean' && !json)) {
  json.code = response.status;
  return Promise.reject(json);
}
if (schema) {
  return { json: getNormalizedResponse(json, schema), status: response.status};
}
return { json, status: response.status};
});

So it always raise error when we tries parse response with no body. How can I handle this moment?

UPD: It raises error on

return response.json().then((json) => ({ json, response }));

string.

Body:
I think you should change the order of check in your condition below. You also should check first that json should not be undefined or null.

if (!response.ok || (json && typeof(json) === 'boolean')) {

Edit:

You should check the response at first place and then return should be modified like below:

.then((response) => {
  const json = response.json();
  return ( json ? response.json().then((json) => ({ json, response })) : '' );
}).then(({ json, response }) => {
if (!response.ok || (typeof(json) === 'boolean' && !json)) {
  json.code = response.status;
  return Promise.reject(json);
}
if (schema) {
  return { json: getNormalizedResponse(json, schema), status: response.status};
}
return { json, status: response.status};
});

I am not sure what would you want to return in case response.json is undefined, so please modify it as per your need.


来源: stackexchange

问:
Getting $index from option in ng-change inside select tag
I see there are a lot of questions similar to this one, but I couldn't find any that requires exactly what I have:

ngRepeat inside option-tag

ngChange inside select-tag

I need to get the index of selected option. This is my code

```<code><select data-placeholder="Choose" ng-model="pp.sif" name="myname" ng-change="onChangeSifra()">
    <option ng-repeat="item in sif.what track by $index" value="{{item.SIF}}">
        {{item.LABEL}}
    </option>
</select>
</code>```

ngClick inside option-tag doesn't work on Chrome and IE, so that is not an option.
ngOption (in select-tag) instead of ngRepeat (in option-tag) is not an option because sif.what is an array of objects; also, that is why I can't use indexOf function (ngModel has only part of this object).

Any ideas?

EDIT:
Since a lot of you are telling me to switch to ngOption, let me make it more clear why this isn't an option.
I iterate trough something like this:

```<code>$scope.sif.what = [
    {SIF: 1, LABEL: "label 1", SAVED: "save me 1"},
    {SIF: 2, LABEL: "label 2", SAVED: "save me 2"},
    {SIF: 3, LABEL: "label 3", SAVED: "save me 3"},
]
</code>```

So in a combobox I have "label" as label, "sif" as value, ngModel is the value of "sif", but on ngChange I need the entire object, sif.what(index), or $index.

Thanks.

答:
You can try this login

```<code><select ng-model="optIndex" ng-change="getIndex()">
<option ng-repeat="opt in opts" value={{$index}}></option>
<select>

$scope.getIndex = function(){console.log($scope.optIndex);}
</code>```

Now you can access your index using this snnipet :)

ContentLicense: CC BY-SA 3.0

Body:
I see there are a lot of questions similar to this one, but I couldn't find any that requires exactly what I have:

ngRepeat inside option-tag

ngChange inside select-tag

I need to get the index of selected option. This is my code

<select data-placeholder="Choose" ng-model="pp.sif" name="myname" ng-change="onChangeSifra()">
    <option ng-repeat="item in sif.what track by $index" value="{{item.SIF}}">
        {{item.LABEL}}
    </option>
</select>

ngClick inside option-tag doesn't work on Chrome and IE, so that is not an option.
ngOption (in select-tag) instead of ngRepeat (in option-tag) is not an option because sif.what is an array of objects; also, that is why I can't use indexOf function (ngModel has only part of this object).

Any ideas?

EDIT:
Since a lot of you are telling me to switch to ngOption, let me make it more clear why this isn't an option.
I iterate trough something like this:

$scope.sif.what = [
    {SIF: 1, LABEL: "label 1", SAVED: "save me 1"},
    {SIF: 2, LABEL: "label 2", SAVED: "save me 2"},
    {SIF: 3, LABEL: "label 3", SAVED: "save me 3"},
]

So in a combobox I have "label" as label, "sif" as value, ngModel is the value of "sif", but on ngChange I need the entire object, sif.what(index), or $index.

Thanks.

Body:
You can try this login

<select ng-model="optIndex" ng-change="getIndex()">
<option ng-repeat="opt in opts" value={{$index}}></option>
<select>

$scope.getIndex = function(){console.log($scope.optIndex);}

Now you can access your index using this snnipet :)


问:
How do I compile C# code as a library instead of an executable?
I have a C# console application in Visual Studio 2010. It has a Main() method as well as a bunch of utility classes. I'd like those utility classes to be available to other solutions. From reading online it seems that I need to compile it as a Class Library (DLL). So here's what I did:

Went in Visual Studio to "Project > [ProjectName] Properties > Application" and changed "Output type" from "Console Application" to "Class Library"

Rebuilt; ProjectName.dll was created in bin/Debug.

Created a new Console Application

Solution Explorer > Add Reference > browse to ProjectName.DLL, select it.

However, neither IntelliSense nor the Object Browser could find the classes inside that DLL.

I tried recompiling several different Console Applications as Class Libraries and got the same result. I also noticed that it works if I initially create the solution as a Class Library, but not if I convert it to one later.

Any tips?

答: Make sure that the classes in your dll project are public.</p>

ContentLicense: CC BY-SA 2.5


问:
How can I make this css animation smooth
In the below example you can see the boxes jumping a little bit, How can I make that transition smooth?

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

答:
Increment animation-delay on each .box, select them using nth-child() to add animation-delay individually which was already added,

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}
.box:nth-child(2){
  animation-delay:1s; /*This executes after 1st .box thus animation-delay for this should be 1s (i.e. overall animation time) */
}
.box:nth-child(3){
  animation-delay:2s; /*This executes after 2nd .box thus animation-delay for this should be 1s + 1s (i.e. overall animation time + delay of 2nd child) */
}
@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
Increment animation-delay on each .box, select them using nth-child() to add animation-delay individually which was already added,

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}
.box:nth-child(2){
  animation-delay:1s; /*This executes after 1st .box thus animation-delay for this should be 1s (i.e. overall animation time) */
}
.box:nth-child(3){
  animation-delay:2s; /*This executes after 2nd .box thus animation-delay for this should be 1s + 1s (i.e. overall animation time + delay of 2nd child) */
}
@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


问:
Can I have a 'protected' member in a parent class and inherit it in a child class?
I have 3 kinds of users like admin, customer, and supplier, which are all planned to be inherited from the User class. Can I use protected for username and password in the User class and inherit them in child classes? All tutorials seem to use private, is there any special reason for that?

答:
Can I use protected for username and password in user class

Yes

Whether you should is another question. If they are fields, they personally I'd say: keep the field private and add a protected property - or just simply:

```<code>protected string UserName {get;set;}
</code>```

or maybe:

```<code>protected string UserName {get;private set;}
</code>```

if only the base class should be able to set it, or

```<code>protected string UserName {get;}
</code>```

if only the base class should be able to set it and only in the constructor

Side note: any discussion of storing a password - even in memory - makes me nervous.

Body:
Can I use protected for username and password in user class

Yes

Whether you should is another question. If they are fields, they personally I'd say: keep the field private and add a protected property - or just simply:

protected string UserName {get;set;}

or maybe:

protected string UserName {get;private set;}

if only the base class should be able to set it, or

protected string UserName {get;}

if only the base class should be able to set it and only in the constructor

Side note: any discussion of storing a password - even in memory - makes me nervous.


问:
Hexadecimal entities are changed in UTF characters
In my XML some hexa decimal entities are there when i am transforming its changed into UTF - 8.

INPUT FILE:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

My XSLT:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

CURRENT OUTPUT:

```<code><root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

DESIRED OUTPUT:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>a text.</a>
    <b>b – text.</b>
</root>
</code>```

答:
Add Character map to your script as

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml" use-character-maps="entity"/>

    <xsl:character-map name="entity">
        <xsl:output-character character="–" string="&#x2013;"/>
    </xsl:character-map>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Output

```<code><?xml version="1.0" encoding="UTF-8"?>
    <root>
        <a>a text.</a>
        <b>b – text.</b>
    </root>
</code>```

See process http://xsltransform.hikmatu.com/6qM2e2b

Body:
In my XML some hexa decimal entities are there when i am transforming its changed into UTF - 8.

INPUT FILE:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    a text.
    b – text.
</root>

My XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

CURRENT OUTPUT:

<root>
    a text.
    b – text.
</root>

DESIRED OUTPUT:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    a text.
    b – text.
</root>

Body:
Add Character map to your script as

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml" use-character-maps="entity"/>

    <xsl:character-map name="entity">
        <xsl:output-character character="&#x2013;" string="&amp;#x2013;"/>
    </xsl:character-map>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Output

<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <a>a text.</a>
        <b>b &#x2013; text.</b>
    </root>

See process http://xsltransform.hikmatu.com/6qM2e2b


问:
get face skin tone color from image
i have tried below code that is returning me color of specific pixel which i have pass in argument

```<code>int x = (int)event.getX();
int y = (int)event.getY();
int pixel = bitmap.getPixel(x,y);

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

int[] color={redValue ,blueValue ,greenValue };
btn.setBackgroundColor(getHexColor(color));

public static int getHexColor(int[] color) {
return android.graphics.Color.rgb(color[0], color[1], color[2]);
}
</code>```

i have also try color palette following link is reference link that is also not returning perfect skin tone color of face

this is i have also tried

anyone have idea how to extract or get face skin tone color ??

答:
Use this

```<code>Matrix inverse = new Matrix();
                    v.getMatrix().invert(inverse);
                    float[] touchPoint = new float[] {event.getX(), event.getY()};
                    inverse.mapPoints(touchPoint);
                    int xCoord = (int) touchPoint[0];
                    int yCoord = (int) touchPoint[1];
                    int intColor = ((BitmapDrawable)imageView.getDrawable()).getBitmap().getPixel(xCoord,yCoord);

btn.setBackgroundColor(intColor);
</code>```

Hope This will help

OR

Simply Change this in you code, don't convert the color pixel to hex.
Use the color pixel directly in setBackGroundColor(pixel)
like

```<code>btn.setBackgroundColor(pixel);
</code>```

This is the full code i have tried

```<code>imageView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction()==(MotionEvent.ACTION_DOWN)){

            Matrix inverse = new Matrix();
            v.getMatrix().invert(inverse);
            float[] touchPoint = new float[] {event.getX(), event.getY()};
            inverse.mapPoints(touchPoint);
            int xCoord = (int) touchPoint[0];
            int yCoord = (int) touchPoint[1];
            int intColor = ((BitmapDrawable)imageView.getDrawable()).getBitmap().getPixel(xCoord ,yCoord );

            try {
                btn.setBackgroundColor(intColor);
            }catch (Exception e){
                e.printStackTrace();
            }

            return false;
        }
        return false;
    }
});
</code>```

Try catch is not necessary but i am putting it only for precaution for any unplanned error

Title: get face skin tone color from image

Body:
i have tried below code that is returning me color of specific pixel which i have pass in argument

int x = (int)event.getX();
int y = (int)event.getY();
int pixel = bitmap.getPixel(x,y);

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

int[] color={redValue ,blueValue ,greenValue };
btn.setBackgroundColor(getHexColor(color));

public static int getHexColor(int[] color) {
return android.graphics.Color.rgb(color[0], color[1], color[2]);
}

i have also try color palette following link is reference link that is also not returning perfect skin tone color of face

this is i have also tried

anyone have idea how to extract or get face skin tone color ??

Body:
Use this

Matrix inverse = new Matrix();
                    v.getMatrix().invert(inverse);
                    float[] touchPoint = new float[] {event.getX(), event.getY()};
                    inverse.mapPoints(touchPoint);
                    int xCoord = (int) touchPoint[0];
                    int yCoord = (int) touchPoint[1];
                    int intColor = ((BitmapDrawable)imageView.getDrawable()).getBitmap().getPixel(xCoord,yCoord);

btn.setBackgroundColor(intColor);

Hope This will help

OR

Simply Change this in you code, don't convert the color pixel to hex.
Use the color pixel directly in setBackGroundColor(pixel)
like

btn.setBackgroundColor(pixel);

This is the full code i have tried

imageView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction()==(MotionEvent.ACTION_DOWN)){

            Matrix inverse = new Matrix();
            v.getMatrix().invert(inverse);
            float[] touchPoint = new float[] {event.getX(), event.getY()};
            inverse.mapPoints(touchPoint);
            int xCoord = (int) touchPoint[0];
            int yCoord = (int) touchPoint[1];
            int intColor = ((BitmapDrawable)imageView.getDrawable()).getBitmap().getPixel(xCoord ,yCoord );

            try {
                btn.setBackgroundColor(intColor);
            }catch (Exception e){
                e.printStackTrace();
            }

            return false;
        }
        return false;
    }
});

Try catch is not necessary but i am putting it only for precaution for any unplanned error


问:
detecting a 404 on a http get and quickly handling it
I got this HTTP get request:

```<code>this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
          (response: Response) => {
            let apiResponse = JSON.parse(JSON.stringify(response));
            this.post_content = apiResponse.content.rendered;
            // do something with the this.post_content
          },
          (error: any) => {
            this.post_content = 'An error has occurred.';
        });
</code>```

If the URL is missing, and you already got a Failed to load resource: the server responded with a status of 404 (Not Found) message on the dev tools console.log, but yet, your code still showing the spinner, what are you supposed to do to quickly detect this and stop the wait and handle the 404 to say a message such as "That link does not exist"?

答:
You need to handle this in your error handler:</p>

```<code>this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
      (response: Response) => {
        let apiResponse = JSON.parse(JSON.stringify(response));
        this.post_content = apiResponse.content.rendered;
        // do something with the this.post_content
      },
      (error: any) => {
        this.post_content = 'An error has occurred: ' + error.message ;
        alert(this.post_content);
        //Code to stop spinner
    });
</code>```

Body:
I got this HTTP get request:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
          (response: Response) => {
            let apiResponse = JSON.parse(JSON.stringify(response));
            this.post_content = apiResponse.content.rendered;
            // do something with the this.post_content
          },
          (error: any) => {
            this.post_content = 'An error has occurred.';
        });

If the URL is missing, and you already got a Failed to load resource: the server responded with a status of 404 (Not Found) message on the dev tools console.log, but yet, your code still showing the spinner, what are you supposed to do to quickly detect this and stop the wait and handle the 404 to say a message such as "That link does not exist"?

Body:
You need to handle this in your error handler:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
      (response: Response) => {
        let apiResponse = JSON.parse(JSON.stringify(response));
        this.post_content = apiResponse.content.rendered;
        // do something with the this.post_content
      },
      (error: any) => {
        this.post_content = 'An error has occurred: ' + error.message ;
        alert(this.post_content);
        //Code to stop spinner
    });


问:
Import error with python gmond_python_modules in Ganglia
I used gmond_python_modules, trying to monitor one cluster having several hosts with each has 8 GPUs.

And after the last steps, I tried to restart gmond service on my web node, only to get:

```<code>Starting GANGLIA gmond: Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
ImportError: No module named site
                                                           [FAILED]
</code>```

I searched and thought initially it was because I compiled ganglia without --with-python option. But it wasn't. I recompiled with that option(checked configure output and it saied it found python) and everything works fine until I added GPU monitoring python module. Same error again.

And I also tried to manually assign PYTHONHOME and PYTHONPATH, which makes no difference.  I installed anaconda. Is it a possible reason that causes Ganglia not finding correct load path?

Any thoughts are welcome. And will offer more details if needed.

Distribution and version details:

System: centos 6.8

Python: 2.7 on web node, 2.6 on computing node

Ganglia: 3.7.2

gmond_python_modules: clone form Github today

答: See this post. The reason here is python-devel is not installed in calculating nodes, leadning to missing of 'python.h'. So ganglia configure script could not detect python support.

Body:
I used gmond_python_modules, trying to monitor one cluster having several hosts with each has 8 GPUs.

And after the last steps, I tried to restart gmond service on my web node, only to get:

Starting GANGLIA gmond: Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
ImportError: No module named site
                                                           [FAILED]

I searched and thought initially it was because I compiled ganglia without --with-python option. But it wasn't. I recompiled with that option(checked configure output and it saied it found python) and everything works fine until I added GPU monitoring python module. Same error again.

And I also tried to manually assign PYTHONHOME and PYTHONPATH, which makes no difference.  I installed anaconda. Is it a possible reason that causes Ganglia not finding correct load path?

Any thoughts are welcome. And will offer more details if needed.

Distribution and version details:

System: centos 6.8

Python: 2.7 on web node, 2.6 on computing node

Ganglia: 3.7.2

gmond_python_modules: clone form Github today


问:
Getting Same Rectangle Position from Scaled Small Size Image
I'm trying to process a large size image.Since the processing takes too much time to complete i'm resizing the image prior processing.After processing i'm drawing a rectangle on the small size image.How can i translate the the coordinates of this rectangle to original unscaled image ie:Draw the rectangle at the same position on the unscaled image.

I'm using the following code to resize the image

```<code>public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}
</code>```

This is what im trying to achieve

答:
```<code>Rectangle ConvertToLargeRect(Rectangle smallRect, Size largeImageSize, Size smallImageSize)
{
    double xScale = (double)largeImageSize.Width / smallImageSize.Width;
    double yScale = (double)largeImageSize.Height / smallImageSize.Height;
    int x = (int)(smallRect.X * xScale + 0.5);
    int y = (int)(smallRect.Y * yScale + 0.5);
    int right = (int)(smallRect.Right * xScale + 0.5);
    int bottom = (int)(smallRect.Bottom * yScale + 0.5);
    return new Rectangle(x, y, right - x, bottom - y);
}
</code>```

Body:
I'm trying to process a large size image.Since the processing takes too much time to complete i'm resizing the image prior processing.After processing i'm drawing a rectangle on the small size image.How can i translate the the coordinates of this rectangle to original unscaled image ie:Draw the rectangle at the same position on the unscaled image.

I'm using the following code to resize the image

public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}

This is what im trying to achieve


问:
Strategy for WCF server with .Net clients and Android clients?
I am using WCF to write a server that should be able to communicate with .Net clients, Android clients and possibly other types of clients.

The main type of client is a desktop application that will be written in .Net. This client will usually be on the same intranet as the server. It will make an initial call to the server to get the current state of the system and will then receive updates from the server whenever a value changes. These updates are frequent, perhaps once a second.

The Android clients will connect over the Internet. This client is also interested in updates, but it is not as critical as for the desktop client so a (less frequent) polling scenario might be acceptable.

All clients will have to login to use the services, and when connecting over the Internet the connection should be secure.

I am familiar with WCF but I am not sure what bindings are most appropriate for the scenario and what security solution to use. Also, I have not used Android, but I would like to make it as simple as possible for the person implementing the Android client to consume my services. So, what is my strategy?

答:
WCF via HTTP transport is the way to go because it is not binary and does not make assumptions re all peers are .net/windows.

see this page for more info


问:
I created a public account but all options are not available to me
Example: communicating with subscribers
enter image description here

what to do?

checked on all versions Viber and on all types of mobile phones but compared to the result there is no result

答:
1 : 1 communication with subscribers is reserved for chatbots or some CRM solutions that would allow agent chat.

You should read this part of documentation for a start.


问:
How to change the tint color of the clear button on a UITextField
I have an auto-generated clear button on my UITextfield, with the default blue tint color. I cannot change the tint color to white. I have tried modifying the storyboard and code without success, and I do not want to use a custom image.

How can I change the default clear button tint color without using a custom image?

答:
For Swift 4, add this to a subclass of UITextField: </p>

```<code>import UIKit

class CustomTextField: UITextField {

    override func layoutSubviews() {
        super.layoutSubviews()

        for view in subviews {
            if let button = view as? UIButton {
                button.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
                button.tintColor = .white
            }
        }
    }
}
</code>```

Body:
For Swift 4, add this to a subclass of UITextField:

import UIKit

class CustomTextField: UITextField {

    override func layoutSubviews() {
        super.layoutSubviews()

        for view in subviews {
            if let button = view as? UIButton {
                button.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
                button.tintColor = .white
            }
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Insert tag a right after img
Have look on this code:

```<code><a href="#" class="list-group-item">
    <span class="badge"><?=$st ?></span>
    <img class="small_profile_pic" src="<?=$pic ?>" /> aaa<a href="#"><?=$msg['UserName'] ?></a> :
</a>
</code>```

this is a row that show a message in short type. in this row I need to <?=$msg['UserName'] ?> be after image but it going to next line.
when I type word without a tag its OK but links goes to next line. How do I fix this?

more explanation on this pic:

Please notice that I can't use float, if there is another way except float please tell me that.

Edited:

(I have fixed that place by changing parent tag to span but ...)
I need to make whole row a link to that specific message and make username a link to user profile. Who can I place links inside each other?Or another solution maybe?

Second Edit

I have placed a tags inside each other and both of them works well but still second a tag goes to next line! I have tried display:inline but whole row collapsed!

答:
You can't use 'a' tag in "a" tag .... but just for you If you want to align it after image use style property and use ,</p>

```<code><a href="#" class="list-group-item">
    <span class="badge"><?=$st ?></span>
    <img class="small_profile_pic" src="<?=$pic ?>" style="display:inline" /> aaa<a href="#" style="display:inline"><?=$msg['UserName'] ?></a> :
</a>
</code>```

Title: Insert tag a right after img

Body:
Have look on this code:

    <?=$st ?>
    <img class="small_profile_pic" src="<?=$pic ?>" /> aaa<?=$msg['UserName'] ?> :

this is a row that show a message in short type. in this row I need to <?=$msg['UserName'] ?> be after image but it going to next line.
when I type word without a tag its OK but links goes to next line. How do I fix this?

more explanation on this pic:

Please notice that I can't use float, if there is another way except float please tell me that.

Edited:

(I have fixed that place by changing parent tag to span but ...)
I need to make whole row a link to that specific message and make username a link to user profile. Who can I place links inside each other?Or another solution maybe?

Second Edit

I have placed a tags inside each other and both of them works well but still second a tag goes to next line! I have tried display:inline but whole row collapsed!

Body:
You can't use 'a' tag in "a" tag .... but just for you If you want to align it after image use style property and use ,

<a href="#" class="list-group-item">
    <span class="badge"><?=$st ?></span>
    <img class="small_profile_pic" src="<?=$pic ?>" style="display:inline" /> aaa<a href="#" style="display:inline"><?=$msg['UserName'] ?></a> :
</a>


问:
How to move/rename file from internal app storage to external storage on Android?
I am downloading files from the internet and saving the streaming data to a temp file in my app's internal storage given by getFilesDir().

Once the download is complete, I need to move the temp file to my download directory on External Memory (usually an SD Card).  For some reason though, File.renameTo() isn't working for this.  I'm guessing there's a problem because it's two separate file systems, but I can still download directly to the SD Card and the file URIs are correct.

Is there another simple and quick way to transfer that file from internal memory to external or do I have to do a byte stream copy and delete the original?

答:
Internal and external memory is two different file systems. Therefore renameTo() fails.

You will have to copy the file and delete the original


问:
Recursively cycle every path of an array
I have the following(json) object:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);
</code>```

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

```<code>Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)
</code>```

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

```<code>foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
</code>```

答:
I have created simple recursive function.For your example. Store previous key values in one variable and add all data according to previous key and create new array.(which contain all previous keys as index and last element as value)   . Try following code:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

function traverse_array($array,$key="",$prev="",&$final_op=array())
{
  if(is_array($array))
  {
    $prev .= $key." - ";
    foreach ($array as $key => $value) {
      traverse_array($value,$key,$prev,$final_op);
    }
  }
  else
  {

    $prev =trim($prev," - ");
    $final_op[$prev][]=$array;
  }
  return $final_op;
}
$data = traverse_array($obj);
foreach ($data as $key => $value) {
  echo $key." (".implode(",", $value).")";
  echo PHP_EOL;
}
</code>```

DEMO

Body:
I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

Body:
I have created simple recursive function.For your example. Store previous key values in one variable and add all data according to previous key and create new array.(which contain all previous keys as index and last element as value)   . Try following code:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

function traverse_array($array,$key="",$prev="",&$final_op=array())
{
  if(is_array($array))
  {
    $prev .= $key." - ";
    foreach ($array as $key => $value) {
      traverse_array($value,$key,$prev,$final_op);
    }
  }
  else
  {

    $prev =trim($prev," - ");
    $final_op[$prev][]=$array;
  }
  return $final_op;
}
$data = traverse_array($obj);
foreach ($data as $key => $value) {
  echo $key." (".implode(",", $value).")";
  echo PHP_EOL;
}

DEMO


问:
How to read the changes in page (layout) in liferay DXP?
Is there any service to read  changes in page( layout) in liferay DXP?</p>

答:
Layout changes are stored in layout table in Liferay.

You can create Modal Listener that listen's event on a table.

It has methods like onAfterUpdate,onAfterCreate,onAfterRemove etc which might help you.

For details you can refer
https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/model-listeners


问:
Wordwrap not working correctly with NavMenu and Div
I created a ASP.Net Core Web Application with Angular in VS2017.
The initial application word wraps the way I want.
However after I added some HTML and styles the word wrap no longer works when the left panel is showing.

I found that the following HTML

```<code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>

<div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</code>```

causes the following display

How do I fix the effect of the Div?

答:
Try adding this css for wordwrap</p>

```<code>h2 {
    white-space: normal;}
</code>```

Body:
I created a ASP.Net Core Web Application with Angular in VS2017.
The initial application word wraps the way I want.
However after I added some HTML and styles the word wrap no longer works when the left panel is showing.

I found that the following HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

causes the following display

How do I fix the effect of the Div?

Body:
Try adding this css for wordwrap

h2 {
    white-space: normal;}


问:
Whats the difference between void function(stuct *s) vs void function(stuct s)?
I have this school homework to do and I'm confused because of the functions I am asked to make. It is different from the style I do singly-linked list.

I do singly linked-list like this:

```<code>typedef struct structNode{
    int data;
    struct structNode *next;
} node;

typedef struct structList{
    int count;
    struct structNode *head, *tail;
} list;

void insertFront(list *L, int x);
void insertRear(list *L, int x);
void insertAt(list *L, int x, int p);
void deleteFront(list *L);
void deleteRear(list *L);
void deleteAt(list *L, int p);
void displayAll(list *L);
</code>```

Where all arguments are receiving a pointer but my homework needs me to do my code like this:

```<code>typedef struct node *nodePtr;

struct node {
    int item;
    nodePtr next;
};

typedef nodePtr Statistician;

Statistician newStatistician();
  //allocates memory to the structure. Dynamic allocation
void destroyStatistician(Statistician *s);
  //destroys statistician
void add(Statistician s, int x);
  //Adds data to the rear
void remove(Statistician s, int x);
 //removes data
void displayData(Statistician s);
</code>```

So I'm confused whats the difference because I'm used to receiving pointers and the homework style is different.

I think the one with the receiving pointer is call by reference thats why what ever i edit locally can be edited globally...

And also how is my structure implementation different from the one I have to do?

答:
Statistician is a pointer. It is typedef'ed as nodePtr which in turn is defined as node*. So passing a Statistician is really passing a node*.

Whether it's smart from a usability standpoint to make a pointer look like a nonpointer is a different question.

Body:
I have this school homework to do and I'm confused because of the functions I am asked to make. It is different from the style I do singly-linked list.

I do singly linked-list like this:

typedef struct structNode{
    int data;
    struct structNode *next;
} node;

typedef struct structList{
    int count;
    struct structNode *head, *tail;
} list;

void insertFront(list *L, int x);
void insertRear(list *L, int x);
void insertAt(list *L, int x, int p);
void deleteFront(list *L);
void deleteRear(list *L);
void deleteAt(list *L, int p);
void displayAll(list *L);

Where all arguments are receiving a pointer but my homework needs me to do my code like this:

typedef struct node *nodePtr;

struct node {
    int item;
    nodePtr next;
};

typedef nodePtr Statistician;

Statistician newStatistician();
  //allocates memory to the structure. Dynamic allocation
void destroyStatistician(Statistician *s);
  //destroys statistician
void add(Statistician s, int x);
  //Adds data to the rear
void remove(Statistician s, int x);
 //removes data
void displayData(Statistician s);

So I'm confused whats the difference because I'm used to receiving pointers and the homework style is different.

I think the one with the receiving pointer is call by reference thats why what ever i edit locally can be edited globally...

And also how is my structure implementation different from the one I have to do?


问:
Why changeResourceRecordSets gets not authorized to access this resource?
I'm trying to create a new record in Route 53 of type Alias to tell Route 53 to sue CloudFront to serve the site. I'm trying to do this using the following code:

```<code>let options = {
    ChangeBatch: {
        Changes: [{
            Action: "CREATE",
            ResourceRecordSet: {
                AliasTarget: {
                    DNSName: '12kjh31k2hj3.cloudfront.net',
                    EvaluateTargetHealth: false,
                    HostedZoneId: 'JKEJWQHKJQWKK'
                },
                Name: 'example.com',
                Type: "A"
            }
        }],
        Comment: "S3 Hosted Site"
    },
    HostedZoneId: 'Z2FDTNDATAQYW2' // Fixed ID CloudFront distribution
};

route53.changeResourceRecordSets(options, function(error, data) {

    //
    //  1.  Check if there was an error
    //
    if(error)
    {
        return reject(error);
    }

    //
    //  -> Move to the next chain
    //
    return resolve(container);

});
</code>```

When I run this I get:

```<code>AccessDenied: User: arn:aws:iam::1234567:user/cli_s3_hosting is not authorized to access this resource
</code>```

If I use IAM Policy Simulator I have no issues as seen in the screenshot below.

I also tried to add AdminFullAccess and still I get the same error. What am I missing?

答: You have to swap the values of HostedZoneId's i.e. Z2FDTNDATAQYW2 should appear first and then your route53 hosted zone. The error is appearing since you are trying to change resource record set of the CF distribution hosted zone (Z2FDTNDATAQYW2) which does not belong to your account.</p>

Body:
I'm trying to create a new record in Route 53 of type Alias to tell Route 53 to sue CloudFront to serve the site. I'm trying to do this using the following code:

let options = {
    ChangeBatch: {
        Changes: [{
            Action: "CREATE",
            ResourceRecordSet: {
                AliasTarget: {
                    DNSName: '12kjh31k2hj3.cloudfront.net',
                    EvaluateTargetHealth: false,
                    HostedZoneId: 'JKEJWQHKJQWKK'
                },
                Name: 'example.com',
                Type: "A"
            }
        }],
        Comment: "S3 Hosted Site"
    },
    HostedZoneId: 'Z2FDTNDATAQYW2' // Fixed ID CloudFront distribution
};

route53.changeResourceRecordSets(options, function(error, data) {

    //
    //  1.  Check if there was an error
    //
    if(error)
    {
        return reject(error);
    }

    //
    //  -> Move to the next chain
    //
    return resolve(container);

});

When I run this I get:

AccessDenied: User: arn:aws:iam::1234567:user/cli_s3_hosting is not authorized to access this resource

If I use IAM Policy Simulator I have no issues as seen in the screenshot below.

I also tried to add AdminFullAccess and still I get the same error. What am I missing?


问:
Understanding jQuery (basic question)
i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

```<code>$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }
});
</code>```

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance

答: The 'not defined' message is coming from code that is using testFunction but is not waiting until it is defined.  You have enclosed the definition of testFunction in the documentReady event but not the user of testFunction.  </p>

Title: Understanding jQuery (basic question)

Body:
i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }
});

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance


问:
Return a Revenue Total from previous month using SSRS Expression
Is there a way to return previous month's Revenue as an Opening balance?
For Example:

Create an expression to pull the revenue field for all In progress deals on the last day of the previous month using an expression

I can get the the last day using this expression, however i dont know how to add in the revenue field

```<code>=dateadd("m",0,dateserial(year(Today),month(Today),0))
</code>```

Please can someone help me in pulling the total revenue recorded on last day of previous month?

答:
i just wanted to know if it is possible. i dont need a lecture.
A simple yes or No would suffice - i got it working.</p>

Body:
Is there a way to return previous month's Revenue as an Opening balance?
For Example:

Create an expression to pull the revenue field for all In progress deals on the last day of the previous month using an expression

I can get the the last day using this expression, however i dont know how to add in the revenue field

=dateadd("m",0,dateserial(year(Today),month(Today),0))

Please can someone help me in pulling the total revenue recorded on last day of previous month?


问:
C++ storing a const& to a temporary

Recently I have run into a problem in a project. The code there is much more complicated than the following example but I hope the problem (if there is one) is the same.

```<code>#include <iostream>
class mObject
{
public:
    mObject(){ std::cout << "mObject ctor\n"; }
    mObject(const mObject& other){ std::cout << "mObject copy ctor\n"; }
    ~mObject(){ std::cout << "mObject dtor\n"; }
};

struct cFoo{
    cFoo(const mObject& obj):obj_(obj){}
    const mObject& get() { return obj_;}
    const mObject& obj_;
};

mObject giveme() { return mObject(); }
void func2(const mObject& p) { mObject g = p; }

int main()
{
    cFoo k(giveme());
    func2(k.get());
    return 0;
}
</code>```

This gives me the following code:

```<code>mObject ctor
mObject dtor
mObject copy ctor
mObject dtor
</code>```

So the original "temporary" mObject instance dies before func2 usese it. I thought life time of a temporary object is extended if there is a const& to it. Assigning return of giveme() to a local const& in funtion main solves this problem. Then the temporary lives until the end of the main's scope. So what is going on here???

答: Within the same scope of the same function, you can extend the lifetime of an anonymous temporary by binding it to a const reference; for the avoidance of doubt this behaviour is not transitive across function calls.

Title: C++ storing a const& to a temporary

Body:
Recently I have run into a problem in a project. The code there is much more complicated than the following example but I hope the problem (if there is one) is the same.

#include <iostream>
class mObject
{
public:
    mObject(){ std::cout << "mObject ctor\n"; }
    mObject(const mObject& other){ std::cout << "mObject copy ctor\n"; }
    ~mObject(){ std::cout << "mObject dtor\n"; }
};

struct cFoo{
    cFoo(const mObject& obj):obj_(obj){}
    const mObject& get() { return obj_;}
    const mObject& obj_;
};

mObject giveme() { return mObject(); }
void func2(const mObject& p) { mObject g = p; }

int main()
{
    cFoo k(giveme());
    func2(k.get());
    return 0;
}

This gives me the following code:

mObject ctor
mObject dtor
mObject copy ctor
mObject dtor

So the original "temporary" mObject instance dies before func2 usese it. I thought life time of a temporary object is extended if there is a const& to it. Assigning return of giveme() to a local const& in funtion main solves this problem. Then the temporary lives until the end of the main's scope. So what is going on here???


问:
PHP Calling a model method multiple times with having different value for parameter in codeiginter
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

```<code>class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}
</code>```

My_controller.php

```<code>class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}
</code>```

答:
How about changing </p>

```<code>if($param = 'one'){
</code>```

<p>to </p>

```<code>if($param == 'one'){
</code>```

Body:
I created a method in the model to get data from the database and then call it in the controller for multiple time with different method parameters($param) values. This is working for only one parameter value which one comes first. I Know i am doing it in wrong way but i am unable to find the solution for this. please help.

Actually, I am trying to have category based on their type('wordpress', 'magento', 'shopify') form database

My_model.php

class My_model extends CI_Model{

  public function fun_name($param){
       return $this->db->get_where('categories', array('type' => '$param'));
  }

}

My_controller.php

class My_controller extends CI_Controller{
   public function get_data(){
       $this->load->model('my_model');
       $data = array(
           'first'   =>   $this->my_model->fun_name('wordpress'),
           'second'  =>   $this->my_model->fun_name('magento'),
           'third'   =>   $this->my_model->fun_name('shopify')
        );
       $this->load->view('index', $data);
   }
}

Body:
How about changing

if($param = 'one'){

to

if($param == 'one'){


问:
This.props returning undefined?
I'm currently passing data into my component via props, and for some reason it's showing up as undefined.
From my parent component perspective I have the following pass 2 props, data and header.

```<code>class ContractTable extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: []
    };
}

render() {
    return (
        <div>
            <p></p>
            <MuiThemeProvider>
                <TableTest
                    data={this.state.data}
                    header={[
                        {
                            name: "First Name",
                            prop: "firstName"
                        },
                        {
                            name: "Last Name",
                            prop: "lastName"
                        },
                        {
                            name: "Age",
                            prop: "age"
                        },
                        {
                            name: "Height",
                            prop: "height"
                        },
                        {
                            name: "Address",
                            prop: "address"
                        }
                    ]}
                />
            </MuiThemeProvider>
            <p></p>
        </div>
    );
}
</code>```

I try to grab the props and set it as my state, but when I log this.props.data or this.props.header it returns undefined. Why is this?

```<code>import React, { Component } from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';

class TableTest extends Component {
constructor(props) {
    super(props);

    this.state = {
        data: props.data,
        header: props.header
    }

    this.row = this.row.bind(this);
}

row = (currentValue, index, header) => (
    <TableRow key={`t-${index}`}>
        {
            header.map((headerName, index) => (
                <TableRowColumn key={`trc-${index}`}>
                    {currentValue[headerName.prop]}
                </TableRowColumn>
            ))
        }
    </TableRow>
);

render() {
    return 'hello'
}
}

export default TableTest;
</code>```

答:
Update: take a look https://jsfiddle.net/nroLmghv/

Just rendered simple table header.

Passing props to state is not a good approach.

I created a snippet. And it looks working. Point in which place do you have a problem. Or provide MuiThemeProvider and TableTest full code.

class Example extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            // mock value
            data: "some value"
        }
  }

  render() {
    return

      <TableTest
         data={this.state.data}
         header={[
        {
            name: "First Name",
            prop: "firstName"
        },
        {
            name: "Last Name",
            prop: "lastName"
        },
        {
            name: "Age",
            prop: "age"
        },
        {
            name: "Height",
            prop: "height"
        },
        {
            name: "Address",
            prop: "address"
        }
    ]}
    />

;
  }
}

class TableTest extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: this.props.data,
            header: this.props.header
        }

        console.log(this.state.data)
        console.log(this.state.header)
    }

    render() {
        return

;
    }
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div></code>```

Title: This.props returning undefined?

Body:
I'm currently passing data into my component via props, and for some reason it's showing up as undefined.
From my parent component perspective I have the following pass 2 props, data and header.

class ContractTable extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: []
    };
}

render() {
    return (

            <MuiThemeProvider>
                <TableTest
                    data={this.state.data}
                    header={[
                        {
                            name: "First Name",
                            prop: "firstName"
                        },
                        {
                            name: "Last Name",
                            prop: "lastName"
                        },
                        {
                            name: "Age",
                            prop: "age"
                        },
                        {
                            name: "Height",
                            prop: "height"
                        },
                        {
                            name: "Address",
                            prop: "address"
                        }
                    ]}
                />
            </MuiThemeProvider>

    );
}

I try to grab the props and set it as my state, but when I log this.props.data or this.props.header it returns undefined. Why is this?

import React, { Component } from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';

class TableTest extends Component {
constructor(props) {
    super(props);

    this.state = {
        data: props.data,
        header: props.header
    }

    this.row = this.row.bind(this);
}

row = (currentValue, index, header) => (
    <TableRow key={`t-${index}`}>
        {
            header.map((headerName, index) => (
                <TableRowColumn key={`trc-${index}`}>
                    {currentValue[headerName.prop]}
                </TableRowColumn>
            ))
        }
    </TableRow>
);

render() {
    return 'hello'
}
}

export default TableTest;

Body:
Update: take a look https://jsfiddle.net/nroLmghv/

Just rendered simple table header.

Passing props to state is not a good approach.

I created a snippet. And it looks working. Point in which place do you have a problem. Or provide MuiThemeProvider and TableTest full code.

class Example extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            // mock value
            data: "some value"
        }
  }

  render() {
    return <div>
      <TableTest
         data={this.state.data}
         header={[
        {
            name: "First Name",
            prop: "firstName"
        },
        {
            name: "Last Name",
            prop: "lastName"
        },
        {
            name: "Age",
            prop: "age"
        },
        {
            name: "Height",
            prop: "height"
        },
        {
            name: "Address",
            prop: "address"
        }
    ]}
    />
    </div>;
  }
}

class TableTest extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: this.props.data,
            header: this.props.header
        }

        console.log(this.state.data)
        console.log(this.state.header)
    }

    render() {
        return <div></div>;
    }
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>


问:
optimizing solution to find common third on large data set
This is a follow up question to my previous question. I run into a problem to find a memory efficient solution to find a common third for my large data set (3.5 million groups and 6.2 million persons)

The proposed solution using the igraph package works fast for a normal sized data sets unfortunately runs into memory issues by creating a large matrix for bigger data sets. Similar issue comes up with my own solution using concatenated inner joins where the third inner join inflates the dataframe so my pc runs out of memory (16gb).

```<code>    df.output <-   inner_join(df,df, by='group' ) %>%
      inner_join(.,df, by=c('person.y'='person')) %>%
      inner_join(.,df, by=c('group.y'='group')) %>%
      rename(person_in_common='person.y', pers1='person.x',pers2='person') %>%
      select(pers1,pers2,person_in_common) %>%
      filter(pers1!=pers2) %>%
      distinct() %>%
      filter(person_in_common!=pers1 & person_in_common!=pers2)

    df.output[-3] <- t(apply(df.output[-3], 1,
                             FUN=function(x) sort(x, decreasing=FALSE)))

    df.output <- unique(df.output)
</code>```

Small data set example and expected output

```<code>df <- data.frame(group= c("a","a","b","b","b","c"),
             person = c("Tom","Jerry","Tom","Anna","Sam","Nic"), stringsAsFactors = FALSE)

df
    group person
1     a    Tom
2     a  Jerry
3     b    Tom
4     b   Anna
5     b    Sam
6     c    Nic
</code>```

and expected result

```<code>df.output
  pers1 pers2 person_in_common
1  Anna Jerry              Tom
2 Jerry   Sam              Tom
3   Sam   Tom             Anna
4  Anna   Tom              Sam
6  Anna   Sam              Tom
</code>```

I unfortunately don't have access to a machine with more ram and are also not really experienced with cloud computing, so I hope to make it work on my local pc. I would appreciate input how to optimize any of the solutions or an advise how to tackle the problem otherwise.

Edit 1

A dataframe which reflects my actual data size.

```<code>set.seed(33)

Data <- data.frame(group = sample(1:3700000, 14000000, replace=TRUE),
                   person = sample(1:6800000, 14000000,replace = TRUE))
</code>```

Edit 2

My real data is a bit more complex in terms of larger groups and more persons per group as the example data. Consequently it gets more memory intense. I could not figure out how to simulate this kind of structure so following the real data for download:

Full person-group data

答:
So, I managed to run this on your test data (I have 16 GB of RAM), but if you run this on your small example then you would see that it does not give the same results.  I did not get why, but maybe you could hep me with that. So I will try to explain every step:

```<code>myFun <- function(dt) {
  require(data.table)
  # change the data do data.table:
  setDT(dt)
  # set key/order the data by group and person:
  setkey(dt, group, person)
  # I copy the initial data and change the name of soon to be merged column name to "p2"
  # which represents person2
  dta <- copy(dt)
  setnames(dta, "person", "p2")
  # the first merge using data.table:
  dt1 <- dt[dta, on = "group", allow.cartesian = TRUE, nomatch = 0]
  # now we remove rows where persons are the same:
  dt1 <- dt1[person != p2] # remove equal persons
  # and also we need to remove rows where person1 and person2 are the same,
  # just in different order , example:
  # 2:     a    Tom    Jerry
  # 3:     a  Jerry      Tom
  # is the same, if I get it right then you did this using apply in the end of code,
  # but it would be much better if we could reduce data now
  # also my approach will be much faster (we take pairwise min word to 2 column
  # and max to the last):
  l1 <- pmin(dt1[[2]], dt1[[3]])
  l2 <- pmax(dt1[[2]], dt1[[3]])
  set(dt1, j = 2L, value = l1)
  set(dt1, j = 3L, value = l2)
  # now lets clear memory and take unique rows of dt1:
  rm(l1, l2, dt)
  dt1 <- unique(dt1)
  gc()
  # change name for group column:
  setnames(dta, "group", "g2")
  # second merge:
  dt2 <- dt1[dta, on = "p2", allow.cartesian = TRUE, nomatch = 0]
  rm(dt1)
  gc()
  setnames(dta, "p2", "p3")
  dt3 <- dt2[dta, on = "g2", allow.cartesian = TRUE, nomatch = 0] # third merge
  rm(dt2)
  gc()
  dt3 <- dt3[p3 != p2 & p3 != person] # removing equal persons
  gc()
  dt3 <- dt3[, .(person, p2, p3)]
  gc()
  return(dt3[])
}
</code>```

On Small data set example:

```<code>df <- data.frame(group = c("a","a","b","b","b","c"),
                 person = c("Tom","Jerry","Tom","Anna","Sam","Nic"),
                 stringsAsFactors = FALSE)
df
myFun(df)
#    person  p2    p3
# 1:   Anna Tom Jerry
# 2:    Sam Tom Jerry
# 3:  Jerry Tom  Anna
# 4:    Sam Tom  Anna
# 5:  Jerry Tom   Sam
# 6:   Anna Tom   Sam
# 7:   Anna Sam   Tom
</code>```

Something similar to your result but not quite the same

Now with larger data:

```<code>set.seed(33)
N <- 10e6
dt <- data.frame(group = sample(3.7e6, N, replace = TRUE),
                 person = sample(6.8e6, N, replace = TRUE))
system.time(results <- myFun(dt)) # 13.22 sek

rm(results)
gc()
</code>```

And:

```<code>set.seed(33)
N <- 14e6
dt <- data.frame(group = sample(3.7e6, N, replace = TRUE),
                 person = sample(6.8e6, N, replace = TRUE))
system.time(results <- myFun(dt)) # around 40 sek, but RAM does get used to max
</code>```

Update:

Maybe you can try this splitting aproch, lets say with nparts 6-10?:

```<code>myFunNew3 <- function(dt, nparts = 2) {
  require(data.table)
  setDT(dt)
  setkey(dt, group, person)
  dta <- copy(dt)

  # split into N parts
  splits <- rep(1:nparts, each = ceiling(dt[, .N]/nparts))
  set(dt, j = "splits", value = splits)
  dtl <- split(dt, by = "splits", keep.by = F)
  set(dt, j = "splits", value = NULL)
  rm(splits)
  gc()

  i = 1
  for (i in seq_along(dtl)) {
    X <- copy(dtl[[i]])
    setnames(dta, c("group", "person"))
    X <- X[dta, on = "group", allow.cartesian = TRUE, nomatch = 0]
    X <- X[person != i.person]
    gc()
    X <- X[dta, on = "person", allow.cartesian = TRUE, nomatch = 0]
    gc()
    setnames(dta, "group", "i.group")
    X <- X[dta, on = "i.group", allow.cartesian = TRUE, nomatch = 0]
    gc()
    setnames(X, "i.person.1", "pers2")
    setnames(X, "i.person", "pers1" )
    setnames(X, "person", "person_in_common" )
    X <- X[, .(pers1, pers2, person_in_common)]
    gc()
    X <- X[pers1 != pers2 & person_in_common != pers1 & person_in_common != pers2]
    gc()
    name1 <- "pers1"
    name2 <- "pers2"
    l1 <- pmin(X[[name1]], X[[name2]])
    l2 <- pmax(X[[name1]], X[[name2]])
    set(X, j = name1, value = l1)
    set(X, j = name2, value = l2)
    rm(l1, l2)
    gc()
    X <- unique(X)
    gc()
    if (i > 1) {
      X1 <- rbindlist(list(X1, X), use.names = T, fill = T)
      X1 <- unique(X1)
      rm(X)
      gc()
    } else {
      X1 <- copy(X)
    }
    dtl[[i]] <- 0L
    gc()
  }
  rm(dta, dtl)
  gc()
  setkey(X1, pers1, pers2, person_in_common)
  X1[]
}
</code>```

Body:
This is a follow up question to my previous question. I run into a problem to find a memory efficient solution to find a common third for my large data set (3.5 million groups and 6.2 million persons)

The proposed solution using the igraph package works fast for a normal sized data sets unfortunately runs into memory issues by creating a large matrix for bigger data sets. Similar issue comes up with my own solution using concatenated inner joins where the third inner join inflates the dataframe so my pc runs out of memory (16gb).

    df.output <-   inner_join(df,df, by='group' ) %>%
      inner_join(.,df, by=c('person.y'='person')) %>%
      inner_join(.,df, by=c('group.y'='group')) %>%
      rename(person_in_common='person.y', pers1='person.x',pers2='person') %>%
      select(pers1,pers2,person_in_common) %>%
      filter(pers1!=pers2) %>%
      distinct() %>%
      filter(person_in_common!=pers1 & person_in_common!=pers2)

    df.output[-3] <- t(apply(df.output[-3], 1,
                             FUN=function(x) sort(x, decreasing=FALSE)))

    df.output <- unique(df.output)

Small data set example and expected output

df <- data.frame(group= c("a","a","b","b","b","c"),
             person = c("Tom","Jerry","Tom","Anna","Sam","Nic"), stringsAsFactors = FALSE)

df
    group person
1     a    Tom
2     a  Jerry
3     b    Tom
4     b   Anna
5     b    Sam
6     c    Nic

and expected result

df.output
  pers1 pers2 person_in_common
1  Anna Jerry              Tom
2 Jerry   Sam              Tom
3   Sam   Tom             Anna
4  Anna   Tom              Sam
6  Anna   Sam              Tom

I unfortunately don't have access to a machine with more ram and are also not really experienced with cloud computing, so I hope to make it work on my local pc. I would appreciate input how to optimize any of the solutions or an advise how to tackle the problem otherwise.

Edit 1

A dataframe which reflects my actual data size.

set.seed(33)

Data <- data.frame(group = sample(1:3700000, 14000000, replace=TRUE),
                   person = sample(1:6800000, 14000000,replace = TRUE))

Edit 2

My real data is a bit more complex in terms of larger groups and more persons per group as the example data. Consequently it gets more memory intense. I could not figure out how to simulate this kind of structure so following the real data for download:

Full person-group data

Body:
So, I managed to run this on your test data (I have 16 GB of RAM), but if you run this on your small example then you would see that it does not give the same results.  I did not get why, but maybe you could hep me with that. So I will try to explain every step:

myFun <- function(dt) {
  require(data.table)
  # change the data do data.table:
  setDT(dt)
  # set key/order the data by group and person:
  setkey(dt, group, person)
  # I copy the initial data and change the name of soon to be merged column name to "p2"
  # which represents person2
  dta <- copy(dt)
  setnames(dta, "person", "p2")
  # the first merge using data.table:
  dt1 <- dt[dta, on = "group", allow.cartesian = TRUE, nomatch = 0]
  # now we remove rows where persons are the same:
  dt1 <- dt1[person != p2] # remove equal persons
  # and also we need to remove rows where person1 and person2 are the same,
  # just in different order , example:
  # 2:     a    Tom    Jerry
  # 3:     a  Jerry      Tom
  # is the same, if I get it right then you did this using apply in the end of code,
  # but it would be much better if we could reduce data now
  # also my approach will be much faster (we take pairwise min word to 2 column
  # and max to the last):
  l1 <- pmin(dt1[[2]], dt1[[3]])
  l2 <- pmax(dt1[[2]], dt1[[3]])
  set(dt1, j = 2L, value = l1)
  set(dt1, j = 3L, value = l2)
  # now lets clear memory and take unique rows of dt1:
  rm(l1, l2, dt)
  dt1 <- unique(dt1)
  gc()
  # change name for group column:
  setnames(dta, "group", "g2")
  # second merge:
  dt2 <- dt1[dta, on = "p2", allow.cartesian = TRUE, nomatch = 0]
  rm(dt1)
  gc()
  setnames(dta, "p2", "p3")
  dt3 <- dt2[dta, on = "g2", allow.cartesian = TRUE, nomatch = 0] # third merge
  rm(dt2)
  gc()
  dt3 <- dt3[p3 != p2 & p3 != person] # removing equal persons
  gc()
  dt3 <- dt3[, .(person, p2, p3)]
  gc()
  return(dt3[])
}

On Small data set example:

df <- data.frame(group = c("a","a","b","b","b","c"),
                 person = c("Tom","Jerry","Tom","Anna","Sam","Nic"),
                 stringsAsFactors = FALSE)
df
myFun(df)
#    person  p2    p3
# 1:   Anna Tom Jerry
# 2:    Sam Tom Jerry
# 3:  Jerry Tom  Anna
# 4:    Sam Tom  Anna
# 5:  Jerry Tom   Sam
# 6:   Anna Tom   Sam
# 7:   Anna Sam   Tom

Something similar to your result but not quite the same

Now with larger data:

set.seed(33)
N <- 10e6
dt <- data.frame(group = sample(3.7e6, N, replace = TRUE),
                 person = sample(6.8e6, N, replace = TRUE))
system.time(results <- myFun(dt)) # 13.22 sek

rm(results)
gc()

And:

set.seed(33)
N <- 14e6
dt <- data.frame(group = sample(3.7e6, N, replace = TRUE),
                 person = sample(6.8e6, N, replace = TRUE))
system.time(results <- myFun(dt)) # around 40 sek, but RAM does get used to max

Update:

Maybe you can try this splitting aproch, lets say with nparts 6-10?:

myFunNew3 <- function(dt, nparts = 2) {
  require(data.table)
  setDT(dt)
  setkey(dt, group, person)
  dta <- copy(dt)

  # split into N parts
  splits <- rep(1:nparts, each = ceiling(dt[, .N]/nparts))
  set(dt, j = "splits", value = splits)
  dtl <- split(dt, by = "splits", keep.by = F)
  set(dt, j = "splits", value = NULL)
  rm(splits)
  gc()

  i = 1
  for (i in seq_along(dtl)) {
    X <- copy(dtl[[i]])
    setnames(dta, c("group", "person"))
    X <- X[dta, on = "group", allow.cartesian = TRUE, nomatch = 0]
    X <- X[person != i.person]
    gc()
    X <- X[dta, on = "person", allow.cartesian = TRUE, nomatch = 0]
    gc()
    setnames(dta, "group", "i.group")
    X <- X[dta, on = "i.group", allow.cartesian = TRUE, nomatch = 0]
    gc()
    setnames(X, "i.person.1", "pers2")
    setnames(X, "i.person", "pers1" )
    setnames(X, "person", "person_in_common" )
    X <- X[, .(pers1, pers2, person_in_common)]
    gc()
    X <- X[pers1 != pers2 & person_in_common != pers1 & person_in_common != pers2]
    gc()
    name1 <- "pers1"
    name2 <- "pers2"
    l1 <- pmin(X[[name1]], X[[name2]])
    l2 <- pmax(X[[name1]], X[[name2]])
    set(X, j = name1, value = l1)
    set(X, j = name2, value = l2)
    rm(l1, l2)
    gc()
    X <- unique(X)
    gc()
    if (i > 1) {
      X1 <- rbindlist(list(X1, X), use.names = T, fill = T)
      X1 <- unique(X1)
      rm(X)
      gc()
    } else {
      X1 <- copy(X)
    }
    dtl[[i]] <- 0L
    gc()
  }
  rm(dta, dtl)
  gc()
  setkey(X1, pers1, pers2, person_in_common)
  X1[]
}


问:
Widely used hashing algorithm in Java for implementing Hash tables?
I am implementing a basic HashTable data structure in Java without using collection framework and Arrays.

I intend to use individual nodes whose reference I would store in an array.

I am doing it this way:

Define a Node:

```<code>class Node {

    private int data;
    private String key;
    private Node next;
    // Other helper methods
}
</code>```

Create an array which would hold reference to pre-created Node objects:

```<code>public class MyHashTable {

    private Node[] nodeArray = new Node[100];

    public MyHashTable() {
        for(int i=0 ; i<100; i++) {
            nodeArray[i] = new Node();
        }
    }

    private int getIndex(String key) {
        long hashCode = key.hashCode();
        return  (int )hashCode%100;
    }

    // Other helper methods...
}
</code>```

For getting the hash-code, I am using the Java's inbuilt method -> hashCode().

It seems to be working fine, however for the case in which the key is "second", it returns a negative hash code and because of which the programs terminates with an exception.

My question is:

Is there any standard hashing algorithm which I can use for hashing and which is widely used? I am writing for learning purpose.

答:
You could use for example:

```<code>@Override
public int hashCode() {
    return 31 * data + ((key == null) ? 0 : key.hashCode());
}
</code>```

But you also need to implement equals.

Body:
I am implementing a basic HashTable data structure in Java without using collection framework and Arrays.

I intend to use individual nodes whose reference I would store in an array.

I am doing it this way:

Define a Node:

class Node {

    private int data;
    private String key;
    private Node next;
    // Other helper methods
}

Create an array which would hold reference to pre-created Node objects:

public class MyHashTable {

    private Node[] nodeArray = new Node[100];

    public MyHashTable() {
        for(int i=0 ; i<100; i++) {
            nodeArray[i] = new Node();
        }
    }

    private int getIndex(String key) {
        long hashCode = key.hashCode();
        return  (int )hashCode%100;
    }

    // Other helper methods...
}

For getting the hash-code, I am using the Java's inbuilt method -> hashCode().

It seems to be working fine, however for the case in which the key is "second", it returns a negative hash code and because of which the programs terminates with an exception.

My question is:

Is there any standard hashing algorithm which I can use for hashing and which is widely used? I am writing for learning purpose.

Body:
You could use for example:

@Override
public int hashCode() {
    return 31 * data + ((key == null) ? 0 : key.hashCode());
}

But you also need to implement equals.


问:
What to choose to store just one integer? Sqlite? or Text file?
I've build a small web-service in PHP. I want to control the number of calls to a specific API method.

I thought at first of using a text file, because it's just an integer. But after taking a good look at SQLite it seemed much more convenient.
So the code is just: get the "counter" from SQLite and increment it when that method is called, then store it back on SQLite db.

Is this a right way of doing it? Would it be simpler and more scalable to just use a file or... maybe something else?

Thanks in advance.

答: You could use shared memory to hold the counter, and locking to ensure safe increments.</p>

OwnerDisplayName: rogeriopvl

OwnerDisplayName: John Nilsson


问:
Android Button Inside PopupWindow
I have a popupwindow in my application that is meant to act as a sort of settings window.  Inside of this there will be a couple little views like checkboxes and what not, but I seem to be having a problem getting one to work properly.

Currently I only have one button in the view that it's inflating, and I'm trying to use it to close the popup window, but I am getting a NullPointerException when I try to setup the onClickListener.  In fact, if I refer to the button at all, even in something like "button.isShown()", it gives me the exception as if the button didn't exist.

I've tried everything I could think of, but nothing quite solves this problem.  I assume there would be a way to have working buttons inside a PopupWindow, or do I need to modify some form of dialog to get the effect I am after?

Thank you for your help.

答:
Make sure when you call findViewById(R.id.yourButton) that you are using Dialog.findViewById(id) otherwise its going to look on your main layout for the button, and not find it correctly, which will result in NullPointers when you attempt to use the reference.

Edit: here is dome code to make this more clear

```<code>    AlertDialog.Builder builder = new AlertDialog.Builder(this)
    .setView(layout);
    alertDialog = builder.create();
    alertDialog.show();
    button = (Button) alertDialog.findViewById(R.id.yourButton);
</code>```

Title: Android Button Inside PopupWindow

Body:
Make sure when you call findViewById(R.id.yourButton) that you are using Dialog.findViewById(id) otherwise its going to look on your main layout for the button, and not find it correctly, which will result in NullPointers when you attempt to use the reference.

Edit: here is dome code to make this more clear

    AlertDialog.Builder builder = new AlertDialog.Builder(this)
    .setView(layout);
    alertDialog = builder.create();
    alertDialog.show();
    button = (Button) alertDialog.findViewById(R.id.yourButton);


问:
Executing query with condition in java (response = Illegal operation on empty result set)
I have a problem, I want to execute query based on the condition. The concept is if the result is null, then execute another query. But when I try it, the result is an error

Illegal operation on empty result set`

My code:

```<code>String strSQL = "SELECT * FROM user WHERE userid=? AND password=? LIMIT 1;";

PreparedStatement pst=null;
pst = con.prepareStatement(strSQL);
pst.setString(1, userid);
pst.setString(2, password);

rs = pst.executeQuery();

if(rs.getString(1) == null && rs.getString(2) == null) {
   String strSQL = "SELECT userid FROM user WHERE userid=?;";
}

if(rs.next())
{
    yoyo yo = new yoyo();
    yo.SetUserid(rs.getString(1));
    yo.SetUsername(rs.getString(2));
    yo.SetPosisi(rs.getString(5));
    lstLogin = yo;
}
</code>```

答:
You have not executed the query when if(rs.getString(1) == null && rs.getString(2) == null) condition is true.

To solve this, change the if condition as following:

```<code>if(!rs.next()){
    strSQL = "SELECT userid FROM user WHERE userid=?;";
    pst = con.prepareStatement(strSQL);
    pst.setString(1, userid);
    rs = pst.executeQuery();
}
</code>```

Note: You have re-declared strSQL variable in if statement.

Body:
I have a problem, I want to execute query based on the condition. The concept is if the result is null, then execute another query. But when I try it, the result is an error

Illegal operation on empty result set`

My code:

String strSQL = "SELECT * FROM user WHERE userid=? AND password=? LIMIT 1;";

PreparedStatement pst=null;
pst = con.prepareStatement(strSQL);
pst.setString(1, userid);
pst.setString(2, password);

rs = pst.executeQuery();

if(rs.getString(1) == null && rs.getString(2) == null) {
   String strSQL = "SELECT userid FROM user WHERE userid=?;";
}

if(rs.next())
{
    yoyo yo = new yoyo();
    yo.SetUserid(rs.getString(1));
    yo.SetUsername(rs.getString(2));
    yo.SetPosisi(rs.getString(5));
    lstLogin = yo;
}

Body:
You have not executed the query when if(rs.getString(1) == null && rs.getString(2) == null) condition is true.

To solve this, change the if condition as following:

if(!rs.next()){
    strSQL = "SELECT userid FROM user WHERE userid=?;";
    pst = con.prepareStatement(strSQL);
    pst.setString(1, userid);
    rs = pst.executeQuery();
}

Note: You have re-declared strSQL variable in if statement.


Title: Python matplotlib.plot the pointe messed up due to the picture size?

Body:
Hey everyone! I use the python matplotlib.plot to draw a line

Here is my data

x = ['1000', '5950', '10900', '15850', '20800', '25750', '30700', '35650', '40600', '45550', '50500', '55450', '60400', '65350', '70300', '75250', '80200', '85150', '90100', '95050', '100000']
y = ['0.003383', '0.16341', '0.543723', '1.19463', '2.12827', '3.33978', '4.70849', '6.46607', '8.52736', '11.2711', '14.3101', '18.176', '26.1123', '32.0252', '31.692', '43.1399', '48.2962', '48.2436', '52.6464', '61.8072', '68.8354']

I write this in IPython

import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()

and it gived me this

check this

I mean, according to the x y list, it should a Increasing curve.

So, can someone can assist?
I will appreciate if you give any advice:)

Body:
This happens because the lists you are using contain strings. What you actually want are integers for x, and floats for y. In order to do this you can cast the contents of the lists to either int or float using a list comprehension.

import matplotlib.pyplot as plt

x = ['1000', '5950', '10900', '15850', '20800', '25750', '30700', '35650', '40600', '45550',
     '50500', '55450', '60400', '65350', '70300', '75250', '80200', '85150', '90100', '95050', '100000']
y = ['0.003383', '0.16341', '0.543723', '1.19463', '2.12827', '3.33978', '4.70849', '6.46607',
     '8.52736', '11.2711', '14.3101', '18.176', '26.1123', '32.0252', '31.692', '43.1399', '48.2962', '48.2436',
     '52.6464', '61.8072', '68.8354']

# Convert contents of lists
new_x = [int(i) for i in x]
new_y = [float(j) for j in y]

fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(x,y)
ax1.set_title("List of strings")

ax2.plot(new_x,new_y)
ax2.set_title("Lists have been converted")

plt.show()

Which produces:


问:
Properly Format a datetime-local form input via echo from MYSQL Table
I'm attempting to echo the value of arrivalDateTimeDest into a form so that the user can edit this value. I've attempted to accomplish this a few ways, however, the value that's echo's always equals mm/dd/yyyy --:-- --. What am I doing wrong? My attempts are listed below.

```<code><input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date_format($row['arrivalDateTimeDest'],'Y/m/d H:i:s')?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('Y/m/d H:i:s', $row['arrivalDateTimeDest'])?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('c', $row['arrivalDateTimeDest'])?>">
</code>```

In light of the recent answers to this post, I've pinpointed the issue, however I cannot yet solve it. When input type = text, I have no issue echoing the value, however, I cannot do this when the input type is set to datetime-local.

答:
strtotime doesn't handle mm/dd/yyyy correctly, try this

echo DateTime::createFromFormat("m/d/Y H:i s", $row['arrivalDateTimeDest'])->format("y-m-d");

so in your code it should look like this:

```<code><input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo DateTime::createFromFormat("m/d/Y H:i:s", $row['arrivalDateTimeDest'])->format("y-m-d")?>">
</code>```

make sure that this part: "m/d/Y H:i s" fits the format that you get from $row['arrivalDateTimeDest']

Body:
I'm attempting to echo the value of arrivalDateTimeDest into a form so that the user can edit this value. I've attempted to accomplish this a few ways, however, the value that's echo's always equals mm/dd/yyyy --:-- --. What am I doing wrong? My attempts are listed below.

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date_format($row['arrivalDateTimeDest'],'Y/m/d H:i:s')?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('Y/m/d H:i:s', $row['arrivalDateTimeDest'])?>">

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo date('c', $row['arrivalDateTimeDest'])?>">

In light of the recent answers to this post, I've pinpointed the issue, however I cannot yet solve it. When input type = text, I have no issue echoing the value, however, I cannot do this when the input type is set to datetime-local.

Body:
strtotime doesn't handle mm/dd/yyyy correctly, try this

echo DateTime::createFromFormat("m/d/Y H:i s", $row['arrivalDateTimeDest'])->format("y-m-d");

so in your code it should look like this:

<input type='datetime-local' id="arrivalDateTimeDest" name='arrivalDateTimeDest' value="<?php echo DateTime::createFromFormat("m/d/Y H:i:s", $row['arrivalDateTimeDest'])->format("y-m-d")?>">

make sure that this part: "m/d/Y H:i s" fits the format that you get from $row['arrivalDateTimeDest']


问:
stale element references in loop after redirection to another page
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

```<code>    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }
</code>```

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

答:
I would suggest to rewrite to something like this:</p>

```<code>goToCartridge(name) {
    $$('#dashboard .card.z-depth-1 h2').each((card, index) => {
        card.getText().then(text=> {
            if (name === text) {
                $(`cartridge-${index}`).click()
            }
        })
    })
}
</code>```

Body:
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

Body:
I would suggest to rewrite to something like this:

goToCartridge(name) {
    $$('#dashboard .card.z-depth-1 h2').each((card, index) => {
        card.getText().then(text=> {
            if (name === text) {
                $(`cartridge-${index}`).click()
            }
        })
    })
}


问:
Multithreading : the best way when write duplicated data
I use Spring, Java, Ibatis, Oracle.
I have 1 job which use multithreading to process a lot of data.

All threads will writing data to the same tables inside database, but some time the data of the threads are the same by contraint, like that :

```<code>CONSTRAINT n_uc1 UNIQUE (name, title, language, ...)
</code>```

. The example code like that :

```<code>public Long write(Input input) {
        Long key = read(input);
        if (key != null)
        {
            return key;
        }

        try
        {
            key = write(input);
        }
        catch (org.springframework.dao.DuplicateKeyException ex)
        {
            // if exception happend, it means already wrote data, read it again
            key = read(input);
        }
        return key;
    }
</code>```

With this code, I can get which I expected, but some time I got the exception, and it make the performance go down.

The rule are :

I can't update schema

I don't want to use synchronized, because it make the performance go down

Do you have any other solution for this ?
The performance is very important point.

答:
The description seems to be very vague but still attempting to answer.

If synchronization or removing the constraint is not an option, you may consider how you are feeding the data to the threads.

From the description what i understood is, sometimes more than 1 thread pick up the same data for processing.

If that is the case, you may come up with some logic to distribute the input data among threads than let the threads pick up input data randomly.

If you can give information about input data, its easy to give a solution

Body:
I use Spring, Java, Ibatis, Oracle.
I have 1 job which use multithreading to process a lot of data.

All threads will writing data to the same tables inside database, but some time the data of the threads are the same by contraint, like that :

CONSTRAINT n_uc1 UNIQUE (name, title, language, ...)

. The example code like that :

public Long write(Input input) {
        Long key = read(input);
        if (key != null)
        {
            return key;
        }

        try
        {
            key = write(input);
        }
        catch (org.springframework.dao.DuplicateKeyException ex)
        {
            // if exception happend, it means already wrote data, read it again
            key = read(input);
        }
        return key;
    }

With this code, I can get which I expected, but some time I got the exception, and it make the performance go down.

The rule are :

I can't update schema

I don't want to use synchronized, because it make the performance go down

Do you have any other solution for this ?
The performance is very important point.


答: I think that is because the scope of the test function is now the anonymous function you call on document ready. Declare testFunction outside that anonymous function.</p>

Title: Understanding jQuery (basic question)

Body:
i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }
});

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance