问:
Hello World is not displaying in react native android
Hi I have made Hello World program in react-native for android. I followed this https://facebook.github.io/react-native/docs/tutorial.html#content but it is not diplaying "Hello World" on screen when it launch app.

It is displaying empty screen. How can I fix this issue.

index.android.js

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text
} from 'react-native';

export default class AwesomeProject extends Component {
  render() {
    return (
        <Text>Hello World!</Text>
    );
  }
}

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

Build Logs

```<code>E:\React Programming\AwesomeProject>react-native run-android
Starting JS server...
Running C:\Users\ch-e00925\AppData\Local\Android\sdk/platform-tools/adb -s ZY223
8CX5L reverse tcp:8081 tcp:8081
Building and installing the app on the device (cd android && gradlew.bat install
Debug...
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0350Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug UP-TO-DATE
:app:validateDebugSigning
:app:packageDebug UP-TO-DATE
:app:zipalignDebug UP-TO-DATE
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'Moto G (4) - 6.0.1'
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 1 mins 9.699 secs
Starting the app on ZY2238CX5L (C:\Users\ch-e00925\AppData\Local\Android\sdk/pla
tform-tools/adb -s ZY2238CX5L shell am start -n com.awesomeproject/.MainActivity
)...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }
</code>```

Body:
Hi I have made Hello World program in react-native for android. I followed this https://facebook.github.io/react-native/docs/tutorial.html#content but it is not diplaying "Hello World" on screen when it launch app.

It is displaying empty screen. How can I fix this issue.

index.android.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text
} from 'react-native';

export default class AwesomeProject extends Component {
  render() {
    return (
        <Text>Hello World!</Text>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Build Logs

E:\React Programming\AwesomeProject>react-native run-android
Starting JS server...
Running C:\Users\ch-e00925\AppData\Local\Android\sdk/platform-tools/adb -s ZY223
8CX5L reverse tcp:8081 tcp:8081
Building and installing the app on the device (cd android && gradlew.bat install
Debug...
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42321Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore0110Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase0110Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp30110Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0350Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug UP-TO-DATE
:app:validateDebugSigning
:app:packageDebug UP-TO-DATE
:app:zipalignDebug UP-TO-DATE
:app:assembleDebug UP-TO-DATE
:app:installDebug
Installing APK 'app-debug.apk' on 'Moto G (4) - 6.0.1'
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 1 mins 9.699 secs
Starting the app on ZY2238CX5L (C:\Users\ch-e00925\AppData\Local\Android\sdk/pla
tform-tools/adb -s ZY2238CX5L shell am start -n com.awesomeproject/.MainActivity
)...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }

Body:
The problem is with expo  try adding a lot of characters to your text

<Text>Hello World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</Text>

You will see that the last part will be visible at top screen. The problem is basically the text is draw up out the display.(Status var hide the text!) If you look you could see the text back the status bar.


来源: stackexchange

问:
C++ "Pure virtual method called" with use of abstract baseclass
I am using a abstract baseclass with only pure virtual methods, to have a interface behavior (yes, I am coming from Java) in C++.
As far as I did my research this seems to be the way to go.

I have to abstract base classes, GraphReader and Graph.

```<code>class Graph{
   public:
   Graph() {};
   virtual ~Graph() {};
   virtual void layout() = 0;
   virtual std::vector<std::shared_ptr<Node>> getNodes() = 0;
   virtual std::vector<std::shared_ptr<Edge>> getEdges() = 0;

   protected:

};

class GraphReader{
   public:
   GraphReader(std::string fileName_) :
         fileName(fileName_) {};
   virtual ~GraphReader() {};
   virtual Graph* read() = 0;

   protected:
   std::string fileName;
};
</code>```

These both have derived classes that inherit from GraphReader/Graph.

```<code>class OgdfGraph : public Graph{
   public:
   OgdfGraph();
   virtual ~OgdfGraph();
   void setOgdfGraph(ogdf::Graph &oGraph);
   std::vector<std::shared_ptr<Node>> getNodes();
   std::vector<std::shared_ptr<Edge>> getEdges();
   void layout();

   private:
   [...]

};

class OgdfGmlReader : public GraphReader {
   public:
   OgdfGmlReader(std::string fileName);
   virtual ~OgdfGmlReader();
   Graph* read();
};
</code>```

With the read() function returning the Graph* value as follows:

```<code>Graph* OgdfGmlReader::read() {

   [...]

   OgdfGraph og;
   og.setOgdfGraph(G);
   Graph* graph = &og;

   return graph;
}
</code>```

In my main I do the following:

```<code>   OgdfGmlReader tr = OgdfGmlReader("../data/lesmiserables.gml");
   GraphReader* gr = &tr;
   Graph* graph = gr->read();

   graph->layout();
</code>```

The loading of the graph works, but when I call the layout function on graph, I get the following error (on runtime, it compiles):

```<code>pure virtual method called
terminate called without an active exception
Aborted (core dumped)
</code>```

Does this problem come from the fact that I return the Graph and I am not directly before it assigning the derived class to its parent class as with the GraphReader?
I am the most confused as it works for the GraphReader but not for the Graph (returned from the GraphReader), as it is quite the same for my understanding.

Any help how to solve this issue (while possibly maintaining the inheritance architecture) is greatly appreciated!

Thank you very much in advance!

答:
The problem is in Read function:

The instance of  OgdfGraph og is local variable which is assigned to graph is returned from Read function. Please note that the variable og will go out of scope and deleted once Read function has executed. Hence graph will remain just a pointer to Graph* without any valid instance allocated to it.

You can fix it by changing OgdfGraph og as OgdfGraph* pog = new OgdfGraph()

ContentLicense: CC BY-SA 3.0

Body:
I am using a abstract baseclass with only pure virtual methods, to have a interface behavior (yes, I am coming from Java) in C++.
As far as I did my research this seems to be the way to go.

I have to abstract base classes, GraphReader and Graph.

class Graph{
   public:
   Graph() {};
   virtual ~Graph() {};
   virtual void layout() = 0;
   virtual std::vector<std::shared_ptr<Node>> getNodes() = 0;
   virtual std::vector<std::shared_ptr<Edge>> getEdges() = 0;

   protected:

};

class GraphReader{
   public:
   GraphReader(std::string fileName_) :
         fileName(fileName_) {};
   virtual ~GraphReader() {};
   virtual Graph* read() = 0;

   protected:
   std::string fileName;
};

These both have derived classes that inherit from GraphReader/Graph.

class OgdfGraph : public Graph{
   public:
   OgdfGraph();
   virtual ~OgdfGraph();
   void setOgdfGraph(ogdf::Graph &oGraph);
   std::vector<std::shared_ptr<Node>> getNodes();
   std::vector<std::shared_ptr<Edge>> getEdges();
   void layout();

   private:
   [...]

};

class OgdfGmlReader : public GraphReader {
   public:
   OgdfGmlReader(std::string fileName);
   virtual ~OgdfGmlReader();
   Graph* read();
};

With the read() function returning the Graph* value as follows:

Graph* OgdfGmlReader::read() {

   [...]

   OgdfGraph og;
   og.setOgdfGraph(G);
   Graph* graph = &og;

   return graph;
}

In my main I do the following:

   OgdfGmlReader tr = OgdfGmlReader("../data/lesmiserables.gml");
   GraphReader* gr = &tr;
   Graph* graph = gr->read();

   graph->layout();

The loading of the graph works, but when I call the layout function on graph, I get the following error (on runtime, it compiles):

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

Does this problem come from the fact that I return the Graph and I am not directly before it assigning the derived class to its parent class as with the GraphReader?
I am the most confused as it works for the GraphReader but not for the Graph (returned from the GraphReader), as it is quite the same for my understanding.

Any help how to solve this issue (while possibly maintaining the inheritance architecture) is greatly appreciated!

Thank you very much in advance!


问:
Calculating values in dynamically created DOM
I have created an html table that is dynamically created in the DOM.  It has 4 columns and two of the columns will have tetboxes that a user can enter values into and then will be subtracted as a value in the last column.  'Delta' = 'State Before' - 'State After'.  I am able to get the value when it is entered but not sure how to get the value of the other field to do the computation.

HTML

```<code>    <table id="deptState" border="1">
    <tr>
        <th>Department</th>
        <th>State Before</th>
        <th>State After</th>
        <th>Delta</th>
    </tr>
</table>
</code>```

JAVASCRIPT

```<code>   var deptArray = ["Human Resources", "Accounting and Finance", "IT", "Marketing", "Purchasing Department"];
var state = ["stateBefore", "stateAfter", "Delta"];

for(var x=0; x<deptArray.length; x++) {
    var html = "<tr>";
        html +="<td>"+deptArray[x]+"</td>";
        for(var y=0; y<state.length; y++) {
            if (state[y] === "stateBefore")
            {
                html += "<td><input type='text' class='.nrm-text' id='"+deptArray[x]+state[0]+"'></td>";
            }else if (state[y] === "stateAfter") {
                html += "<td><input type='text' class='.nrm-text' id='"+deptArray[x]+state[1]+"'></td>";
            }else if (state[y] === "Delta") {
                html += "<td><input type='text' id='"+deptArray[x]+state[2]+"'></td>";
            }
        }
      html += "</tr>";
      $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
  console.dir(allTextBoxes);
  allTextBoxes.addEventListener("change", function( e ){
    if (e.target.tagName === 'INPUT'){
              alert("Value: "+document.getElementById(e.target.id).value);
            console.log("Save data to SharePoint list");
    }
  })
</code>```

It's easier to show.  Here's the jsfiddle:

In one of the rows, enter 9 in 'State Before' and 5 in 'State After'.  'Delta' should then have 4

http://jsfiddle.net/isogunro/pq4uref9/

答:
use a common class:

```<code>  var deptArray = ["Human Resources", "Accounting and Finance", "IT",
  "Marketing", "Purchasing Department"];
  var state = ["stateBefore", "stateAfter", "Delta"];

 for(var x=0; x<deptArray.length; x++) {
var html = "<tr>";
    html +="<td>"+deptArray[x]+"</td>";
    for(var y=0; y<state.length; y++) {
        if (state[y] === "stateBefore")
        {
            html += "<td><input type='text' class='nrm-text state-before' id='"+deptArray[x]+state[0]+"'></td>";
        }else if (state[y] === "stateAfter") {
            html += "<td><input type='text' class='nrm-text state-after' id='"+deptArray[x]+state[1]+"'></td>";
        }else if (state[y] === "Delta") {
            html += "<td><input type='text' class='delta' id='"+deptArray[x]+state[2]+"'></td>";
        }
    }
  html += "</tr>";
  $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
   console.dir(allTextBoxes);
   allTextBoxes.addEventListener("change", function( e ){
   if (e.target.tagName === 'INPUT'){
          alert("Value: "+document.getElementById(e.target.id).value);
        console.log("Save data to SharePoint list");
   }
 });
</code>```

Now get the current rows delta value once we enter after State After:

```<code>$('.state-after').focusout(function(){
  var stateBefore=$(this).closest('tr').find('.state-before').val();
  var stateAfter=$(this).closest('tr').find('.state-after').val();
  var delta=(stateBefore-stateAfter);
  $(this).closest('tr').find('.delta').val(delta);
  console.log(delta);
});
</code>```

Check the updated fiddle:

Body:
I have created an html table that is dynamically created in the DOM.  It has 4 columns and two of the columns will have tetboxes that a user can enter values into and then will be subtracted as a value in the last column.  'Delta' = 'State Before' - 'State After'.  I am able to get the value when it is entered but not sure how to get the value of the other field to do the computation.

HTML

        Department
        State Before
        State After
        Delta

JAVASCRIPT

   var deptArray = ["Human Resources", "Accounting and Finance", "IT", "Marketing", "Purchasing Department"];
var state = ["stateBefore", "stateAfter", "Delta"];

for(var x=0; x<deptArray.length; x++) {
    var html = "
";
        html +=""+deptArray[x]+"	";
        for(var y=0; y<state.length; y++) {
            if (state[y] === "stateBefore")
            {
                html += "<input type='text' class='.nrm-text' id='"+deptArray[x]+state[0]+"'>	";
            }else if (state[y] === "stateAfter") {
                html += "<input type='text' class='.nrm-text' id='"+deptArray[x]+state[1]+"'>	";
            }else if (state[y] === "Delta") {
                html += "<input type='text' id='"+deptArray[x]+state[2]+"'>	";
            }
        }
      html += "
";
      $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
  console.dir(allTextBoxes);
  allTextBoxes.addEventListener("change", function( e ){
    if (e.target.tagName === 'INPUT'){
              alert("Value: "+document.getElementById(e.target.id).value);
            console.log("Save data to SharePoint list");
    }
  })

It's easier to show.  Here's the jsfiddle:

In one of the rows, enter 9 in 'State Before' and 5 in 'State After'.  'Delta' should then have 4

http://jsfiddle.net/isogunro/pq4uref9/

Body:
use a common class:

  var deptArray = ["Human Resources", "Accounting and Finance", "IT",
  "Marketing", "Purchasing Department"];
  var state = ["stateBefore", "stateAfter", "Delta"];

 for(var x=0; x<deptArray.length; x++) {
var html = "<tr>";
    html +="<td>"+deptArray[x]+"</td>";
    for(var y=0; y<state.length; y++) {
        if (state[y] === "stateBefore")
        {
            html += "<td><input type='text' class='nrm-text state-before' id='"+deptArray[x]+state[0]+"'></td>";
        }else if (state[y] === "stateAfter") {
            html += "<td><input type='text' class='nrm-text state-after' id='"+deptArray[x]+state[1]+"'></td>";
        }else if (state[y] === "Delta") {
            html += "<td><input type='text' class='delta' id='"+deptArray[x]+state[2]+"'></td>";
        }
    }
  html += "</tr>";
  $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
   console.dir(allTextBoxes);
   allTextBoxes.addEventListener("change", function( e ){
   if (e.target.tagName === 'INPUT'){
          alert("Value: "+document.getElementById(e.target.id).value);
        console.log("Save data to SharePoint list");
   }
 });

Now get the current rows delta value once we enter after State After:

$('.state-after').focusout(function(){
  var stateBefore=$(this).closest('tr').find('.state-before').val();
  var stateAfter=$(this).closest('tr').find('.state-after').val();
  var delta=(stateBefore-stateAfter);
  $(this).closest('tr').find('.delta').val(delta);
  console.log(delta);
});

Check the updated fiddle:


问:
EditText in Listview loses focus when pressed on Android 4.x
I know there are a lot of similar questions out here
but I couldn't get any of the provided solutions working in a simple sample app.

The problem occurs when the softkeyboard is shown for the first time. As soon as it is shown, only by pressing the editText again makes it editable.

Tried the following:

```<code> android:windowSoftInputMode="adjustPan|adjustResize"
</code>```

This is not solving any issues. It seems that this line is mandatory to have the activity resized after the softkeyboard is popping up. Unfortunately, it's also causing any EditTexts to lose focus. This is probably to the ListView itself gaining focus after the resizing process. So I tried the following workaround:

```<code> listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
</code>```

This always causes the first visible EditText that the ListView contains to gain focus, which is undesirable. The second EditText in the second row should instead gain focus when pressed, which is not happening. Also, if I eventually managed to focus another EditText other then the first one shown (e.g. by pressing 'Next' on the softkeyboard), the first visible one will receive focus after the keyboard is dismissed and the ListView being resized to its full size again.

I tried several other things like intercepting onFocusChange() events for the ListView, while knowing which EditText was pressed by its TouchListener. Requesting the focus for that certain EditText again did not lead to any success either.

Using a ScrollView instead of a ListView as suggested by other users is not an option either for the concerned project.

答:
I was having the same problem with recyclerView and trying all suggested solutions.

Finally, the problem on my case was that the recyclerView had wrap_content as value for the height on my XML by accident; changed it to match_parent and started working as expected, no focusable value set and using android:windowSoftInputMode="adjustResize"

Body:
I know there are a lot of similar questions out here
but I couldn't get any of the provided solutions working in a simple sample app.

The problem occurs when the softkeyboard is shown for the first time. As soon as it is shown, only by pressing the editText again makes it editable.

Tried the following:

 android:windowSoftInputMode="adjustPan|adjustResize"

This is not solving any issues. It seems that this line is mandatory to have the activity resized after the softkeyboard is popping up. Unfortunately, it's also causing any EditTexts to lose focus. This is probably to the ListView itself gaining focus after the resizing process. So I tried the following workaround:

 listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

This always causes the first visible EditText that the ListView contains to gain focus, which is undesirable. The second EditText in the second row should instead gain focus when pressed, which is not happening. Also, if I eventually managed to focus another EditText other then the first one shown (e.g. by pressing 'Next' on the softkeyboard), the first visible one will receive focus after the keyboard is dismissed and the ListView being resized to its full size again.

I tried several other things like intercepting onFocusChange() events for the ListView, while knowing which EditText was pressed by its TouchListener. Requesting the focus for that certain EditText again did not lead to any success either.

Using a ScrollView instead of a ListView as suggested by other users is not an option either for the concerned project.


问:
Unpacking s3.ObjectSummary from bucket.objects.all() iteration
I'm using boto3 to download files from s3, and i'm trying to unpack the values from bucket.objects.all() iteration:

```<code>bucket = boto3.Session(profile_name='default').resource('s3').Bucket(bucket_name)
for (bucket_name, key) in zip(bucket.objects.all()):
   print(bucket_name, key)
</code>```

But this is returning the following error:

```<code>ValueError: not enough values to unpack (expected 2, got 1)
</code>```

What I'm doing wrongly?

答:
You can try this part instead of zip(bucket.objects.all()):

```<code>map(lambda x: (x.bucket_name, x.key), bucket.objects.all())
</code>```

the function map allows to apply the function lambda (first parameter) to each members of the second parameter
bucket.objects.all() which returns a list of ObjectSummary.

map returns a list you can loop

The lambda returns a tuple of 2 values so that you can unpack them.

Body:
I'm using boto3 to download files from s3, and i'm trying to unpack the values from bucket.objects.all() iteration:

bucket = boto3.Session(profile_name='default').resource('s3').Bucket(bucket_name)
for (bucket_name, key) in zip(bucket.objects.all()):
   print(bucket_name, key)

But this is returning the following error:

ValueError: not enough values to unpack (expected 2, got 1)

What I'm doing wrongly?

Body:
You can try this part instead of zip(bucket.objects.all()):

map(lambda x: (x.bucket_name, x.key), bucket.objects.all())

the function map allows to apply the function lambda (first parameter) to each members of the second parameter
bucket.objects.all() which returns a list of ObjectSummary.

map returns a list you can loop

The lambda returns a tuple of 2 values so that you can unpack them.


问:
Create model and association in Sequelize and Epilogue

Desired behaviour

Using Epilogue JS and Sequelize, I have two resources, Student and Course, that have a m2m relationship. I would like to create a new Student and associate that student instance with an existing course.

The problem

When I POST a new student and include course information in the payload, Epilogue/Sequelize will attempt to create the new student and create new courses based on the nested payload. This will cause a validation error because those courses already exist.

Code example

```<code>const Student = db.define('student', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

const Course = db.define('course', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

Student.belongsToMany(Course, {through: 'student_courses'});
Course.belongsToMany(Student, {through: 'student_courses'});

const StudentResource = epilogue.resource({
  model: Student,
  endpoints: ['/student', '/student/:id'],
  include: [{
    model: Course
  }];
});
</code>```

I want to POST a new student and associate with an existing course, e.g.:

```<code>// POST /users/
{
  name: "Sally",
  courses: [
    {id: 123, name: "math"},
    {id: 456, name: "science"}
  ]
}
</code>```

However, Epilogue/Sequelize will fail because these courses already exist:

```<code>{
    "message": "Validation error",
    "errors": [
        {
            "field": "id",
            "message": "id must be unique"
        }
    ]
}
</code>```

答:
Not very aquinted with how epilogue works, but doing it purely via sequelize, you can use the set<Association> methods

Something along the lines,

```<code>student = model.student.create(/*some properties*/)
student.setCourse(course_id)
</code>```

More about it, in this issue

Body:
Desired behaviour

Using Epilogue JS and Sequelize, I have two resources, Student and Course, that have a m2m relationship. I would like to create a new Student and associate that student instance with an existing course.

The problem

When I POST a new student and include course information in the payload, Epilogue/Sequelize will attempt to create the new student and create new courses based on the nested payload. This will cause a validation error because those courses already exist.

Code example

const Student = db.define('student', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

const Course = db.define('course', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

Student.belongsToMany(Course, {through: 'student_courses'});
Course.belongsToMany(Student, {through: 'student_courses'});

const StudentResource = epilogue.resource({
  model: Student,
  endpoints: ['/student', '/student/:id'],
  include: [{
    model: Course
  }];
});

I want to POST a new student and associate with an existing course, e.g.:

// POST /users/
{
  name: "Sally",
  courses: [
    {id: 123, name: "math"},
    {id: 456, name: "science"}
  ]
}

However, Epilogue/Sequelize will fail because these courses already exist:

{
    "message": "Validation error",
    "errors": [
        {
            "field": "id",
            "message": "id must be unique"
        }
    ]
}

Body:
Not very aquinted with how epilogue works, but doing it purely via sequelize, you can use the set<Association> methods

Something along the lines,

student = model.student.create(/*some properties*/)
student.setCourse(course_id)

More about it, in this issue


问:
How do I change the color of text wrapped only in
 tags with CSS?
OK, specifically, I’ve got a div with some text in it on my Wordpress blog and I’m trying to figure out the custom CSS to change the text color.

```<code><div class=“foo-bar">
  Some text here
</div>
</code>```

I’m sure this is some beginner mistake, but for some reason when I write

```<code>.foo-bar {

  color: #abc;

}
</code>```

Nothing changes. Variations of the color attribute aren’t changing anything either.

NOTE: Because I’m using WP Customizer UI I can’t change the HTML

答:
I am not sure if you have had some sort of copy and paste error, but the quotes surrounding your class don't match.  You start with “ and finish with ".  Make them both ".</p>

```<code><div class="foo-bar">
  Some text here
</div>
</code>```

Title: How do I change the color of text wrapped only in <div> tags with CSS?

Body:
OK, specifically, I’ve got a div with some text in it on my Wordpress blog and I’m trying to figure out the custom CSS to change the text color.

  Some text here

I’m sure this is some beginner mistake, but for some reason when I write

.foo-bar {

  color: #abc;

}

Nothing changes. Variations of the color attribute aren’t changing anything either.

NOTE: Because I’m using WP Customizer UI I can’t change the HTML

Body:
I am not sure if you have had some sort of copy and paste error, but the quotes surrounding your class don't match.  You start with “ and finish with ".  Make them both ".

<div class="foo-bar">
  Some text here
</div>


问:
Rewriting one part of a URL into a link
I am trying to get one part of a URL to insert into another.

URL in address bar will read domain.com/test.php?/12345 then link in page must become domain.com/do/Login/12345 (this end number will change for every user)

(Note that I can't change the URL domain.com/test.php?/12345 as this has already been set by the site owner.)

For the URLs above I had to remove the http://www. part above as new user can't submit more than one link for spam prevention. The final script should include http://www.

You will be able to see that all I need to get is the number at the end ie 12345 but I'm not too sure how to achieve this (javascript beginner). This is what I have so far:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Path test</title>
</head>

<body>

<script>
// get URL eg http://www.domain.com/test.php?/12345
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>

<script>
//write new domain then add user number ie 12345
document.write('http://www.domain.com/do/Login/' + window.location.pathname);
</script>
</body>
</html>
</code>```

This obviously does not work but shows where I got to.

I've had some luck using a script I found at http://www.sitepoint.com/forums/showthread.php?t=244955 but it only worked with filenames with an extension name on like .html, .php etc.

Any ideas?

Thanks in advance.

答:
First, you need to get the part of the url after the question mark. This is available in the

```<code> window.location.search
</code>```

variable. Note that that already includes the "/". Then you need to create the actual link. document.write('http://...) won't work because that will just write it in text form and will not be an actual anchor tag. For that you need something like:

```<code>document.getElementById("yourLink").href = "http://domain.com/do/Login" + window.location.search
</code>```

don't forget to put an anchor tag in the html with an id that matches the element in the getElementById() method above. If you don't want to put an anchor tag in your html markup, you can create one with javascript with something like:

```<code>var link = document.createElement('a');
link.href = "http://domain.com/do/Login" + window.location.search;
document.body.appendChild(link);
</code>```

This may need further adjusting to your needs.

ContentLicense: CC BY-SA 2.5

Title: Rewriting one part of a URL into a link

Body:
I am trying to get one part of a URL to insert into another.

URL in address bar will read domain.com/test.php?/12345 then link in page must become domain.com/do/Login/12345 (this end number will change for every user)

(Note that I can't change the URL domain.com/test.php?/12345 as this has already been set by the site owner.)

For the URLs above I had to remove the http://www. part above as new user can't submit more than one link for spam prevention. The final script should include http://www.

You will be able to see that all I need to get is the number at the end ie 12345 but I'm not too sure how to achieve this (javascript beginner). This is what I have so far:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Path test</title>

This obviously does not work but shows where I got to.

I've had some luck using a script I found at http://www.sitepoint.com/forums/showthread.php?t=244955 but it only worked with filenames with an extension name on like .html, .php etc.

Any ideas?

Thanks in advance.

Body:
First, you need to get the part of the url after the question mark. This is available in the

 window.location.search

variable. Note that that already includes the "/". Then you need to create the actual link. document.write('http://...) won't work because that will just write it in text form and will not be an actual anchor tag. For that you need something like:

document.getElementById("yourLink").href = "http://domain.com/do/Login" + window.location.search

don't forget to put an anchor tag in the html with an id that matches the element in the getElementById() method above. If you don't want to put an anchor tag in your html markup, you can create one with javascript with something like:

var link = document.createElement('a');
link.href = "http://domain.com/do/Login" + window.location.search;
document.body.appendChild(link);

This may need further adjusting to your needs.


问:
Saving a file asynchronously in ASP.NET Core causing exceptions with DbContext
I have an application that saves document information for customers. I am trying to add functionality to allow users to upload PDFs and have them saved to disk. I am using the recommended code found here and here.

When the code works, everything looks good -- the document entity is saved to the database and the uploaded file is saved to disk. However, I am getting sporadic exceptions thrown -- things like System.ObjectDisposedException ("Cannot access a disposed object"), sometimes a DbUpdate exception saying a reference is null, etc... I can reproduce the issue, but not 100% every time and not with the same exception every time.

I suspect this is somehow being caused by using CopyToAsync when saving the file. I am not very experienced with async code and I may be doing something obviously wrong. If I change the method to use the synchronous CopyTo instead, it seems to fix the problem. I'm trying to understand why this is happening.

I am injecting my repo and DbContext using AutoFac. Here is the code for the service method which is called by the controller:

```<code>public async Task<int> SaveDocument(DocumentDetailDto dto, string user, string webRoot)
{
     documentToSave = new Document();

     // Code not shown that maps dto to new document and adds it to context

     if (dto.FileUpload != null && dto.FileUpload.Length > 0)
     {
          var fileName = $"{dto.CustomerId}-{dto.DocumentTypeId}-{DateTime.Now.Ticks}.pdf";

          var filePath = Path.Combine(webRoot, "uploads");

          using (var fileStream = new FileStream(Path.Combine(filePath, fileName), FileMode.Create))
          {
               await dto.FileUpload.CopyToAsync(fileStream);
          }
     }

     _repo.Save(user);

     return documentToSave.Id;
}
</code>```

Do you see anything obviously wrong with this setup? Is there anything special I need to do when using async with a FileStream right before calling save on the context? I'm still trying to debug the errors, but it almost seems like the issue is some kind of conflict between the open FileStream and the DbContext trying to write to the database. Any ideas to try are most welcome!

Edited to add some additional code:

Here is how I am registering the DbContext in Startup.cs:

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
     services.AddMvc();

     // Add DbContext
     var connection = Configuration.GetConnectionString("DefaultConnection");

     services.AddDbContext<DocContext>(
                options => options.UseSqlServer(connection, b => b.MigrationsAssembly("InfrastructureLayer")));

      // Add repository
      services.AddScoped<IRepository, EntityFrameworkRepository<DocContext>>();

      services.AddTransient<IResolveUserService, ResolveUserService>();

      // Autofac setup
      var containerBuilder = new ContainerBuilder();
      containerBuilder.RegisterModule<ServiceLayer.AutofacModule>();
      containerBuilder.Populate(services);
      var container = containerBuilder.Build();
      return new AutofacServiceProvider(container);
 }
</code>```

Here is the Save method in the repo:

```<code>public virtual void Save(string user = "")
{
     var modifiedEntries = Context.ChangeTracker.Entries<IEntity>()
          .Where(x => x.State == EntityState.Modified)
          .Select(x => x.Entity)
          .ToList();

     foreach (var entity in modifiedEntries)
     {
          entity.ModifiedDate = DateTime.UtcNow;
          entity.ModifiedBy = user;
     }

     var newEntries = Context.ChangeTracker.Entries<IEntity>()
          .Where(x => x.State == EntityState.Added)
          .Select(x => x.Entity)
          .ToList();

     foreach (var entity in newEntries)
     {
          entity.CreatedDate = DateTime.UtcNow;
          entity.CreatedBy = user;
     }

     Context.SaveChanges();
}
</code>```

And here is how the SaveDocument method is called from the controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Save(DocumentDetailDto dto, [FromServices]IResolveUserService userService, [FromServices]IHostingEnvironment environment)
{
     _service.SaveDocument(dto, userService.GetUser(), environment.WebRootPath);

     return RedirectToAction("Detail", "Customers", new { id = dto.CustomerId });
}
</code>```

Thanks!

答:
You should await for _service.SaveDocument to complete. Currently you start it and does not wait its results. Instead you send successful response to user, request is processed, used resources may be disposed at any moment.

Change your controller action to:

```<code>public async Task<IActionResult> Save(...
{
     await _service.SaveDocument(...

     return RedirectToAction(...
}
</code>```

Body:
I have an application that saves document information for customers. I am trying to add functionality to allow users to upload PDFs and have them saved to disk. I am using the recommended code found here and here.

When the code works, everything looks good -- the document entity is saved to the database and the uploaded file is saved to disk. However, I am getting sporadic exceptions thrown -- things like System.ObjectDisposedException ("Cannot access a disposed object"), sometimes a DbUpdate exception saying a reference is null, etc... I can reproduce the issue, but not 100% every time and not with the same exception every time.

I suspect this is somehow being caused by using CopyToAsync when saving the file. I am not very experienced with async code and I may be doing something obviously wrong. If I change the method to use the synchronous CopyTo instead, it seems to fix the problem. I'm trying to understand why this is happening.

I am injecting my repo and DbContext using AutoFac. Here is the code for the service method which is called by the controller:

public async Task<int> SaveDocument(DocumentDetailDto dto, string user, string webRoot)
{
     documentToSave = new Document();

     // Code not shown that maps dto to new document and adds it to context

     if (dto.FileUpload != null && dto.FileUpload.Length > 0)
     {
          var fileName = $"{dto.CustomerId}-{dto.DocumentTypeId}-{DateTime.Now.Ticks}.pdf";

          var filePath = Path.Combine(webRoot, "uploads");

          using (var fileStream = new FileStream(Path.Combine(filePath, fileName), FileMode.Create))
          {
               await dto.FileUpload.CopyToAsync(fileStream);
          }
     }

     _repo.Save(user);

     return documentToSave.Id;
}

Do you see anything obviously wrong with this setup? Is there anything special I need to do when using async with a FileStream right before calling save on the context? I'm still trying to debug the errors, but it almost seems like the issue is some kind of conflict between the open FileStream and the DbContext trying to write to the database. Any ideas to try are most welcome!

Edited to add some additional code:

Here is how I am registering the DbContext in Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
     services.AddMvc();

     // Add DbContext
     var connection = Configuration.GetConnectionString("DefaultConnection");

     services.AddDbContext<DocContext>(
                options => options.UseSqlServer(connection, b => b.MigrationsAssembly("InfrastructureLayer")));

      // Add repository
      services.AddScoped<IRepository, EntityFrameworkRepository<DocContext>>();

      services.AddTransient<IResolveUserService, ResolveUserService>();

      // Autofac setup
      var containerBuilder = new ContainerBuilder();
      containerBuilder.RegisterModule<ServiceLayer.AutofacModule>();
      containerBuilder.Populate(services);
      var container = containerBuilder.Build();
      return new AutofacServiceProvider(container);
 }

Here is the Save method in the repo:

public virtual void Save(string user = "")
{
     var modifiedEntries = Context.ChangeTracker.Entries<IEntity>()
          .Where(x => x.State == EntityState.Modified)
          .Select(x => x.Entity)
          .ToList();

     foreach (var entity in modifiedEntries)
     {
          entity.ModifiedDate = DateTime.UtcNow;
          entity.ModifiedBy = user;
     }

     var newEntries = Context.ChangeTracker.Entries<IEntity>()
          .Where(x => x.State == EntityState.Added)
          .Select(x => x.Entity)
          .ToList();

     foreach (var entity in newEntries)
     {
          entity.CreatedDate = DateTime.UtcNow;
          entity.CreatedBy = user;
     }

     Context.SaveChanges();
}

And here is how the SaveDocument method is called from the controller:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Save(DocumentDetailDto dto, [FromServices]IResolveUserService userService, [FromServices]IHostingEnvironment environment)
{
     _service.SaveDocument(dto, userService.GetUser(), environment.WebRootPath);

     return RedirectToAction("Detail", "Customers", new { id = dto.CustomerId });
}

Thanks!

Body:
You should await for _service.SaveDocument to complete. Currently you start it and does not wait its results. Instead you send successful response to user, request is processed, used resources may be disposed at any moment.

Change your controller action to:

public async Task<IActionResult> Save(...
{
     await _service.SaveDocument(...

     return RedirectToAction(...
}


问:
WCF DiscoveryClient returns references to localhost from remote machines
I have an app with a self-hosted WCF service.

My WCF service gets published under the URI "net.tcp://localhost:8004/DocumentService". When I run the service on a remote machine and try to discover the service with the new .NET 4 class DiscoveryClient, the found services all have the URI "net.tcp://localhost:8004/DocumentService" too without any information about the actual machine where the service is hosted.

Obviously this is useless if I want to access the service on the remote machine. But I can't find any reference to the actual remote machine (IP address or server name) in the arguments passed to FindProgressChanged.

Is there a way to get the information about the remote machine or do I have to publish my service with the machine name of the remote machine? Or is DiscoveryClient just broken?

I hope this make sense.

答: I spent a lot of time investigating this problem. Building base addresses in the code was not acceptable for me, as it implies hardcoding transport scheme and port (the latter, of course, can be stored in a separate config section, but then why not just to use the existing section?). I wanted to have an ability to just configure the base address in config as usual. And it turns out that a base address like <add baseAddress="net.tcp://*:8731/"/> will perfectly work. I think the same is true for programmatic configuration.


问:
Why is this improved sieve slower with pypy?
```<code>def sieve(n):
    nums = [0] * n
    for i in range(2, int(n**0.5)+1):
        if nums[i] == 0:
            for j in range(i*i, n, i):
                nums[j] = 1

    return [i for i in range(2, n) if nums[i] == 0]

def sieve_var(n):
    nums = [0] * n
    for i in range(3, int(n**0.5)+1, 2):
        if nums[i] == 0:
            for j in range(i*i, n, i):
                nums[j] = 1

    return [2] + [i for i in range(3, n, 2) if nums[i] == 0]
</code>```

On my machine, sieve(10**8) takes 2.28 s while sieve_var(10**8) takes 2.67 s. I don't think pypy's warmup time is the culprit here, so why isn't sieve_var, which iterates over less, faster? In standard python 3.3 sieve_var is faster as expected. Using pypy 4.0.1 32bit on Windows 8.1.

Edit: As a test, I added count = 0 at the start of the function and count += 1 inside the inner loop (where nums[j] = 1 is). sieve(10**8) counts 242570202 while sieve_var(10**8) counts 192570204. So although the count isn't halved for sieve_var, it is doing less "work".

For fun, here is a version with slice indexing:

```<code>def sieve_slice(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]
</code>```

With python 3.6, sieve_slice runs about 4x faster than sieve, but with pypy3 7.3.0, sieve runs about 2x faster than sieve_slice.

答:
TL,DR;

As a C-program this would be a memory bound algorithm. However, even jit-compiled pypy-code has considerably more overhead and the operations are no longer "for free". Surprisingly (or maybe not), rhese two sieve versions have different jit-code, it is probably just bad luck that the second version results in a slower code.

If it would be C,  @Armin's answer would be the right one. It is well known, that for modern computers/caches and memory-bound code it does not matter if we jump over an integer - nevertheless all values must be fetched from memory and this is a bottle-neck. See this article for a great explanation.

Yet my experiments show that the non-optimized version (sieve) is slightly faster than the optimized version (sieve_var). Timings also shown, that the last line of sieve i.e. [i for i in range(2, n) if nums[i] == 0] is executed faster than the line of sieve_var - return [2] + [i for i in range(3, n, 2) if nums[i] == 0].

On my machine it was0.45 seconds vs. 0.65 seconds for 10^8 elements. These numbers may vary from machine to machine, so it is quite possible that somebody with faster CPU and slower memory would not see any difference at all. If it could be explained in terms of "memory dominates all", then we should be able to see, that the slower version has more cache misses as the faster version.

However, by running valgrind --tool=cachegrind pypy sieveXXX.py we can see, that there is almost no difference in number of cache misses, at least nothing that would explain the observable difference.

Let's consider a slightly simpler version, which exhibits exactly the same behavior - we don't save the primes, but just count them:

```<code>def sieve(n):
    ...
    res=0
    for i in range(2, n):
          if nums[i] == 0:
              res+=1
    return res

def sieve_var(n):
    ...
    res=1
    for i in range(3, n,2):
          if nums[i] == 0:
              res+=1
    return res
</code>```

The first version is still faster: 0.35 sec. vs. 0.45 sec (to make sure the time difference is no fluke and not due to some jit-warmup, I put the last part of the code into a for-loop and got always the same timings).

Before going further, let's take a look at a C-implementation and its assembly

```<code>long long int sum(long long int *a, int n){
    long long int res=0;
    for(int i=2;i<n;i++)
       if(a[i]==0)
          res++;
    return res;
}
</code>```

compiled with gcc and -Os we get:

```<code>        movl    $2, %edx
        xorl    %eax, %eax
.L4:
        cmpl    %edx, %esi
        jle     .L1
        cmpq    $0, (%rdi,%rdx,8)
        jne     .L3
        incq    %rax
.L3:
        incq    %rdx
        jmp     .L4
.L1:
        ret
</code>```

Pretty small and straight forward and takes only 0.08 seconds on my machine. My memory can go as fast as 10 GB/s and there are 8*10^8 bytes - so the whole time was basically needed to get the data.

But from this we also see, that the pypy-version has about 0.25 seconds overhead compared to the C-code. Where does it come from? By utilizing the vmprof-module we can see the jit-code and:

for one iteration of the loop, there are many more operations than in the C-version

the versions for sieve and sieve_par are very different. We can use debugger to count the number of instruction of an iteration: 24 for sieve  and 76-operations for sieve_var which handles only every second element, so the relation is actually  24:38.

It is hard to tell, why jit-code is so different for both versions without debugging pypy. Probably it is just bad luck, that the sieve_par is slower.

ContentLicense: CC BY-SA 4.0

Body:
def sieve(n):
    nums = [0] * n
    for i in range(2, int(n**0.5)+1):
        if nums[i] == 0:
            for j in range(i*i, n, i):
                nums[j] = 1

    return [i for i in range(2, n) if nums[i] == 0]

def sieve_var(n):
    nums = [0] * n
    for i in range(3, int(n**0.5)+1, 2):
        if nums[i] == 0:
            for j in range(i*i, n, i):
                nums[j] = 1

    return [2] + [i for i in range(3, n, 2) if nums[i] == 0]

On my machine, sieve(10**8) takes 2.28 s while sieve_var(10**8) takes 2.67 s. I don't think pypy's warmup time is the culprit here, so why isn't sieve_var, which iterates over less, faster? In standard python 3.3 sieve_var is faster as expected. Using pypy 4.0.1 32bit on Windows 8.1.

Edit: As a test, I added count = 0 at the start of the function and count += 1 inside the inner loop (where nums[j] = 1 is). sieve(10**8) counts 242570202 while sieve_var(10**8) counts 192570204. So although the count isn't halved for sieve_var, it is doing less "work".

For fun, here is a version with slice indexing:

def sieve_slice(n):
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

With python 3.6, sieve_slice runs about 4x faster than sieve, but with pypy3 7.3.0, sieve runs about 2x faster than sieve_slice.

Body:
TL,DR;

As a C-program this would be a memory bound algorithm. However, even jit-compiled pypy-code has considerably more overhead and the operations are no longer "for free". Surprisingly (or maybe not), rhese two sieve versions have different jit-code, it is probably just bad luck that the second version results in a slower code.

If it would be C,  @Armin's answer would be the right one. It is well known, that for modern computers/caches and memory-bound code it does not matter if we jump over an integer - nevertheless all values must be fetched from memory and this is a bottle-neck. See this article for a great explanation.

Yet my experiments show that the non-optimized version (sieve) is slightly faster than the optimized version (sieve_var). Timings also shown, that the last line of sieve i.e. [i for i in range(2, n) if nums[i] == 0] is executed faster than the line of sieve_var - return [2] + [i for i in range(3, n, 2) if nums[i] == 0].

On my machine it was0.45 seconds vs. 0.65 seconds for 10^8 elements. These numbers may vary from machine to machine, so it is quite possible that somebody with faster CPU and slower memory would not see any difference at all. If it could be explained in terms of "memory dominates all", then we should be able to see, that the slower version has more cache misses as the faster version.

However, by running valgrind --tool=cachegrind pypy sieveXXX.py we can see, that there is almost no difference in number of cache misses, at least nothing that would explain the observable difference.

Let's consider a slightly simpler version, which exhibits exactly the same behavior - we don't save the primes, but just count them:

def sieve(n):
    ...
    res=0
    for i in range(2, n):
          if nums[i] == 0:
              res+=1
    return res

def sieve_var(n):
    ...
    res=1
    for i in range(3, n,2):
          if nums[i] == 0:
              res+=1
    return res

The first version is still faster: 0.35 sec. vs. 0.45 sec (to make sure the time difference is no fluke and not due to some jit-warmup, I put the last part of the code into a for-loop and got always the same timings).

Before going further, let's take a look at a C-implementation and its assembly

long long int sum(long long int *a, int n){
    long long int res=0;
    for(int i=2;i<n;i++)
       if(a[i]==0)
          res++;
    return res;
}

compiled with gcc and -Os we get:

        movl    $2, %edx
        xorl    %eax, %eax
.L4:
        cmpl    %edx, %esi
        jle     .L1
        cmpq    $0, (%rdi,%rdx,8)
        jne     .L3
        incq    %rax
.L3:
        incq    %rdx
        jmp     .L4
.L1:
        ret

Pretty small and straight forward and takes only 0.08 seconds on my machine. My memory can go as fast as 10 GB/s and there are 8*10^8 bytes - so the whole time was basically needed to get the data.

But from this we also see, that the pypy-version has about 0.25 seconds overhead compared to the C-code. Where does it come from? By utilizing the vmprof-module we can see the jit-code and:

for one iteration of the loop, there are many more operations than in the C-version

the versions for sieve and sieve_par are very different. We can use debugger to count the number of instruction of an iteration: 24 for sieve  and 76-operations for sieve_var which handles only every second element, so the relation is actually  24:38.

It is hard to tell, why jit-code is so different for both versions without debugging pypy. Probably it is just bad luck, that the sieve_par is slower.


问:
Access AWS Node SDK inside firewall without changing any configuration in firewall
I have a desktop app which downloads app assets after installation is completed.
App uses aws node sdk to download all the assets from S3 buckets.
Problem comes when app is getting installed inside company firewall. Company firewall blocks the api request used by aws node sdk.
And I can't ask all my client to white-list amazon web service urls but I can ask them to white-list my own company url like *.mycompany.com.
Is there any way we can access aws node sdk using my company domain.

答: We had this same problem and resolved it by creating a proxy API endpoint on a separate server that would take the request, and pipe the stream from AWS S3 back to the client. Because this proxy endpoint was hosted in a whitelisted domain, we didn't have to worry about the company's firewall blocking the request.</p>


问:
Oracle : SQL - Selecting cust_id with specific App_Nm ( and should not have other app_nm)
Please suggest me an approach to select the CUST_ID which only has DEF AS APP_NM. In the below example, the query should only return 123 as the other cust_id contains other App_nm apart from DEF

```<code>CUST_ID |   APP_NM

XYZ |   ABC

XYZ |   BCD

XYZ |   BB

XYZ |   DEF

XYZ |   DEF

123 |   DEF

123 |   DEF

567 |   BCD

567 |   DEF
</code>```

I tried using count but didn't work out.

答:
A simple solution to this is to find out CUST_ID which don't have APP_NM = "DEF" and remove them from all the CUST_ID rows. Since you have multiple rows matching this criteria, you can further use GROUP BY to return one row. Following is the final query:

```<code>SELECT CUST_ID
FROM TestTable1
WHERE CUST_ID
NOT IN (SELECT CUST_ID
        FROM TestTable1
        WHERE APP_NM != "DEF")
GROUP BY CUST_ID;
</code>```

I am calling the table TestTable1 please replace with appropriate name

I have tested the above query on local MySQL installation and following is the table:

```<code>mysql> select * from TestTable1;
+---------+--------+
| CUST_ID | APP_NM |
+---------+--------+
| XYZ     | ABC    |
| XYZ     | BCD    |
| XYZ     | BB     |
| XYZ     | DEF    |
| XYZ     | DEF    |
| 123     | DEF    |
| 123     | DEF    |
| 567     | BCD    |
| 567     | DEF    |
+---------+--------+
9 rows in set (0.00 sec)
</code>```

Following is the result of the above query:

```<code>mysql> SELECT CUST_ID FROM TestTable1 WHERE CUST_ID NOT IN (SELECT CUST_ID FROM TestTable1 WHERE APP_NM != "DEF") GROUP BY CUST_ID;
+---------+
| CUST_ID |
+---------+
| 123     |
+---------+
1 row in set (0.00 sec)
</code>```

Body:
Please suggest me an approach to select the CUST_ID which only has DEF AS APP_NM. In the below example, the query should only return 123 as the other cust_id contains other App_nm apart from DEF

CUST_ID |   APP_NM

XYZ |   ABC

XYZ |   BCD

XYZ |   BB

XYZ |   DEF

XYZ |   DEF

123 |   DEF

123 |   DEF

567 |   BCD

567 |   DEF

I tried using count but didn't work out.

Body:
A simple solution to this is to find out CUST_ID which don't have APP_NM = "DEF" and remove them from all the CUST_ID rows. Since you have multiple rows matching this criteria, you can further use GROUP BY to return one row. Following is the final query:

SELECT CUST_ID
FROM TestTable1
WHERE CUST_ID
NOT IN (SELECT CUST_ID
        FROM TestTable1
        WHERE APP_NM != "DEF")
GROUP BY CUST_ID;

I am calling the table TestTable1 please replace with appropriate name

I have tested the above query on local MySQL installation and following is the table:

mysql> select * from TestTable1;
+---------+--------+
| CUST_ID | APP_NM |
+---------+--------+
| XYZ     | ABC    |
| XYZ     | BCD    |
| XYZ     | BB     |
| XYZ     | DEF    |
| XYZ     | DEF    |
| 123     | DEF    |
| 123     | DEF    |
| 567     | BCD    |
| 567     | DEF    |
+---------+--------+
9 rows in set (0.00 sec)

Following is the result of the above query:

mysql> SELECT CUST_ID FROM TestTable1 WHERE CUST_ID NOT IN (SELECT CUST_ID FROM TestTable1 WHERE APP_NM != "DEF") GROUP BY CUST_ID;
+---------+
| CUST_ID |
+---------+
| 123     |
+---------+
1 row in set (0.00 sec)


问:
How can i Integrate FullCalendar with Codeigniter
I am using Codeigniter. I am trying to integrate FullCalendar with my project. It is working. But, i am not able to save the events in database(mysql) using codeigniter. Is it possible to save selected events to database with date?</p>

答:
It is possible. You need to setup some kind of mysql table which can store the events. From FullCalendar with PHP & CodeIgniter:

```<code>CREATE TABLE `calendar_events` (
`ID` int(11) NOT NULL,
`title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
`description` varchar(1000) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
</code>```

Then you can insert events into it using the start and end datetimes provided by the library.

When you need to grab them, use the start and end dates that FC provides.

Body:
It is possible. You need to setup some kind of mysql table which can store the events. From FullCalendar with PHP & CodeIgniter:

CREATE TABLE `calendar_events` (
`ID` int(11) NOT NULL,
`title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
`description` varchar(1000) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Then you can insert events into it using the start and end datetimes provided by the library.

When you need to grab them, use the start and end dates that FC provides.


问:
How do I insert text to the 1st line of a file using sed?
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

```<code>#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

And this dosn't work
also tried

```<code>#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test
</code>```

this dosn't seem to work either
oddly when I try

```<code>#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test
</code>```

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

答:
Your problem stems from the fact that sed cannot locate the line you're telling it to write at, for example:

```<code>touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

attempts to write to insert at the line 1 of test, but that line doesn't exist at this point. If you've created your file as:

```<code>echo -en "\n" > test
sed -i '1i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

it would not complain, but you'd be having an extra line. Similarly, when you call:

```<code>sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
</code>```

you're telling sed to insert the following data at the line 2 which doesn't exist at that point so sed doesn't get to edit the file.

So, for the initial line or the last line in the file, you should not use sed because simple > and >> stream redirects are more than enough.

Body:
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test

And this dosn't work
also tried

#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test

this dosn't seem to work either
oddly when I try

#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

Body:
Your problem stems from the fact that sed cannot locate the line you're telling it to write at, for example:

touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test

attempts to write to insert at the line 1 of test, but that line doesn't exist at this point. If you've created your file as:

echo -en "\n" > test
sed -i '1i/etc/example/live/example.com/fullchain.pem;\' test

it would not complain, but you'd be having an extra line. Similarly, when you call:

sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"

you're telling sed to insert the following data at the line 2 which doesn't exist at that point so sed doesn't get to edit the file.

So, for the initial line or the last line in the file, you should not use sed because simple > and >> stream redirects are more than enough.


问:
Can word2vec algorithm be distributed on multi-computers using tensorflow?
I want to train word2vec model on a very big corpus such that embedded words cannot be allocated to RAM.

I know there are existing solutions for the algorithm parallelization, for example Spark implementation, but I would like to use tensorflow library.

Is it possible?

答:
The authors of word2vec implemented the algorithm using an asynchronous SGD called: HogWild!. So you might want to look for tensor flow implementation of this algorithm.

In HogWild!, each thread takes a sample at a time and performs an update to the weights without any synchronization with other threads. These updates from different threads can potentially overwrite each other, leading to data race conditions. But Hogwild! authors show that it works well for very sparse data sets, where many samples are actually near independent since they write to mostly different indices of the model.


答:
Use groupby and mean with an array designed to form the groups you need

```<code>df.groupby(np.arange(len(df)) // 3).mean()
</code>```

Title: Aggregating Dataframe in groups of 3

Body:
I have a DataFrame like this one :

           date        open        high         low       close        vwap
0    1498907700  0.00010020  0.00010020  0.00009974  0.00010019  0.00009992
1    1498908000  0.00010010  0.00010010  0.00010010  0.00010010  0.00010010
2    1498908300  0.00010010  0.00010010  0.00009957  0.00009957  0.00009992
3    1498908600  0.00009957  0.00009957  0.00009957  0.00009957  0.00000000
4    1498908900  0.00010009  0.00010009  0.00009949  0.00009959  0.00009952
5    1498909200  0.00009987  0.00009991  0.00009956  0.00009956  0.00009974
6    1498909500  0.00009948  0.00009948  0.00009915  0.00009915  0.00009919
...
789

And would like to do a mean of each 3 rows and have a new DataFrame which is then 3 times shorter with the mean of all sets of 3 rows inside the source DataFrame.

Body:
Use groupby and mean with an array designed to form the groups you need

df.groupby(np.arange(len(df)) // 3).mean()


问:
what is 'linesize alignment' meaning?
I'm following ffmpeg tutorial in http://dranger.com/ffmpeg/tutorial01.html.

I have just found that avpicture_get_size function is deprecated.

So I have checked ffmpeg's document(https://www.ffmpeg.org/doxygen/3.0/group__lavu__picture.html#ga24a67963c3ae0054a2a4bab35930e694) and found substitute av_image_get_buffer_size.

But I can't understand align parameter meaning 'linesize alignment'......

What is it meaning?

答:
If you look at the definition of avpicture_get_size in version 3.2 you see the following code:

```<code>int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height)
{
    return av_image_get_buffer_size(pix_fmt, width, height, 1);
}
</code>```

It simply calls the suggested function: av_image_get_buffer_size with the align parameter set to 1. I did not go further to find out the full significance of why 1 is used for the depreciated function. As usual with ffmpeg, one can probably figure it out by reading the right code and enough code (with some code experiments).

Title: what is 'linesize alignment' meaning?

Body:
If you look at the definition of avpicture_get_size in version 3.2 you see the following code:

int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height)
{
    return av_image_get_buffer_size(pix_fmt, width, height, 1);
}

It simply calls the suggested function: av_image_get_buffer_size with the align parameter set to 1. I did not go further to find out the full significance of why 1 is used for the depreciated function. As usual with ffmpeg, one can probably figure it out by reading the right code and enough code (with some code experiments).


问:
Howto translate the page origin to top-left in PdfBox2?

UPDATE:

The question below is actually very similar to this question on SO which has been perfectly answered by mkl. Short answer: Either live with a bottom-left origin or translate your coordinates to these.
There is a workaround but that's a mess.

ORIGINAL QUESTION:

I want to create a PDF with coordinates 0,0 in the upper left and 210, 297 in the bottom right. Approaches with calculations like y = 297 - y seem to be a bit messy.

This question is similar to this question on SO but refers to PdfBox 2 where the the provided solution doesn't work.

The docs say I should use a Matrix to transform the coordinatesystem. I tried this approach:

```<code>    PDRectangle currentPageRectangle = new PDRectangle(210 * POINTS_PER_MM, 297 * POINTS_PER_MM);
    PDPage currentPage = new PDPage(currentPageRectangle);
    currentDocument.addPage(currentPage);
    contentStream = new PDPageContentStream(currentDocument, currentPage);

    AffineTransform a = new AffineTransform(1, 0, 0, -1, 210 * POINTS_PER_MM, 297 * POINTS_PER_MM);
    Matrix m = new Matrix(a);
    contentStream.transform(m);
</code>```

Unfortunately the page stays blank. Any clues?

答:
Your Affinetransform is not correct, see Javadoc. The last two parameters are translation values, now you translate the page really outside of the physical page because you translate x coordinates wrong.

This code works better (I used height as a placeholder for your page height):

```<code>        contentStream = new PDPageContentStream(document, page);
        contentStream.transform(new Matrix(new java.awt.geom.AffineTransform(1, 0, 0, -1, 0,height)));
</code>```

Also consider getting the actual page height instead of using hardcoded values, this way your code works on any page dimensions:

```<code>float height=page.getMediaBox().getHeight();
</code>```

Body:
UPDATE:

The question below is actually very similar to this question on SO which has been perfectly answered by mkl. Short answer: Either live with a bottom-left origin or translate your coordinates to these.
There is a workaround but that's a mess.

ORIGINAL QUESTION:

I want to create a PDF with coordinates 0,0 in the upper left and 210, 297 in the bottom right. Approaches with calculations like y = 297 - y seem to be a bit messy.

This question is similar to this question on SO but refers to PdfBox 2 where the the provided solution doesn't work.

The docs say I should use a Matrix to transform the coordinatesystem. I tried this approach:

    PDRectangle currentPageRectangle = new PDRectangle(210 * POINTS_PER_MM, 297 * POINTS_PER_MM);
    PDPage currentPage = new PDPage(currentPageRectangle);
    currentDocument.addPage(currentPage);
    contentStream = new PDPageContentStream(currentDocument, currentPage);

    AffineTransform a = new AffineTransform(1, 0, 0, -1, 210 * POINTS_PER_MM, 297 * POINTS_PER_MM);
    Matrix m = new Matrix(a);
    contentStream.transform(m);

Unfortunately the page stays blank. Any clues?

Body:
Your Affinetransform is not correct, see Javadoc. The last two parameters are translation values, now you translate the page really outside of the physical page because you translate x coordinates wrong.

This code works better (I used height as a placeholder for your page height):

        contentStream = new PDPageContentStream(document, page);
        contentStream.transform(new Matrix(new java.awt.geom.AffineTransform(1, 0, 0, -1, 0,height)));

Also consider getting the actual page height instead of using hardcoded values, this way your code works on any page dimensions:

float height=page.getMediaBox().getHeight();


问:
Get data from Parse server for offline usage
I am trying to develop an android application while storing database on parse server. Everything works fine but problem is with application offlime usage. Is there any way i  can store data locally including log in details and fetch data from server only when updated. plz give me some suggestion examples would be better. Thanks</p>

答:
You need to use Localdatastore.

in your android app enable it.

```<code>Parse.Configuration config = new Parse.Configuration.Builder(this)
        .applicationId("XXXXXXXXXXX")
        .clientKey("XXXXXXXXXXX")
        .server("https://api.serverused.com/")
        .enableLocalDataStore() // Acticate it here
        .build();

Parse.initialize(config);  //
</code>```

This is how to save the object or list of objects offline

```<code> ParseQuery<ParseObject> query = ParseQuery.getQuery(“GameScore");
    query.getInBackground("xWMyZ4YE", new GetCallback<ParseObject>() {
    public void done(ParseObject object, ParseException e) {
       if (e == null) {

    // object will be your game score so save it offline
       object.pinAllInBackground();
       } else {
    // something went wrong
    }
  }
});
</code>```

This is how to get your localdata

```<code>ParseQuery<ParseObject> query = ParseQuery.getQuery(“GameScore");
    query.fromLocalDatastore();
    query.getInBackground("xWMyZ4YE", new GetCallback<ParseObject>() {
    public void done(ParseObject object, ParseException e) {
       if (e == null) {
    // object will be your game score
       } else {
    // something went wrong
    }
  }
});
</code>```

If you are saving a list of objects, generally used with findInBackground, you will need to use

```<code>ParseObject.pinAllInBackground(objects);
</code>```

Hope this helps and check the docs Parse LocalDataStore

Body:
You need to use Localdatastore.

in your android app enable it.

Parse.Configuration config = new Parse.Configuration.Builder(this)
        .applicationId("XXXXXXXXXXX")
        .clientKey("XXXXXXXXXXX")
        .server("https://api.serverused.com/")
        .enableLocalDataStore() // Acticate it here
        .build();

Parse.initialize(config);  //

This is how to save the object or list of objects offline

 ParseQuery<ParseObject> query = ParseQuery.getQuery(“GameScore");
    query.getInBackground("xWMyZ4YE", new GetCallback<ParseObject>() {
    public void done(ParseObject object, ParseException e) {
       if (e == null) {

    // object will be your game score so save it offline
       object.pinAllInBackground();
       } else {
    // something went wrong
    }
  }
});

This is how to get your localdata

ParseQuery<ParseObject> query = ParseQuery.getQuery(“GameScore");
    query.fromLocalDatastore();
    query.getInBackground("xWMyZ4YE", new GetCallback<ParseObject>() {
    public void done(ParseObject object, ParseException e) {
       if (e == null) {
    // object will be your game score
       } else {
    // something went wrong
    }
  }
});

If you are saving a list of objects, generally used with findInBackground, you will need to use

ParseObject.pinAllInBackground(objects);

Hope this helps and check the docs Parse LocalDataStore


问:
NVD3 x-axis labels misaligned for lineChart and historicalChart
This is similar to issue reported here.

In this sample working example, I have implemented a line chart and a historical chart.

```<code>chart.xAxis
    .showMaxMin(true)
    .tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)) })
</code>```

Everything thing works as expected, except that axis lables in x-axis are not in sync with line points or the bar.

As the solution suggested in this issue says that it is due to formatting of date, I have tried to format date/time in my new example.
But the issue remains same.

```<code>chart.xAxis
    .showMaxMin(true)
    .tickFormat(function(d) { return d3.time.format('%b %d %Y')(new Date(d)) })
</code>```

To me it initially looked an issue of NVD3 library cause same formatting works perfectly for other chart types I checked. Thus I raised an issue here.

答: You need to set the xScale. Do chart.xScale(d3.time.scale())

Body:
This is similar to issue reported here.

In this sample working example, I have implemented a line chart and a historical chart.

chart.xAxis
    .showMaxMin(true)
    .tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)) })

Everything thing works as expected, except that axis lables in x-axis are not in sync with line points or the bar.

As the solution suggested in this issue says that it is due to formatting of date, I have tried to format date/time in my new example.
But the issue remains same.

chart.xAxis
    .showMaxMin(true)
    .tickFormat(function(d) { return d3.time.format('%b %d %Y')(new Date(d)) })

To me it initially looked an issue of NVD3 library cause same formatting works perfectly for other chart types I checked. Thus I raised an issue here.


问:
RabbitMQ Rest API Create Exchange Failed
I am creating a Spring Boot application and I want to create an exchange via rest api:

```<code>    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    String auth = "guest:guest";
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")) );
    String authHeader = "Basic " + new String( encodedAuth );
    headers.set( "Authorization", authHeader );

    String uri = "http://localhost:15672/api/exchanges/%2f/my-new-exchange-new";

    String input = "{\"type\":\"direct\",\"durable\":\"true\"}";

    HttpEntity<String> entity = new HttpEntity<String>(input,headers);

    ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.PUT, entity, String.class);

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

However I always get the error:

```<code>PUT request for "http://localhost:15672/api/exchanges/%252f/my-new-exchange-new" resulted in 404 (Not Found); invoking error handler
</code>```

Could you please help me with a hint? Thank you!

You can try it out if you want here: https://github.com/pkid/rabbittest

答:
The problem is most likely the URL encoding applied to your uri variable by the RestTemplate given the %252f returned in the error. To avoid that, you need to use RestTemplate methods that work with URI and tell it to assume the URL is already encoded:

```<code>String uri = "http://localhost:15672/api/exchanges/%2F/my-new-exchange-new";
restTemplate.exchange(UriComponentsBuilder.fromHttpUrl(uri)
                                          .build(true)
                                          .toUri(), HttpMethod.PUT, entity, String.class);
</code>```

Body:
I am creating a Spring Boot application and I want to create an exchange via rest api:

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    String auth = "guest:guest";
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")) );
    String authHeader = "Basic " + new String( encodedAuth );
    headers.set( "Authorization", authHeader );

    String uri = "http://localhost:15672/api/exchanges/%2f/my-new-exchange-new";

    String input = "{\"type\":\"direct\",\"durable\":\"true\"}";

    HttpEntity<String> entity = new HttpEntity<String>(input,headers);

    ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.PUT, entity, String.class);

    System.out.println(response);

However I always get the error:

PUT request for "http://localhost:15672/api/exchanges/%252f/my-new-exchange-new" resulted in 404 (Not Found); invoking error handler

Could you please help me with a hint? Thank you!

You can try it out if you want here: https://github.com/pkid/rabbittest

Body:
The problem is most likely the URL encoding applied to your uri variable by the RestTemplate given the %252f returned in the error. To avoid that, you need to use RestTemplate methods that work with URI and tell it to assume the URL is already encoded:

String uri = "http://localhost:15672/api/exchanges/%2F/my-new-exchange-new";
restTemplate.exchange(UriComponentsBuilder.fromHttpUrl(uri)
                                          .build(true)
                                          .toUri(), HttpMethod.PUT, entity, String.class);


问:
c# Loop not incrementing as expected
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks</p>

```<code>using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}
</code>```

答:
With the line

```<code>a[i] = i * j;
</code>```

i remains the same value for the entire cycle of the loop using j, this means you are continuously overwriting the value placed in a[i].

With the new algorithmn you are using, you are effectively storing the square of i at each index of the array, so this will be enough:

```<code>for (int i = 0; i < 10; i++)
    a[i] = i * i;
</code>```

Title: c# Loop not incrementing as expected

Body:
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks

using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}

Body:
With the line

a[i] = i * j;

i remains the same value for the entire cycle of the loop using j, this means you are continuously overwriting the value placed in a[i].

With the new algorithmn you are using, you are effectively storing the square of i at each index of the array, so this will be enough:

for (int i = 0; i < 10; i++)
    a[i] = i * i;


问:
C Programming: How to read the whole file contents into a buffer
I want to write the full contents of a file into a buffer. The file actually only contains a string which i need to compare with a string.

What would be the most efficient option which is portable even on linux.

ENV: Windows

答:
Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

```<code>#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}
</code>```

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Body:
Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.


问:
how to send ajax request in jQuery with data encoded
when i send ajax request i got the error that

```<code> $.ajax({
                        type: "POST",
                        url: furl2,
                        cache: false,
                        contentType: "application/json;charset=utf-8",
                        data: { id: id, url: $("#id" + id + " .customURL").val() },
                        success: function (msg) {
                          //some code here
                        },
                    });
                }
</code>```

i got the error that id is undefined even i put them.

how i can send a ajax request to server using ajax.

答:
```<code>// create an empty object
var data = {};

// create and populate nodes in the object
data.id = id;
data.url = //what ever you wanted it to be

$.ajax({
      type: "POST",
      url: furl2,
      cache: false,
      dataType: "json",
      data: data, // send the object to the server as post data
       success: function (result) {
           // try and grab a node in the json object
           console.log(result.foo);
       },
});
</code>```

This will send the data as posts to the server, and require json encoded data in return, which is nice becasue you don't have to send the html from the server, you can just construct it in the js.

If you wanna encode data from the server with for example php you can do it on a regular array or object

```<code><?php
    // fetch what ever post we need
    $id = $_POST['id'];

    $arr = array(
          "foo" => "1",
          "two" => "2"
    );

    return json_encode($arr);

?>
</code>```

OwnerDisplayName: Steven Spielberg

Body:
when i send ajax request i got the error that

 $.ajax({
                        type: "POST",
                        url: furl2,
                        cache: false,
                        contentType: "application/json;charset=utf-8",
                        data: { id: id, url: $("#id" + id + " .customURL").val() },
                        success: function (msg) {
                          //some code here
                        },
                    });
                }

i got the error that id is undefined even i put them.

how i can send a ajax request to server using ajax.

Body:
// create an empty object
var data = {};

// create and populate nodes in the object
data.id = id;
data.url = //what ever you wanted it to be

$.ajax({
      type: "POST",
      url: furl2,
      cache: false,
      dataType: "json",
      data: data, // send the object to the server as post data
       success: function (result) {
           // try and grab a node in the json object
           console.log(result.foo);
       },
});

This will send the data as posts to the server, and require json encoded data in return, which is nice becasue you don't have to send the html from the server, you can just construct it in the js.

If you wanna encode data from the server with for example php you can do it on a regular array or object

<?php
    // fetch what ever post we need
    $id = $_POST['id'];

    $arr = array(
          "foo" => "1",
          "two" => "2"
    );

    return json_encode($arr);

?>


问:
Change text in div
Let's say I have following text in my div

Foo

Bar

  change text

```

<p>and on clicking the change text button I want the text to be and on clicking the "change to old" I want it to switch to the old text again.</p>

<pre class="lang-html prettyprint-override"><code><div id="textbox">
  <p>Lorem</p>
  <br>
  <p>Ipsum</p>
  change to old one
<div>
</code>```

Is this actually possible with the current approach with the help of css and javascript or would I have to structure my html differently? If it is possible with the current approach, how so?

答:
If you are looking for a text rotator, you can do something like this.

window.onload = function () {
  var current = 0;
  var ps = document.querySelectorAll("p");
  for (var i = 0; i < ps.length; i++) {
    ps[i].style.display = 'none';
  }
  ps[current%ps.length].style.display = 'block';
  document.querySelector("a").onclick = function () {
    ps[current%ps.length].style.display = 'none';
    current++;
    ps[current%ps.length].style.display = 'block';
    return false;
  };
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="texts">
  <p>Saying 1... No #1...</p>
  <p>Saying 2... No #2...</p>
  <p>Saying 3... No #3...</p>
  <p>Saying 4... No #4...</p>
  <p>Saying 5... No #5...</p>
</div>
Rotate</code>```

Updated. Now this code is very much scalable. Have any number of
 tags and it will work. You don't need to change the JavaScript. Only HTML, you can add / remove. Please let me know if this works. I haven't used jquery!

Title: Change text in div

Body:
Let's say I have following text in my div

Foo

Bar

  change text

and on clicking the change text button I want the text to be and on clicking the "change to old" I want it to switch to the old text again.

Lorem

Ipsum

  change to old one

Is this actually possible with the current approach with the help of css and javascript or would I have to structure my html differently? If it is possible with the current approach, how so?

Body:
If you are looking for a text rotator, you can do something like this.

window.onload = function () {
  var current = 0;
  var ps = document.querySelectorAll("p");
  for (var i = 0; i < ps.length; i++) {
    ps[i].style.display = 'none';
  }
  ps[current%ps.length].style.display = 'block';
  document.querySelector("a").onclick = function () {
    ps[current%ps.length].style.display = 'none';
    current++;
    ps[current%ps.length].style.display = 'block';
    return false;
  };
};

<div id="texts">
  <p>Saying 1... No #1...</p>
  <p>Saying 2... No #2...</p>
  <p>Saying 3... No #3...</p>
  <p>Saying 4... No #4...</p>
  <p>Saying 5... No #5...</p>
</div>
<a href="#">Rotate</a>

Updated. Now this code is very much scalable. Have any number of <p> tags and it will work. You don't need to change the JavaScript. Only HTML, you can add / remove. Please let me know if this works. I haven't used jquery!


问:
Automatically upload photos to a particular Google Photos album
I'm trying to automatically upload JPG photo files from a particular directory on my computer to a particular album on Google Photos. I'd like the photos to periodically get pushed up to Google Photos (every day or so is frequent enough). Google Photos Backup almost does what I want, but it just uploads the files -- it doesn't put them into a particular [pre-existing] album on Google Photos. It's possible that I can somehow use Google Drive and a simple cron job for this, although I don't know how. I am also considering using the Picassa Web Albums API, but that feels overkill and I'd like to avoid that work unless it's necessary. Are there any straightforward solutions to this?

答:
As you said that Google Photo Backup do the (upload) job, in my opinion the best way then is to use directly a Google Apps Script stored inside your Google Drive (running periodicaly) in order to push each new detected pictures inside a particular album.

If you need relative documentation, you may take a look at the album class documentation and also https://developers.google.com/apps-script/

If you need to use an other language to do the job (python, js, etc...) please specify which one and give us also more precision. (mac / windows / linux)


问:
How i should set parameters of Scrypt hashing function so I can get a duration of hash processing about 250 ms?
I whant to hashing a password with SCrypto hashing function but if i will to use a default parameters i get hashing duration about 5-6 seconds. How i can set parameters so i get duration less then 1 second (better 250 ms)

SCrypt.scrypt(pass, salt, n, r, p, length)

default Scrypt(pass, salt, 16384, 8, 1, length)

答:
The answer will be highly dependent on your device. The time taken will be roughly proportional to N * r, though, so if it's currently taking 6 seconds, N / 8 (because it's a power of 2) should get you under 1 second, and N / 32 should get you to ~250 ms.

But be careful, because values so small reduce the overall security of the function, and it may even become worse than tried-and-true methods like bcrypt: http://blog.ircmaxell.com/2014/03/why-i-dont-recommend-scrypt.html

Also note the recommendation not to use Scrypt as a password hashing function (for storage), but as a key derivation function (what it was designed for), where the resulting key isn't stored.