问:
Getting Empty response while fetching JSON data
When I try to fetch JSON data from a website I can see the data in my browser but when i try to do the same through programing i get empty response http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 this is the url i am trying to fetch i get empty response in my App where as just changing the value in the url string from 1113 to 1416 the JSON data is properly seen.
 Below is my code

```<code>protected Void doInBackground(Void... params) {
String matchesUrl = "http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1"
            data = new ArrayList<ListGroup>();
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(matchesUrl);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null||jsonStr !="") {
                data = jsonExtractor.extractJson(jsonStr);
            }else{
                Log.e(TAG, "Response from url: null");
            }
            return null;
        }
</code>```

HttpHandler class:

```<code>public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}
</code>```

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 inside the app

```<code>E/FootBallMainFragment: Json Data is downloading
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:06:03.851 23817-24720/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url:
06-06 16:06:03.870 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -1118482, canvas = android.view.GLES20RecordingCanvas@4422f0f, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@36589616
06-06 16:06:03.871 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -13619152, canvas = android.view.GLES20RecordingCanvas@c76cb97, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@17401d0b
</code>```

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1416&getMatches=1 inside the app

```<code>E/FootBallMainFragment: Json Data is downloading
06-06 16:04:55.988 23817-24044/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb17&getMatches=1
06-06 16:04:55.994 23817-24044/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:04:55.996 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:04:55.999 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:04:56.386 23817-24044/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url: {"2017-06-08":{"11|2:1|4:1|0":"REAL MADRID|ZERU|23:30|0|0","12|6:2|8:2|0":"AL AHLY|JUVENTUS|23:55|0|0"},"2017-06-07":{"9|1:1|3:1|0":"ATHLETICO|JEMTEM|23:30|0|0","10|5:2|7:2|0":"PREDATORS|JB|23:55|0|0"},"2017-06-06":{"8|6:2|7:2|0":"AL AHLY|JB|23:55|0|0","7|2:1|3:1|0":"REAL MADRID|JEMTEM|23:30|0|0"},"2017-06-01":{"6|8:2|5:2|0":"JUVENTUS|PREDATORS|23:55|0|0","5|4:1|1:1|0":"ZERU|ATHLETICO|23:30|0|0"},"2017-05-31":{"4|7:2|8:2|0":"JB|JUVENTUS|23:55|0|0","3|3:1|4:1|0":"JEMTEM|ZERU|23:30|0|0"},"2017-05-30":{"2|5:2|6:2|0":"PREDATORS|AL AHLY|23:55|0|0","1|1:1|2:1|0":"ATHLETICO|REAL MADRID|23:30|0|0"}}
</code>```

Its bit confusing as both the url are responding correctly but only one works inside the App. Can't figure out why is it so

答:
I think Problem is in reading data at below statement.

```<code>while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
</code>```

you are appending '\n' in every line...i didn't understand the use of this, you should try after removing .append('\n') from here.

Body:
When I try to fetch JSON data from a website I can see the data in my browser but when i try to do the same through programing i get empty response http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 this is the url i am trying to fetch i get empty response in my App where as just changing the value in the url string from 1113 to 1416 the JSON data is properly seen.
 Below is my code

protected Void doInBackground(Void... params) {
String matchesUrl = "http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1"
            data = new ArrayList<ListGroup>();
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(matchesUrl);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null||jsonStr !="") {
                data = jsonExtractor.extractJson(jsonStr);
            }else{
                Log.e(TAG, "Response from url: null");
            }
            return null;
        }

HttpHandler class:

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 inside the app

E/FootBallMainFragment: Json Data is downloading
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:06:03.851 23817-24720/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url:
06-06 16:06:03.870 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -1118482, canvas = android.view.GLES20RecordingCanvas@4422f0f, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@36589616
06-06 16:06:03.871 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -13619152, canvas = android.view.GLES20RecordingCanvas@c76cb97, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@17401d0b

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1416&getMatches=1 inside the app

E/FootBallMainFragment: Json Data is downloading
06-06 16:04:55.988 23817-24044/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb17&getMatches=1
06-06 16:04:55.994 23817-24044/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:04:55.996 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:04:55.999 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:04:56.386 23817-24044/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url: {"2017-06-08":{"11|2:1|4:1|0":"REAL MADRID|ZERU|23:30|0|0","12|6:2|8:2|0":"AL AHLY|JUVENTUS|23:55|0|0"},"2017-06-07":{"9|1:1|3:1|0":"ATHLETICO|JEMTEM|23:30|0|0","10|5:2|7:2|0":"PREDATORS|JB|23:55|0|0"},"2017-06-06":{"8|6:2|7:2|0":"AL AHLY|JB|23:55|0|0","7|2:1|3:1|0":"REAL MADRID|JEMTEM|23:30|0|0"},"2017-06-01":{"6|8:2|5:2|0":"JUVENTUS|PREDATORS|23:55|0|0","5|4:1|1:1|0":"ZERU|ATHLETICO|23:30|0|0"},"2017-05-31":{"4|7:2|8:2|0":"JB|JUVENTUS|23:55|0|0","3|3:1|4:1|0":"JEMTEM|ZERU|23:30|0|0"},"2017-05-30":{"2|5:2|6:2|0":"PREDATORS|AL AHLY|23:55|0|0","1|1:1|2:1|0":"ATHLETICO|REAL MADRID|23:30|0|0"}}

Its bit confusing as both the url are responding correctly but only one works inside the App. Can't figure out why is it so

Body:
I think Problem is in reading data at below statement.

while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }

you are appending '\n' in every line...i didn't understand the use of this, you should try after removing .append('\n') from here.


来源: stackexchange

问:
Using Pug and SCSS with Angular (ng-model)
I'm trying to learn Angular simultaneously with Pug and SCSS, my current issue is with the ng-class concept. My code is as follows:

HTML (In Pug)

```<code>form
   input#theSearch(type='text' ng-model="theSearch")
   br
   span(ng-class ="{'test': isEven()}") Example Text
</code>```

SCSS

```<code>.test {
    color:red;
    font-size:80px;
}
</code>```

AngularJS

```<code>angular.module("root", [])
   .controller("index",["$scope",function($scope) {
     $scope.theSearch = 1;
     $scope.isEven = function () { return $scope.theSearch % 2 === 0; };
}]);
</code>```

So, ideally this will react when the user inputs an even number and turn the span red as well as increasing the size. Currently, it does not change despite even inputs. I suspect this is some rookie syntax mistake but any guidance on the issue would be most appreciated.

Side Notes:
I'm in the CodePen environment. Pug is included, SCSS is included, Bootstrap is included, Angular 1.6.1, is being used. All of the html is contained in main.container-fluid(ng-app="root"). Thank you in advance!

答: Figured it out thanks to the codePen posted by karthick! My HTML was missing ng-controller="index" on the form element. Without the controller, the $scope does not know where to be applied (I believe). Thank you again to karthick!

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to learn Angular simultaneously with Pug and SCSS, my current issue is with the ng-class concept. My code is as follows:

HTML (In Pug)

form
   input#theSearch(type='text' ng-model="theSearch")
   br
   span(ng-class ="{'test': isEven()}") Example Text

SCSS

.test {
    color:red;
    font-size:80px;
}

AngularJS

angular.module("root", [])
   .controller("index",["$scope",function($scope) {
     $scope.theSearch = 1;
     $scope.isEven = function () { return $scope.theSearch % 2 === 0; };
}]);

So, ideally this will react when the user inputs an even number and turn the span red as well as increasing the size. Currently, it does not change despite even inputs. I suspect this is some rookie syntax mistake but any guidance on the issue would be most appreciated.

Side Notes:
I'm in the CodePen environment. Pug is included, SCSS is included, Bootstrap is included, Angular 1.6.1, is being used. All of the html is contained in main.container-fluid(ng-app="root"). Thank you in advance!


问:
Creating the perfect resume - Anyway to put some sort of markdown in a resume that hides clipboard copy?
Note: not looking for a speicifc language implementation, just want to get poiinted in the right direction

This question is very broad and not specific and I probably will get downvoted for it but was curious:

Is there any way for me to programmatically create a webpage depicting a resume, such that when copy and pasted only some portions of it get copied to the clipboard?

We all know the situation where you have your resume with a header like:

```<code>Name
_____________________________
</code>```

Where that line seperator looks good on the resume, but on many modern applications it pulls info from the resume and autofills it and the line then looks messed up.

Is there any sort of solution, maybe some sort of markup of what can get copied to the clipboard or not?

答:
Sure. In one div, write the information you want to be copied separated by spaces and
 only. In a second div, write the nice formatting like your line separator, then use CSS to position the 2nd div over the first one. Or just wrap every formatting elements in a div and make them have user-select: none;

For example, see this:

#myinfo{
  width:400px;
  height:200px;
  position:absolute;
}

#fancy {
  width:400px;
  height:200px;
  position:absolute;
  user-select: none;
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="myinfo">
  <span>
  Bob Tables
  </span> <br />
  <span>Engineer</span>
  </div>
  <div id="fancy">__________</div>
</div></code>```

Now I'm not saying this is a good idea, you can probably achieve what you want without superposing two div as long as it's something CSS can do.

Body:
Note: not looking for a speicifc language implementation, just want to get poiinted in the right direction

This question is very broad and not specific and I probably will get downvoted for it but was curious:

Is there any way for me to programmatically create a webpage depicting a resume, such that when copy and pasted only some portions of it get copied to the clipboard?

We all know the situation where you have your resume with a header like:

Name
_____________________________

Where that line seperator looks good on the resume, but on many modern applications it pulls info from the resume and autofills it and the line then looks messed up.

Is there any sort of solution, maybe some sort of markup of what can get copied to the clipboard or not?

Body:
Sure. In one div, write the information you want to be copied separated by spaces and <br /> only. In a second div, write the nice formatting like your line separator, then use CSS to position the 2nd div over the first one. Or just wrap every formatting elements in a div and make them have user-select: none;

For example, see this:

#myinfo{
  width:400px;
  height:200px;
  position:absolute;
}

#fancy {
  width:400px;
  height:200px;
  position:absolute;
  user-select: none;
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
}

<div id="parent">
  <div id="myinfo">
  <span>
  Bob Tables
  </span> <br />
  <span>Engineer</span>
  </div>
  <div id="fancy">__________</div>
</div>

Now I'm not saying this is a good idea, you can probably achieve what you want without superposing two div as long as it's something CSS can do.


问:
React Native Android Run
I am just starting with react native. I created my first app using React Native CLI. It was created without any errors. When I am trying to react-native run-android It ends up with this error as shown.

答:
Make sure you have your device connected to your computer, you can check that by running:

```<code>adb devices
</code>```

if it's not connected, in your phone go to: settings > Developer Options > (enable) USB debugging.

Else if you want to run it from an emulator you will need to either install Genymotion, or AndroidStudio.

Title: React Native Android Run

Body:
Make sure you have your device connected to your computer, you can check that by running:

adb devices

if it's not connected, in your phone go to: settings > Developer Options > (enable) USB debugging.

Else if you want to run it from an emulator you will need to either install Genymotion, or AndroidStudio.


问:
Mocking non-public static methods in abstract classes with JMockit?
I have the following class:

```<code>public abstract class AbstractParent {
    static String method() {
        return "OriginalOutput";
    }
}
</code>```

I want to mock this method. I decide to use JMockit. So I create a mock class:

```<code>public class MockParent {
    static String method() {
        return "MOCK";
    }
}
</code>```

And my test code looks like this:

```<code>public class RealParentTest {

    @Before
    public void setUp() throws Exception {
        Mockit.redefineMethods( AbstractParent.class, MockParent.class );
    }

    @Test
    public void testMethod() {
        assertEquals(MockParent.method(),AbstractParent.method());
    }

}
</code>```

Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.

Edit Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.

Answer Only the mock method needs to be public, you can leave the original method as is.

答:
Apparently the new way to do this is to use MockUp<T>

```<code>new MockUp<AbstractParent>(){
    @Mock String method() {
        return "MOCK";
    }
};

assertEquals("MOCK" AbstractParent.method());
</code>```

Another alternative is apparently to continue with something like MockParent with a @MockClass annonation. Haven't done this myself as the another inline version does the job.

I've implemented this in an example project on github.

OwnerDisplayName: Epaga

ContentLicense: CC BY-SA 2.5

Body:
I have the following class:

public abstract class AbstractParent {
    static String method() {
        return "OriginalOutput";
    }
}

I want to mock this method. I decide to use JMockit. So I create a mock class:

public class MockParent {
    static String method() {
        return "MOCK";
    }
}

And my test code looks like this:

public class RealParentTest {

    @Before
    public void setUp() throws Exception {
        Mockit.redefineMethods( AbstractParent.class, MockParent.class );
    }

    @Test
    public void testMethod() {
        assertEquals(MockParent.method(),AbstractParent.method());
    }

}

Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.

Edit Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.

Answer Only the mock method needs to be public, you can leave the original method as is.

LastEditorDisplayName: Epaga

Body:
Apparently the new way to do this is to use MockUp<T>

new MockUp<AbstractParent>(){
    @Mock String method() {
        return "MOCK";
    }
};

assertEquals("MOCK" AbstractParent.method());

Another alternative is apparently to continue with something like MockParent with a @MockClass annonation. Haven't done this myself as the another inline version does the job.

I've implemented this in an example project on github.


问:
Putting Anaconda pip onto Flash drive and installing off it
I am unable to install pip normally because of a proxy at work.  I am going to use a flash drive to transfer it onto the computer.  Is it possible to put just pip onto a flashdrive and transfer it onto different computer to install? If so how?</p>

答:
Assuming you don't need to install PIP and you mean you can't use PIP in it's normal method to download/install a package from the internet, you can download the package onto a flash drive and then do:</p>

```<code>pip install /dir/package
</code>```

Body:
Assuming you don't need to install PIP and you mean you can't use PIP in it's normal method to download/install a package from the internet, you can download the package onto a flash drive and then do:

pip install /dir/package


问:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after th y are sent
I'm new to Node. I'm using express.js
There is a part of my code, where I'm trying to get data that I got from a form by AJAX and write this to variable url. I have request.body, but I can't pass it to "then". Instead of it, I have an error

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent.

Could you tell me what am I doing wrong? Thanks a lot.

```<code>    app.get('/', function (req, res) {
        return res.render('index.html').end();
    });

    app.post("/", jsonParser, function (request, response) {
        return new Promise((resolve, reject) => {
            if (!request.body) {
                reject()
            } else {
                console.log(request.body);
                response.json(`${request.body.url}`);
                url = response.json(`${request.body.url}`);
                resolve(url);
            }
        }).then(data => console.log(data));
    });
</code>```

答:
response.json is an express function that... sends a Json response.

You're calling it twice with

```<code>response.json(`${request.body.url}`);
url = response.json(`${request.body.url}`);
</code>```

but you cannot do that, you cannot send two responses for one request.

Just remove the first line.

Body:
I'm new to Node. I'm using express.js
There is a part of my code, where I'm trying to get data that I got from a form by AJAX and write this to variable url. I have request.body, but I can't pass it to "then". Instead of it, I have an error

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent.

Could you tell me what am I doing wrong? Thanks a lot.

    app.get('/', function (req, res) {
        return res.render('index.html').end();
    });

    app.post("/", jsonParser, function (request, response) {
        return new Promise((resolve, reject) => {
            if (!request.body) {
                reject()
            } else {
                console.log(request.body);
                response.json(`${request.body.url}`);
                url = response.json(`${request.body.url}`);
                resolve(url);
            }
        }).then(data => console.log(data));
    });

Body:
response.json is an express function that... sends a Json response.

You're calling it twice with

response.json(`${request.body.url}`);
url = response.json(`${request.body.url}`);

but you cannot do that, you cannot send two responses for one request.

Just remove the first line.


问:
cannot upgrade umbraco using nuget in visual studio 2013
I am upgrading Umbraco from 7.4.3 to 7.6.3.

I installed Umbraco 7.4.3 using nuget in VS2013. Now when I try to upgrade using nuget( Update-Package UmbracoCms),  I get the following error in VS2013:

The 'UmbracoCms 7.6.3' package requires NuGet client version '3.4.4' or above, but the current NuGet version is '2.12.0.817'

I checked here and it seem to me that NuGet client version '3.4.4' is for vs2015 only but I am using VS2013.

Is there any solution of this problem?

答:
You can use the command line nuget.exe 4.1.0 or higher (3.5.0 isn't able to use MSBuild 12) to perform the necessary commands (nuget.exe update to update the package, nuget.exe restore whenever you clone the project / do CI builds). But then you'll need to disable the VS-integrated NuGet restore.

Other option is to migrate to a newer version of visual studio to get VS-integrated support for new NuGet features.


问:
Business intelligence wont display data cube, problem with connectivity
I am using VS 2008 version 3.5 SP1 and MySQL server 2008 R2
When using business intelligence and when I start adding dimensions and so the database is connected fine and BI is retrieving the info, but when I make the data cube and click on process this happens http://img64.imageshack.us/img64/1597/errorhb.png

I did everything, I made sure that the browser service was enabled and I made sure of the server name ..etc but still no luck ...

答: Your screen shot suggests you're trying to connect to an instance of SQL Express. You can't build cubes on that version of SQL Server, you need Standard or above.</p>


问:
Multi-list iteration with default value in Python
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

```<code>heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]
</code>```

and the list of lists is:

```<code>params = [heights,alphas,C,B]
</code>```

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

```<code>instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}
</code>```

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

```<code>params = [[1,2,3],[4,5][7,8]]
</code>```

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

```<code>from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))
</code>```

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?

答:
Notice that the 2nd and 3rd instance of each tuple in the final list, is the products from only the 2nd and third row of the initial array

```<code>a, *b = params
# a = [1, 2, 3]
# b = [[4, 5], [7, 8]]
</code>```

Make a product out of all elements in b

```<code>import itertools

b = [x for x in itertools.product(*b)]
# b = [(4, 7), (4, 8), (5, 7), (5, 8)]
</code>```

Now do a product of a with all the values of b

```<code>c = [(a, b, c) for a, (b, c) in itertools.product(a, b)]

# c = [(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]
</code>```

Overall shortened:

```<code>import itertools

params = [[1,2,3],
          [4,5],
          [7,8]]

a, *b = params
f = itertools.product

c = [(a, b ,c) for a, (b, c) in f(a, f(*b))]
</code>```

Body:
I'm running an experiment with python simulation, and need to create a list of input cases.

Each case is an instance taken from a list of list of parameters, For example:

heights = [100,110,120]
alphas = [0.1,0.01,0.001]
C = [0.1,0.2,0.5,0.9]
B = [1,2]

and the list of lists is:

params = [heights,alphas,C,B]

The original amount is bigger (~30x100) so it's not efficient to address each list directly.

Eventually each input case is a tuple/namedtuple/dictionary of one parameter from each category, for example:

instance = {'height':100, 'alpha':0.1,'C:0.1, 'B':1}

I would like to iterate the parameter space in order to create a list of instances - but here is the catch:

Instead of making a cartesian product of all of them, per each parameter I want to iterate all the options, while the rest of categories are set to a default value (the first). For example:

params = [[1,2,3],[4,5][7,8]]

the expected set of instances (with no repeat) is:

[(1,4,7),(2,4,7),(3,4,7),(1,5,7)(1,4,8)]

where 1 is the default of first index, 4 is the default of the second index and 7 is the default of the 3rd.

Making a cartesian product is quite easy with itertools:

from itertools import product
params = [[1,2,3],[4,5],[7,8]]
list(product(*params))

[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

then I can filter out unnecessary instances, but it sounds ineficient to generate them at first place. Is there any elegant way to build this iteration?

Body:
Notice that the 2nd and 3rd instance of each tuple in the final list, is the products from only the 2nd and third row of the initial array

a, *b = params
# a = [1, 2, 3]
# b = [[4, 5], [7, 8]]

Make a product out of all elements in b

import itertools

b = [x for x in itertools.product(*b)]
# b = [(4, 7), (4, 8), (5, 7), (5, 8)]

Now do a product of a with all the values of b

c = [(a, b, c) for a, (b, c) in itertools.product(a, b)]

# c = [(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

Overall shortened:

import itertools

params = [[1,2,3],
          [4,5],
          [7,8]]

a, *b = params
f = itertools.product

c = [(a, b ,c) for a, (b, c) in f(a, f(*b))]


问:
In Power Builder trying to replace a escape character with ~ sign
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

```<code>Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")
</code>```

Any help here please.

答:
Tilde is a modifier character in PowerBuilder. The first function it has is to represent special characters, so you have ~r, ~n, ~t for carriage return, newline, and tab.
The second function is an escape that removes any special meaning of the following character. This allows you to write things like "~"" to make a string that contains a quote character. In that case it's better to write '"', but if you've already done that and want a single quote you have to escape it. Creating expressions for the DataWindow requires additional levels of escaping that I won't get into here. What's happening when you write "~'" is that the tilde tells PowerBuilder to treat the single quote as an ordinary character. It would do that anyway in this case since it's not inside a single-quoted string. That's why you're replacing the ' with another '. If you want ~' you have to write "~~'". The first tilde tells PowerBuilder to treat the following tilde as a regular character, and you end up with ~'. PowerBuilder help lists ~~ as the special character for tilde, and ~' and ~" for the quote characters but when you work with more than one level of escaping you're better off treating it as an escape and working left to right.

Body:
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")

Any help here please.


问:
Call function after time delay and then faster
I know about setInterval( foo, n) that it calls foo every n seconds.
But how can I do to call it faster and faster? Like after the first time, the function will be called again in n-1 seconds, then n-2 seconds, and so on.

答:
You can use setTimeout(foo, n) in combination with foo.bind instead, and then recursively call your function.

Example


问:
Replace part of columns string value
I have a column with values like /i/t/item_xxl_12063874_18123233.jpg. I need a formula to get a string value item_xxl_12063874_18123233.jpg.

答:
Another approach is to find the text "item" as follows:

```<code>=MID(A1,FIND("item",A1,1),LEN(A1))
</code>```

you can change the text you search for as necessary and it does not matter how many are before the text you search for as long as it only occurs once.

Title: Replace part of columns string value

Body:
Another approach is to find the text "item" as follows:

=MID(A1,FIND("item",A1,1),LEN(A1))

you can change the text you search for as necessary and it does not matter how many are before the text you search for as long as it only occurs once.


问:
Implementation of flatMap() for State transition
Exercise 6.8, Chiusano and Bjarnason, Functional Programming in Scala, p. 87 asks how one might implement flatMap() for the following trait:

```<code>trait RNG {
  def nextInt: (Int, RNG)
}

type Rand[+A] = RNG => (A, RNG)
</code>```

The answer key gives the following solution:

```<code>def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
rng => {
  val (a, r1) = f(rng)
  g(a)(r1) // We pass the new state along
}
</code>```

Stackoverflow provides many answers to flatMap()/monad questions, but none which for me answered my questions regarding the next to last line of code.

I do not understand the syntax of the line

```<code>g(a)(r1)
</code>```

(1) I do not understand how g(a)(r1) evaluates. What syntactic function is served by (r1)? The line does not exemplify currying, I do not believe, since g takes only one argument: A.
(2) If g(a) will already return the type Rand[B], then why does not the line end here?
(3) what is the relation between the Rand[B] returned by g(a) and the second set of parentheses: (r1)?
(4) if the return type of this implementation of flatMap() is Rand[B], which is equal to RNG => (A, RNG), how are the enclosing parentheses to the right of the arrow generated? If I had to guess I would say they are generated by the evaluation, (r1), but I do not really understand this code given my questions 1 through 3.

答:
Remember that we're calling f and g inside a new anonymous function, as indicated by the line

```<code>rng => { ... }
</code>```

g returns a Rand[B] when given an A, so g(a) evaluates to a function from RNG to (A, RNG).

So g(a) returns a function expecting an RNG as its argument, we can then call this with our r1, which is of type RNG.

The result of the call is (B, RNG). Now since the flatMap signature expects you to return a Rand[B] which is the same as RNG => (B, RNG) and we return (B, RNG) inside our function, it exactly matches the signature.

Body:
Exercise 6.8, Chiusano and Bjarnason, Functional Programming in Scala, p. 87 asks how one might implement flatMap() for the following trait:

trait RNG {
  def nextInt: (Int, RNG)
}

type Rand[+A] = RNG => (A, RNG)

The answer key gives the following solution:

def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
rng => {
  val (a, r1) = f(rng)
  g(a)(r1) // We pass the new state along
}

Stackoverflow provides many answers to flatMap()/monad questions, but none which for me answered my questions regarding the next to last line of code.

I do not understand the syntax of the line

g(a)(r1)

(1) I do not understand how g(a)(r1) evaluates. What syntactic function is served by (r1)? The line does not exemplify currying, I do not believe, since g takes only one argument: A.
(2) If g(a) will already return the type Rand[B], then why does not the line end here?
(3) what is the relation between the Rand[B] returned by g(a) and the second set of parentheses: (r1)?
(4) if the return type of this implementation of flatMap() is Rand[B], which is equal to RNG => (A, RNG), how are the enclosing parentheses to the right of the arrow generated? If I had to guess I would say they are generated by the evaluation, (r1), but I do not really understand this code given my questions 1 through 3.

Body:
Remember that we're calling f and g inside a new anonymous function, as indicated by the line

rng => { ... }

g returns a Rand[B] when given an A, so g(a) evaluates to a function from RNG to (A, RNG).

So g(a) returns a function expecting an RNG as its argument, we can then call this with our r1, which is of type RNG.

The result of the call is (B, RNG). Now since the flatMap signature expects you to return a Rand[B] which is the same as RNG => (B, RNG) and we return (B, RNG) inside our function, it exactly matches the signature.


问:
VSTS unit tests for .Net Core project: Tests not discovered
I have a .Net core that builds successfully using VSTS. The issue I'm presenting is that Unit Tests aren't being discovered when building the project. I know this is similar to this post but I just wanted to bring up more details in case someone has a good idea seeing this description.

This a summary of the logs:

##[warning]Project file(s) matching the specified pattern were not found.

##[section]Finishing: Test.

I'm concerned about the minimatch pattern used here. It seems is looking for a Tests folder and then any file that ends in .csproj

The default agent queue is Hosted VS2017 as indicated by @starain-MSFT in previous post

The solution structure is described in the next image, is pretty basic:

A .Net Core project with a model class.

A MS Unit Test Project (That contains a reference to the mentioned class).

A [TestClass] with a single [TestMethod] that pass the test.

答:
Well, it resulted that my concern was the key factor to solve my issue.
I just made a little reverse engineer with an MVC project, the default minimatch pattern is different for this type of project, (**\$(BuildConfiguration)\*test*.dll !**\obj\**)

You can learn more about minimatch here.

So I just wanted to look for a .csproj file that contains the word Tests, therefore I changed it to **/*Tests*.csproj instead of **/*Tests/*.csproj.

Now I'm able to see that my unit tests are being executed right away when there is a new build.

I hope that my issue and resolution helps saving other people's time!


问:
Problem rotating simple line image
It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point.
Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.

Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):

```<code>x0:=200;
y0:=200;

  bx:=StrToInt(Edit1.Text);
  by:=StrToInt(Edit2.Text);
  cx:=StrToInt(Edit4.Text);
  cy:=StrToInt(Edit5.Text);
  a:=StrToInt(Edit3.Text);

  //Original triangle

  Form1.Canvas.Pen.Color:=clBlue;
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(bx,by);
  Form1.Canvas.LineTo(cx,cy);
  Form1.Canvas.LineTo(x0,y0);

  //New triangle
  Form1.Canvas.Pen.Color:=clGreen;
  Form1.Canvas.MoveTo(x0,y0);
  b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));
  b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
  c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180));
  c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
  Form1.Canvas.LineTo(b1x,b1y);
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(c1x,c1y);
  Form1.Canvas.LineTo(b1x,b1y);

end;
</code>```

Well, I'm out of ideas. What am I doing wrong?

Thanks for your time.

答:
The formula you are using rotates a point around (0, 0). To achieve the required result change your calculation to:</p>

```<code>b1x:=x0 + Round((bx-x0)*cos(a*pi/180)-(by-y0)*sin(a*pi/180));
b1y:=y0 + Round((bx-x0)*sin(a*pi/180)+(by-y0)*cos(a*pi/180));
c1x:=x0 + Round((cx-x0)*cos(a*pi/180)-(cy-y0)*sin(a*pi/180));
c1y:=y0 + Round((cx-x0)*sin(a*pi/180)+(cy-y0)*cos(a*pi/180));
</code>```

Title: Problem rotating simple line image

Body:
It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point.
Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.

Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):

x0:=200;
y0:=200;

  bx:=StrToInt(Edit1.Text);
  by:=StrToInt(Edit2.Text);
  cx:=StrToInt(Edit4.Text);
  cy:=StrToInt(Edit5.Text);
  a:=StrToInt(Edit3.Text);

  //Original triangle

  Form1.Canvas.Pen.Color:=clBlue;
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(bx,by);
  Form1.Canvas.LineTo(cx,cy);
  Form1.Canvas.LineTo(x0,y0);

  //New triangle
  Form1.Canvas.Pen.Color:=clGreen;
  Form1.Canvas.MoveTo(x0,y0);
  b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));
  b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
  c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180));
  c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
  Form1.Canvas.LineTo(b1x,b1y);
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(c1x,c1y);
  Form1.Canvas.LineTo(b1x,b1y);

end;

Well, I'm out of ideas. What am I doing wrong?

Thanks for your time.

Body:
The formula you are using rotates a point around (0, 0). To achieve the required result change your calculation to:

b1x:=x0 + Round((bx-x0)*cos(a*pi/180)-(by-y0)*sin(a*pi/180));
b1y:=y0 + Round((bx-x0)*sin(a*pi/180)+(by-y0)*cos(a*pi/180));
c1x:=x0 + Round((cx-x0)*cos(a*pi/180)-(cy-y0)*sin(a*pi/180));
c1y:=y0 + Round((cx-x0)*sin(a*pi/180)+(cy-y0)*cos(a*pi/180));


问:
What login did a person get authenticated under?
We have a new intern and he is able to log into our dev environment.  However, I can't figure out how.  We have AD Security Groups as our Logins in SQL Server.  After a lot of research with our server guys we figured out that the intern group is part of the local admin group on our development servers.  The local admin group has a login to SQL Server and that is how he was able to get in.  This brought about the following question.

In SQL Server is there a way to tell what login a person is authenticated under?

Scenario:

```<code>Domain = ACME

User = Bob

Bob is in the AD group ACME\IT-Dept

SQL Server has a login for ACME\IT-Dept
</code>```

How can I tell that Bob was allowed in via the login for ACME\IT-Dept without knowing that Bob is in that group?

答:
Yuo can find it out in following ways:

By impersonating that login and querying sys.login_token like this:

```<code>execute as login = 'that_login';

select distinct name, type
from sys.login_token
where principal_id > 0
      and type in ('WINDOWS LOGIN', 'WINDOWS GROUP');

revert;
</code>```

Looking at the permission path:

```<code> exec xp_logininfo 'that_login', 'all';
</code>```

I prefer the first one as more reliable

Body:
We have a new intern and he is able to log into our dev environment.  However, I can't figure out how.  We have AD Security Groups as our Logins in SQL Server.  After a lot of research with our server guys we figured out that the intern group is part of the local admin group on our development servers.  The local admin group has a login to SQL Server and that is how he was able to get in.  This brought about the following question.

In SQL Server is there a way to tell what login a person is authenticated under?

Scenario:

Domain = ACME

User = Bob

Bob is in the AD group ACME\IT-Dept

SQL Server has a login for ACME\IT-Dept

How can I tell that Bob was allowed in via the login for ACME\IT-Dept without knowing that Bob is in that group?

Body:
Yuo can find it out in following ways:

By impersonating that login and querying sys.login_token like this:

execute as login = 'that_login';

select distinct name, type
from sys.login_token
where principal_id > 0
      and type in ('WINDOWS LOGIN', 'WINDOWS GROUP');

revert;

Looking at the permission path:

 exec xp_logininfo 'that_login', 'all';

I prefer the first one as more reliable


问:
Read.csv returns an error: Cannot Open Connection
I have a strange problem. I want to read a CSV file, and I am perfectly able to do so in my console, but when I do the exact same line in my R markdown file, I get the error:

```<code>Error in file(file, "rt") : cannot open the connection
</code>```

Why can I read the file in the console but not in the R Markdown file?

答:
Working directory of your Rmd differs from the ones of your R console. You should explicitly define the path to your file in the Rmd to avoid the error.

Another option would be moving your csv files to the folder that your markdown is existed.

In sum, You need to consider where the Rmd is, where the current directory of your console is and where your files are. If necessary move the files or change the directory or use explicit path.

Using getwd() you can get the current working directory for your markdown or your console.

ContentLicense: CC BY-SA 4.0

Body:
I have a strange problem. I want to read a CSV file, and I am perfectly able to do so in my console, but when I do the exact same line in my R markdown file, I get the error:

Error in file(file, "rt") : cannot open the connection

Why can I read the file in the console but not in the R Markdown file?


问:
How to efficently parse a string of latitude/longitude points to an array of object in JS?
I receive a series of latitude/longitude points in a string (from a third party) with the following format (of course there can be more than 2 set of pairs):

```<code>[(49.0000, -105.0000), (49.0000, -110.0000)]
</code>```

and I want to convert that string to an array of object like this:

```<code>[{lat: 49.0000, lng: -105.0000}, {lat: 49.0000, lng: -110.0000}]
</code>```

I want to do this in pure JavaScript but would be open to use jQuery if it simplifies the code a lot.

Currently, I use some regex and substrings on the source string but I'm wondering if there more elegant way to do this conversion that I could have missed?

答: Use JSON.parse(dataString) to achieve array of objects with lat/lng fields. If it's not solve your problem, than provide  addition information.

Body:
I receive a series of latitude/longitude points in a string (from a third party) with the following format (of course there can be more than 2 set of pairs):

[(49.0000, -105.0000), (49.0000, -110.0000)]

and I want to convert that string to an array of object like this:

[{lat: 49.0000, lng: -105.0000}, {lat: 49.0000, lng: -110.0000}]

I want to do this in pure JavaScript but would be open to use jQuery if it simplifies the code a lot.

Currently, I use some regex and substrings on the source string but I'm wondering if there more elegant way to do this conversion that I could have missed?


问:
Saving data with dynamic input name to database?
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

```<code><input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">
</code>```

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

```<code>*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1
</code>```

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

```<code>    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store
</code>```

So the final result will be like this:

```<code>id_user : 1
id_item : 5
Store : 3
Take : 2
</code>```

And like this

```<code>id_user : 1
id_item : 6
Store : 1
Take : 1
</code>```

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)

答:
After few hours searching finally i found the answer

I decided to change a bit for the input form.

```<code><input type="text" name="<?php this is id_item?>[0]"> // this array [0] will be assign for 'store' section

<input type="text" name="<?php this is id_item?>[1]"> // this array [1] will be assign for 'take' section
</code>```

I also add 1 input type=hidden for retrieving id_item

```<code><input type="hidden" name="<?php this is id_item ?>[2]" value="<?php this is id_item ?>"> //this array [2] will be assign for send 'id_item' value.
</code>```

And loop the content for receive tha data

```<code>    for($i=0;$i<How much row i have;$i++){
        $store=intval($my_array[$i][0]);
        $take=intval($my_array[$i][1]);
        $amount=$store-$take;
        $id_item=$my_array[$i][2];
        /////////////////////////////////////
        And do insert command to database right here
</code>```

It's not pretty i know, but it will do the job.

Thankyou for answering and comment on my question :)

Body:
Allright, before that i'm a beginner in PHP.
So forgive me for this silly question.

Say that id_user '1' have 2 items, so it will create 2 input form for each item.

These are the input forms:

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '5'" ?>" required="required">

<input value="0" type="text" name="store_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

<input value="0" type="text" name="take_<?php echo $id= "I got this value from id.item in database, in this case '6'" ?>" required="required">

Note : value take_{id} and store_{id} are retrieved from table 'item' coloumn 'id_item' in database.

The user input these values :

*value 'store' for id_item 5 is 3
*value 'take' for id_item 5 is 2
*value 'store' for id_item 6 is 1
*value 'take' for id_item 6 is 1

How do i save value 'store' and 'take' from user input to database with their associated id?
Considering 1 user can have multiple item.

This is table item.

    ->id_user (referencing id_user from user's table)
    ->id_item # this primary key
    ->Take
    ->Store

So the final result will be like this:

id_user : 1
id_item : 5
Store : 3
Take : 2

And like this

id_user : 1
id_item : 6
Store : 1
Take : 1

I've been googled all day, and i think regex with pattern 'store_' and 'take_' should do it? or there is another way to accomplish this?

Thankyou :)

Body:
After few hours searching finally i found the answer

I decided to change a bit for the input form.

<input type="text" name="<?php this is id_item?>[0]"> // this array [0] will be assign for 'store' section

<input type="text" name="<?php this is id_item?>[1]"> // this array [1] will be assign for 'take' section

I also add 1 input type=hidden for retrieving id_item

<input type="hidden" name="<?php this is id_item ?>[2]" value="<?php this is id_item ?>"> //this array [2] will be assign for send 'id_item' value.

And loop the content for receive tha data

    for($i=0;$i<How much row i have;$i++){
        $store=intval($my_array[$i][0]);
        $take=intval($my_array[$i][1]);
        $amount=$store-$take;
        $id_item=$my_array[$i][2];
        /////////////////////////////////////
        And do insert command to database right here

It's not pretty i know, but it will do the job.

Thankyou for answering and comment on my question :)


问:
XS: Passing an external library's function a Perl XS callback
Disclaimer: asked over at perlmonks.

I hope I'm describing and depicting my issue properly... In XS, I'm trying to send a callback into an external library's function, where the callback has Perl specific functions. The XSUB is passed as a function pointer to an external C function. The XSUB callback being sent in turn calls back to a sub in the `main` perl application:

```<code>void callback(){
    dSP;
    PUSHMARK(SP);
    call_pv("p_callback", G_DISCARD|G_NOARGS);
}

// example extern call

externFunc(&callback);
</code>```

This segfaults. I think it's because the external library doesn't understand the perl functions that are being called. Things work fine if I call the C `callback()` function directly though.

Is there some magic that I can do to make the external library "see" the Perl C functions, or am I doing something wrong?

Here's the code I'm testing with:

```<code>use warnings;
use strict;

use Inline ('C' => 'DATA', libs => '-lwiringPi');

init();
setInterrupt(27, 3);

# direct call

callback();

# on() triggers the external function and sends
# it the callback

on(27);

sub p_callback {
    print "in perl callback\n";
}

__DATA__
__C__

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

void init();
void on(int pin);
void off(int pin);
void setInterrupt(int pin, int edge);
void callback();

void init(){
    printf("in init\n");
    wiringPiSetup();
}
void on(int pin){
    pinMode(pin, 1);
    digitalWrite(pin, 1);
}

void off(int pin){
    digitalWrite(pin, 0);
    pinMode(pin, 0);
}

void setInterrupt(int pin, int edge){
    wiringPiISR(pin, edge, &callback);
}

void callback(){
    dSP;
    PUSHMARK(SP);
    call_pv("p_callback", G_DISCARD|G_NOARGS);
}
</code>```

Output:

```<code>in init
in perl callback
Segmentation fault
</code>```

If I remove the perl specific C calls from within the callback and just do a `printf()` or other pure-C work, things proceed without a segfault.

答:
Just came across this question and thought I'd give it my own answer as I did resolve it some time ago.

There were some important bits I was missing to set the Perl context, as well as within the C exec_perl_callback() function.

```<code>use warnings;
use strict;

use Inline 'C';
use Inline 'NoClean';

sub p_callback {
    print "hello, world from perl!\n";
}

exec_perl_callback('p_callback');

__END__
__C__

#define PERL_NO_GET_CONTEXT

PerlInterpreter * mine;

void callback(char* perl_callback){
    PERL_SET_CONTEXT(mine);

    dSP;
    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    PUTBACK;

    exec_perl_callback(perl_callback, G_DISCARD|G_NOARGS);

    FREETMPS;
    LEAVE;
}
</code>```

Output:

```<code>hello world, from perl!
</code>```

Body:
Disclaimer: asked over at perlmonks.

I hope I'm describing and depicting my issue properly... In XS, I'm trying to send a callback into an external library's function, where the callback has Perl specific functions. The XSUB is passed as a function pointer to an external C function. The XSUB callback being sent in turn calls back to a sub in the `main` perl application:

void callback(){
    dSP;
    PUSHMARK(SP);
    call_pv("p_callback", G_DISCARD|G_NOARGS);
}

// example extern call

externFunc(&callback);

This segfaults. I think it's because the external library doesn't understand the perl functions that are being called. Things work fine if I call the C `callback()` function directly though.

Is there some magic that I can do to make the external library "see" the Perl C functions, or am I doing something wrong?

Here's the code I'm testing with:

use warnings;
use strict;

use Inline ('C' => 'DATA', libs => '-lwiringPi');

init();
setInterrupt(27, 3);

# direct call

callback();

# on() triggers the external function and sends
# it the callback

on(27);

sub p_callback {
    print "in perl callback\n";
}

__DATA__
__C__

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

void init();
void on(int pin);
void off(int pin);
void setInterrupt(int pin, int edge);
void callback();

void init(){
    printf("in init\n");
    wiringPiSetup();
}
void on(int pin){
    pinMode(pin, 1);
    digitalWrite(pin, 1);
}

void off(int pin){
    digitalWrite(pin, 0);
    pinMode(pin, 0);
}

void setInterrupt(int pin, int edge){
    wiringPiISR(pin, edge, &callback);
}

void callback(){
    dSP;
    PUSHMARK(SP);
    call_pv("p_callback", G_DISCARD|G_NOARGS);
}

Output:

in init
in perl callback
Segmentation fault

If I remove the perl specific C calls from within the callback and just do a `printf()` or other pure-C work, things proceed without a segfault.

Body:
Just came across this question and thought I'd give it my own answer as I did resolve it some time ago.

There were some important bits I was missing to set the Perl context, as well as within the C exec_perl_callback() function.

use warnings;
use strict;

use Inline 'C';
use Inline 'NoClean';

sub p_callback {
    print "hello, world from perl!\n";
}

exec_perl_callback('p_callback');

__END__
__C__

#define PERL_NO_GET_CONTEXT

PerlInterpreter * mine;

void callback(char* perl_callback){
    PERL_SET_CONTEXT(mine);

    dSP;
    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    PUTBACK;

    exec_perl_callback(perl_callback, G_DISCARD|G_NOARGS);

    FREETMPS;
    LEAVE;
}

Output:

hello world, from perl!


问:
Combined mean and standard deviation from a collection of NumPy arrays of different shapes
Let's say I have Numpy arrays with shapes

```<code>(682, 89, 138)
(2668, 76, 89)
(491, 62, 48)
</code>```

How should I calculate the mean and standard deviation of all three arrays combined? If they were the same shapes, I could use np.stack() and then get the mean and std of the resulting array.

Is it possible to do this with different sized dimensions? Or would I have to reshape before getting the mean and std?

答:
We could use the formula of standard deviation and mean to compute those two scalar values for all input arrays without concatenating/stacking (that could be costly specially on large NumPy arrays). Let's do it in steps - mean and then standard deviation, as it seems we could use mean in std computations.

Getting the combined mean value :

So, we will start with the mean/averaging. For this, we would get the summation scalar for each array. Then, get the total summation and finally divide by the number of elements in all arrays.

Getting the combined standard deviation value :

For standard deviation, we have the formula as :

So, we will use the combined mean value obtained from previous step, use the std formula to get the squared differentiation, divide by the total number of elements across all arrays and then apply square root.

Implementation

Let's say the input arrays are a and b, we would have one solution, like so -

```<code>N = float(a.size + b.size)
mean_ = (a.sum() + b.sum())/N
std_ = np.sqrt((((a - mean_)**2).sum() + ((b - mean_)**2).sum())/N)
</code>```

Sample run for verification

```<code>In [266]: a = np.random.rand(3,4,2)
     ...: b = np.random.rand(2,5,3)
     ...:

In [267]: N = float(a.size + b.size)
     ...: mean_ = (a.sum() + b.sum())/N
     ...: std_ = np.sqrt((((a - mean_)**2).sum() + ((b - mean_)**2).sum())/N)
     ...:

In [268]: mean_
Out[268]: 0.47854757879348042

In [270]: std_
Out[270]: 0.27890341338373376
</code>```

Now, to verify, let's stack and then use relevant ufuncs -

```<code>In [271]: A = np.hstack((a.ravel(), b.ravel()))

In [273]: A.mean()
Out[273]: 0.47854757879348037

In [274]: A.std()
Out[274]: 0.27890341338373376
</code>```

List of arrays as input

For a list holding all those arrays, we need to iterate through them, like so -

```<code>A = [a,b,c] # input list of arrays

N = float(sum([i.size for i in A]))
mean_ = sum([i.sum() for i in A])/N
std_ = np.sqrt(sum([((i-mean_)**2).sum() for i in A])/N)
</code>```

Sample run -

```<code>In [301]: a = np.random.rand(3,4,2)
     ...: b = np.random.rand(2,5,3)
     ...: c = np.random.rand(7,4)
     ...:

In [302]: A = [a,b,c] # input list of arrays
     ...: N = float(sum([i.size for i in A]))
     ...: mean_ = sum([i.sum() for i in A])/N
     ...: std_ = np.sqrt(sum([((i-mean_)**2).sum() for i in A])/N)
     ...: print mean_, std_
     ...:
0.47703535428 0.293308550786

In [303]: A = np.hstack((a.ravel(), b.ravel(), c.ravel()))
     ...: print A.mean(), A.std()
     ...:
0.47703535428 0.293308550786
</code>```

Body:
Let's say I have Numpy arrays with shapes

(682, 89, 138)
(2668, 76, 89)
(491, 62, 48)

How should I calculate the mean and standard deviation of all three arrays combined? If they were the same shapes, I could use np.stack() and then get the mean and std of the resulting array.

Is it possible to do this with different sized dimensions? Or would I have to reshape before getting the mean and std?

Body:
We could use the formula of standard deviation and mean to compute those two scalar values for all input arrays without concatenating/stacking (that could be costly specially on large NumPy arrays). Let's do it in steps - mean and then standard deviation, as it seems we could use mean in std computations.

Getting the combined mean value :

So, we will start with the mean/averaging. For this, we would get the summation scalar for each array. Then, get the total summation and finally divide by the number of elements in all arrays.

Getting the combined standard deviation value :

For standard deviation, we have the formula as :

So, we will use the combined mean value obtained from previous step, use the std formula to get the squared differentiation, divide by the total number of elements across all arrays and then apply square root.

Implementation

Let's say the input arrays are a and b, we would have one solution, like so -

N = float(a.size + b.size)
mean_ = (a.sum() + b.sum())/N
std_ = np.sqrt((((a - mean_)**2).sum() + ((b - mean_)**2).sum())/N)

Sample run for verification

In [266]: a = np.random.rand(3,4,2)
     ...: b = np.random.rand(2,5,3)
     ...:

In [267]: N = float(a.size + b.size)
     ...: mean_ = (a.sum() + b.sum())/N
     ...: std_ = np.sqrt((((a - mean_)**2).sum() + ((b - mean_)**2).sum())/N)
     ...:

In [268]: mean_
Out[268]: 0.47854757879348042

In [270]: std_
Out[270]: 0.27890341338373376

Now, to verify, let's stack and then use relevant ufuncs -

In [271]: A = np.hstack((a.ravel(), b.ravel()))

In [273]: A.mean()
Out[273]: 0.47854757879348037

In [274]: A.std()
Out[274]: 0.27890341338373376

List of arrays as input

For a list holding all those arrays, we need to iterate through them, like so -

A = [a,b,c] # input list of arrays

N = float(sum([i.size for i in A]))
mean_ = sum([i.sum() for i in A])/N
std_ = np.sqrt(sum([((i-mean_)**2).sum() for i in A])/N)

Sample run -

In [301]: a = np.random.rand(3,4,2)
     ...: b = np.random.rand(2,5,3)
     ...: c = np.random.rand(7,4)
     ...:

In [302]: A = [a,b,c] # input list of arrays
     ...: N = float(sum([i.size for i in A]))
     ...: mean_ = sum([i.sum() for i in A])/N
     ...: std_ = np.sqrt(sum([((i-mean_)**2).sum() for i in A])/N)
     ...: print mean_, std_
     ...:
0.47703535428 0.293308550786

In [303]: A = np.hstack((a.ravel(), b.ravel(), c.ravel()))
     ...: print A.mean(), A.std()
     ...:
0.47703535428 0.293308550786


问:
Mass delete Cloudwatch log groups using Boto3 - delete_log_group
I have a pretty lengthy list of cloudwatch log groups i need to delete....like close to a hundred. Since you have to delete them one at a time I thought a little python script could help me out but now im stuck.

here's my script so far...

```<code>import boto3
from botocore.exceptions import ClientError
import json

#Connect to AWS using default AWS credentials in awscli config
cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='/aws/lambda/staging-east1-'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

#   cwlogs.delete_log_group(
#       logGroupName='string'   <---here is where im stuck
#   )
</code>```

How do I take the value of 'logGroupName' in i and convert it to a string that the delete_log_group command can use and iterate through to delete all of my log groups I need to be gone?
I tried using json.loads and it errored out with the following...

Traceback (most recent call last):
File "CWLogCleaner.py", line 18, in
file_parsed = json.loads(f)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

Or am I totally going about this the wrong way?

TIA

答:
Heres what I got working for me. Im sure this is hackey and im no developer but it worked for me...</p>

```<code>cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='ENTER NAME OF YOUR LOG GROUP HERE'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

for i in file_parsed['logGroups']:
    cwlogs.delete_log_group(
        logGroupName=(i['logGroupName'])
    )
</code>```

Body:
I have a pretty lengthy list of cloudwatch log groups i need to delete....like close to a hundred. Since you have to delete them one at a time I thought a little python script could help me out but now im stuck.

here's my script so far...

import boto3
from botocore.exceptions import ClientError
import json

#Connect to AWS using default AWS credentials in awscli config
cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='/aws/lambda/staging-east1-'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

#   cwlogs.delete_log_group(
#       logGroupName='string'   <---here is where im stuck
#   )

How do I take the value of 'logGroupName' in i and convert it to a string that the delete_log_group command can use and iterate through to delete all of my log groups I need to be gone?
I tried using json.loads and it errored out with the following...

Traceback (most recent call last):
File "CWLogCleaner.py", line 18, in
file_parsed = json.loads(f)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

Or am I totally going about this the wrong way?

TIA

Body:
Heres what I got working for me. Im sure this is hackey and im no developer but it worked for me...

cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='ENTER NAME OF YOUR LOG GROUP HERE'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

for i in file_parsed['logGroups']:
    cwlogs.delete_log_group(
        logGroupName=(i['logGroupName'])
    )


问:
Finding First day of week via php

Possible Duplicate:

  Get first day of week in PHP?

Hi,

I want to find first and last date of current week and last week.
Similarly I want to find first and last date of current month and last month.

This has to be done in PHP. Please help.

答:
strtotime is quite powerful with relative time formats:

```<code>strtotime('monday this week');
strtotime('sunday this week');
strtotime('monday last week');
strtotime('sunday last week');
</code>```

(this only works with PHP 5.3+)

```<code>strtotime('first day of this month');
strtotime('last day of this month');
strtotime('first day of last month');
strtotime('last day of last month');
</code>```

In order to get the first and last date of a month in PHP < 5.3, you can use a combination of mktime and date (date('t') gives the number of days of the month):

```<code>mktime(0,0,0,null, 1); // gives first day of current month
mktime(0,0,0,null, date('t')); // gives last day of current month

$lastMonth = strtotime('last month');
mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month
mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month
</code>```

If you just want to get a string for presentation, then you don't need mktime:

```<code>date('Y-m-1'); // first day current month
date('Y-m-t'); // last day current month
date('Y-m-1', strtotime('last month')); // first day last month
date('Y-m-t', strtotime('last month')); // last day last month
</code>```

Title: Finding First day of week via php

Body:
strtotime is quite powerful with relative time formats:

strtotime('monday this week');
strtotime('sunday this week');
strtotime('monday last week');
strtotime('sunday last week');

(this only works with PHP 5.3+)

strtotime('first day of this month');
strtotime('last day of this month');
strtotime('first day of last month');
strtotime('last day of last month');

In order to get the first and last date of a month in PHP < 5.3, you can use a combination of mktime and date (date('t') gives the number of days of the month):

mktime(0,0,0,null, 1); // gives first day of current month
mktime(0,0,0,null, date('t')); // gives last day of current month

$lastMonth = strtotime('last month');
mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month
mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month

If you just want to get a string for presentation, then you don't need mktime:

date('Y-m-1'); // first day current month
date('Y-m-t'); // last day current month
date('Y-m-1', strtotime('last month')); // first day last month
date('Y-m-t', strtotime('last month')); // last day last month


问:
jQuery select by custom attribute
Is it possible to select a div which has a custom attribute like the one below?</p>

```<code><div score="Result:78c61ce9">
</code>```

答:
you can try:</p>

```<code>$('td[score=value]')
</code>```

Title: jQuery select by custom attribute

Body:
you can try:

$('td[score=value]')


问:
How to cin values into a vector
I'm trying to ask the user to enter numbers that will be pushed into a vector,
then using a function call to count these numbers.

why is this not working?  I'm only able to count the first number.

```<code>template <typename T>
void write_vector(const vector<T>& V)
{
   cout << "The numbers in the vector are: " << endl;
  for(int i=0; i < V.size(); i++)
    cout << V[i] << " ";
}

int main()
{
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}
</code>```

答:
You can simply do this with the help of for loop

->Ask on runtime from a user  (how many inputs he want to enter) and the treat same like arrays.

```<code>int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }
</code>```

Title: How to cin values into a vector

Body:
I'm trying to ask the user to enter numbers that will be pushed into a vector,
then using a function call to count these numbers.

why is this not working?  I'm only able to count the first number.

template <typename T>
void write_vector(const vector<T>& V)
{
   cout << "The numbers in the vector are: " << endl;
  for(int i=0; i < V.size(); i++)
    cout << V[i] << " ";
}

int main()
{
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}

Body:
You can simply do this with the help of for loop

->Ask on runtime from a user  (how many inputs he want to enter) and the treat same like arrays.

int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }


问:
Which layer do repository interfaces belong when using DI?
I recently joined a large team/project that uses the repository pattern and dependency injection throughout the solution. I noticed that the repository interfaces were located in a Data layer project, requiring the Business layer project to depend directly on it. It is my understanding that when using DI you would want to reverse this dependency to decouple the business logic from data access (Data references interfaces from the Business layer). When I suggested this to the team, there was a mixed reaction. They didn't see the benefit and argued against it ("everyone knows not to directly reference the concrete types", "we'll never need to swap out our data access technology", etc.).

Is it good practice to keep repository interfaces in the same project as the implementation (Data layer)? If the Business layer only references the repository interfaces from Data layer, are there any drawbacks to this setup?

答:
It all depends. A wise man once said:

abstracts [should be] owned by the upper/policy layers

You might have read Mark Seemann's excellent book Dependency Injection in .NET, where he show cases this principle (see section 2.2 in the 1st edition and chapter 3 in the 2nd edition) with an example for the exact scenario you are describing (i.e. repository interface as part of the Domain Layer).

The most important argument that Mark Seemann gives for doing this is because it allows you to replace your Data Access technology with a different one, which might be a more likely scenario you might think, especially considering the world we live in right now where everything moves to the cloud and in the cloud you might not have (or want) to use the same Data Access technology.

But there are other reasons for wanting to isolate your core layer (the Domain layer) from the rest of the application and let everything depend on the most important part of the application.

One thing that comes to mind is to make it impossible for developers to accidentally couple this layer to Volatile (or impure) parts of the system that make it harder to change later on. The dependency on your Data Access functionality is one obvious thing, because it can make testing harder, but also think about accidentally coupling your Domain layer to System.Web, making it possible for developers to use HttpContext in that part of the system. Chances are quite big that once you have a dependency (from Domain layer to Data Access layer), it will become much harder to invert over time.

On the other hand, whether this high degree of isolation is beneficial to your application does obviously depends on a lot of factors. And especially when the application is already designed this way, it might be better to focus your attention on other improvements first.

Don't forget that the most important part of Dependency Inversion Principle (DIP) and Dependency Injection (DI) is that classes depend on abstractions. This enables loose coupling, and loose coupling improves maintainability. Since those developers already practice DI, they are already in a good place.

A typical improvement that I make is to get rid of most of the repositories, and introduce higher-level concepts such as a generic abstraction over business operations, a generic abstraction over queries and sometimes domain events. This limits the use of repositories to inside the Domain layer. When introducing this, this is a great moment to invert the dependencies for new (or migrated) code that uses these concepts instead of I[EntityName]Repository and I[EntityName]Service abstractions that are typically in violation of most of the SOLID principles anyway.

Another thing I advocate is to prevent the core layer of your application from having a dependency on a logger abstraction of some third party logging library. This again boils down to the DIP that states that the application should own the abstractions, which is not the case when the application depends on a third party abstraction. That's why I promote things like this.


问:
simple way to identify the user is having the account in Gmail?
Do any one say which is the simple way to identify the user is having the account in Gmail ?</p>

答: Do a DNS query on the domain portion of the email address and check the MX records to see if they are the ones for Gmail.  This should cover both normal Gmail addresses, as well as domains using Gmail.</p>


答:
You can try:

// your third party string
var string = '[(49.0000, -105.0000), (49.0000, -110.0000)]';

// make it a valid array of positions
// - basically changing parentheses to brackets
var array = string.replace(/[()]/g, function(d){
    return {
        '(' : '[',
        ')' : ']',
    }[d];
});

// now it is valid, parse it
array = JSON.parse(array);

// each item has lat/long in the positions 0/1, respectively
var result = array.map(function(item){
  return {
    lat: item[0],
    lng: item[1],
  };
});

console.log(result);```

Title: How to efficently parse a string of latitude/longitude points to an array of object in JS?


问:
LoRaWAN rfm95w API/connection
I'm working on a lorawan protocol with a RFM95W module and an Arduino Uno. I have some issues with the connection to my MultiTech gateway.

I'd like to use LMIC API but I didn't know how I can get the APPEUI, the DEVEUI, and the APPKEY if I tried a connection by OTAA and I have the same problem for the NWKSKEY, the APPSKEY, and the DEVADDR when I'm trying a TNB connection. And how can I know if my gateway supports these connections types?

If someone can explain to me where I can find this information, it will be nice.

Many thanks in anticipation of your response.

A.F.

答:
Unless your gateway has a Network Server embedded, you probably need to configure it to use an existing external (or setup your own) network server.

In case you don't want to mess (a lot) with setting this up, I encourage you to check https://www.thethingsnetwork.org/ which is basically a free & open-source worldwide LoRaWan network

Title: LoRaWAN rfm95w API/connection


问:
HTML Canvas floating effect
Possible fix (efficency/perfomance issue over time?)

```<code>let i = 0;
function float() {
    yPos += Math.sin(i);
    i += .01 * yVel;
}
</code>```

I'm trying to re-create the "floating" effect in HTML5 Canvas.
What I am trying to do is trying to get an image to "float" up and down.
The image is drawn and the the float() function is run to calculate the next y-position of the image. I have gotten it to float down, or up, but not how to change the direction after the image has floated example 100px (up or down). How would I do this?

I've uploaded the canvas here: https://stuff.darkleaks.net/HTML5%20WP/cheshire/

Ass you can see, the image floats down, and slows down. After it stops moving I want to change the floating direction. The float() function is where I try to do this.

```<code>   // Request animation frame
    const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

    // Canvas
    const c = document.getElementById('canvas');
    const ctx = c.getContext('2d');

    // Set full-screen
    c.width = window.innerWidth;
    c.height = window.innerHeight;

    // Framerate settings
    // Better not touch theese if you
    // do not know what you are doing
    let fps = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? 29 : 60;
    let now, delta;
    let then = Date.now();
    const interval = 1000 / fps;

    // Preparation below this comment line
    const background = new Image();
    const cheshire = new Image();
    const images = [background, cheshire];
    var imagesCount = images.length;

    background.onload = cheshire.onload;
    background.src = 'bg.png';
    cheshire.src = 'cheshire.png';

    let originalXPos = c.width / 2 - images[1].width / 2;
    let originalYPos = c.height / 2 - images[1].height / 2;
    let xPos = c.width / 2 - images[1].width / 2;
    let yPos = c.height / 2 - images[1].height / 2;
    let xVel = 0;
    let yVel = .5;

    // Draw
    function draw() {

        // Loop
        requestAnimationFrame(draw);
        now = Date.now();
        delta = now - then;

        if (delta > interval) {

            // Calculate then
            then = now - (delta % interval);

            // All your own stuff here
            drawImages();
            float();

        }

    }

    // Draw background
    function drawImages() {
        ctx.drawImage(images[0], 0, 0)
        ctx.drawImage(images[1], xPos, yPos);
    }

    function float() {

        yPos += 1 / yVel;
        yVel += .05;

        // IF the image has floated 100 px (up or down)
        // change direction

    }

    // Returns an random integer between
    // min and max
    function randInt(min, max) {
        max = max === undefined ? min - (min = 0) : max;
        return Math.floor(Math.random() * (max - min) + min);
    }

    // Cursor coordinates X & Y
    function clicked(e) {

        let x, y;

        if (e.offsetX) {
            x = e.offsetX;
            y = e.offsetY;
        } else if (e.layerX) {
            x = e.layerX;
            y = e.layerY;
        }

        // Do something...

    }

    $('canvas').on('click', function(e) {
        clicked(e);
    });

    requestAnimationFrame(draw);nter code here
</code>```

答:
To float down in your code as given in the question

```<code>// in the draw function
xPos += xVel;
yPos += yVel;
</code>```

Then check if the yPos is past some point and if so change direction

```<code>const bottom = ctx.canvas.height - 300; // put somewhere with globals
if(yPos > bottom){ // is pos past bottom
   yVel = -0.5; // change direction
   yPos = bottom; // make sure yPos does not render past bottom
}
</code>```

The same for the top

```<code>const top = 100; // put somewhere with globals
if(yPos < top){ // is pos past top
   yVel = 0.5; // change direction
   yPos = top; // make sure yPos does not render past top
}
</code>```

Title: HTML Canvas floating effect

Body:
Possible fix (efficency/perfomance issue over time?)

let i = 0;
function float() {
    yPos += Math.sin(i);
    i += .01 * yVel;
}

I'm trying to re-create the "floating" effect in HTML5 Canvas.
What I am trying to do is trying to get an image to "float" up and down.
The image is drawn and the the float() function is run to calculate the next y-position of the image. I have gotten it to float down, or up, but not how to change the direction after the image has floated example 100px (up or down). How would I do this?

I've uploaded the canvas here: https://stuff.darkleaks.net/HTML5%20WP/cheshire/

Ass you can see, the image floats down, and slows down. After it stops moving I want to change the floating direction. The float() function is where I try to do this.

   // Request animation frame
    const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

    // Canvas
    const c = document.getElementById('canvas');
    const ctx = c.getContext('2d');

    // Set full-screen
    c.width = window.innerWidth;
    c.height = window.innerHeight;

    // Framerate settings
    // Better not touch theese if you
    // do not know what you are doing
    let fps = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? 29 : 60;
    let now, delta;
    let then = Date.now();
    const interval = 1000 / fps;

    // Preparation below this comment line
    const background = new Image();
    const cheshire = new Image();
    const images = [background, cheshire];
    var imagesCount = images.length;

    background.onload = cheshire.onload;
    background.src = 'bg.png';
    cheshire.src = 'cheshire.png';

    let originalXPos = c.width / 2 - images[1].width / 2;
    let originalYPos = c.height / 2 - images[1].height / 2;
    let xPos = c.width / 2 - images[1].width / 2;
    let yPos = c.height / 2 - images[1].height / 2;
    let xVel = 0;
    let yVel = .5;

    // Draw
    function draw() {

        // Loop
        requestAnimationFrame(draw);
        now = Date.now();
        delta = now - then;

        if (delta > interval) {

            // Calculate then
            then = now - (delta % interval);

            // All your own stuff here
            drawImages();
            float();

        }

    }

    // Draw background
    function drawImages() {
        ctx.drawImage(images[0], 0, 0)
        ctx.drawImage(images[1], xPos, yPos);
    }

    function float() {

        yPos += 1 / yVel;
        yVel += .05;

        // IF the image has floated 100 px (up or down)
        // change direction

    }

    // Returns an random integer between
    // min and max
    function randInt(min, max) {
        max = max === undefined ? min - (min = 0) : max;
        return Math.floor(Math.random() * (max - min) + min);
    }

    // Cursor coordinates X & Y
    function clicked(e) {

        let x, y;

        if (e.offsetX) {
            x = e.offsetX;
            y = e.offsetY;
        } else if (e.layerX) {
            x = e.layerX;
            y = e.layerY;
        }

        // Do something...

    }

    $('canvas').on('click', function(e) {
        clicked(e);
    });

    requestAnimationFrame(draw);nter code here

Body:
To float down in your code as given in the question

// in the draw function
xPos += xVel;
yPos += yVel;

Then check if the yPos is past some point and if so change direction

const bottom = ctx.canvas.height - 300; // put somewhere with globals
if(yPos > bottom){ // is pos past bottom
   yVel = -0.5; // change direction
   yPos = bottom; // make sure yPos does not render past bottom
}

The same for the top

const top = 100; // put somewhere with globals
if(yPos < top){ // is pos past top
   yVel = 0.5; // change direction
   yPos = top; // make sure yPos does not render past top
}


问:
JPA bigdecimal problem in hibernate
I have used maven plugin for hibernate and it has generated entity classes without identifing sequences that are related to ID fields, id fields are generated as BigDecimal... now even if I point to an existing sequence through code like..

```<code>
@Entity
@javax.persistence.SequenceGenerator(

name = "SEQ_NATUREMASTER", sequenceName = "aop_teqachers_school_nature_id_seq")
@Table(name = "aop_teachers_school_nature_master", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "school_nature"))
public class AopTeachersSchoolNatureMaster implements java.io.Serializable {

 /**
  * Above code is added after generating entity class
  */

 private BigDecimal id;
</code>```

and I am getting error

```<code>
INFO : aop.web.teacher.controller.SchoolMasterInsertController - Attemped saving!testnature
Hibernate: select nextval ('aop_teqachers_school_nature_id_seq')
Dec 14, 2010 6:57:26 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet appServlet threw exception
org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
 at org.hibernate.id.IdentifierGeneratorHelper.get(IdentifierGeneratorHelper.java:123)
 at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:101)
 at org.hibernate.id.SequenceHiLoGenerator.generate(SequenceHiLoGenerator.java:81)
 at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
 at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
 at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:154)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:110)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
 at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:650)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:628)
 at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:308)
```

答: I wouldn't go for a decimal ID. And I really don't think you'd need BigInteger either. So change it to int or long. (The reason this fails is that the sequence can't generate the types BigX)

Title: JPA bigdecimal problem in hibernate

Body:
I have used maven plugin for hibernate and it has generated entity classes without identifing sequences that are related to ID fields, id fields are generated as BigDecimal... now even if I point to an existing sequence through code like..

@Entity
@javax.persistence.SequenceGenerator(

name = "SEQ_NATUREMASTER", sequenceName = "aop_teqachers_school_nature_id_seq")
@Table(name = "aop_teachers_school_nature_master", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "school_nature"))
public class AopTeachersSchoolNatureMaster implements java.io.Serializable {

 /**
  * Above code is added after generating entity class
  */

 private BigDecimal id;

and I am getting error

INFO : aop.web.teacher.controller.SchoolMasterInsertController - Attemped saving!testnature
Hibernate: select nextval ('aop_teqachers_school_nature_id_seq')
Dec 14, 2010 6:57:26 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet appServlet threw exception
org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
 at org.hibernate.id.IdentifierGeneratorHelper.get(IdentifierGeneratorHelper.java:123)
 at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:101)
 at org.hibernate.id.SequenceHiLoGenerator.generate(SequenceHiLoGenerator.java:81)
 at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
 at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
 at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:154)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:110)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
 at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:650)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:628)
 at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:308)


答:
To be able to select the div with certain score you could use this. That will get each div with that value of a score.
$('div[score="Result:78c61ce9"]')

And if you wanted to find it based on a certain result which was in a variable you could do

$('div[score="Result:' + val + '"]')

Title: jQuery select by custom attribute

Body: Is it possible to select a div which has a custom attribute like the one below?


问:
Redundant Keys in MySQL
Currently working on a MySQL database which has key declarations such as

```<code>KEY 'id' (id),
KEY 'username' (username),
KEY 'user_id' (username, id)
</code>```

Does this affect how our data works in anyway? Would eliminating this improve our database's efficiency? I concluded they were redundant but I am curious if the person who came before me created these for any reason.

答:
I always eliminate redundant indexes and I notice increase in writing speed without any effect in querying speed.

I can think of situations where having a redundant index might increase reading speed, but it is unlikely and the increase will be minimal.

In conclusion, I warmly recommend removing the redundant indexes: it will increase writing speed.

Title: Redundant Keys in MySQL

Body:
Currently working on a MySQL database which has key declarations such as

KEY 'id' (id),
KEY 'username' (username),
KEY 'user_id' (username, id)

Does this affect how our data works in anyway? Would eliminating this improve our database's efficiency? I concluded they were redundant but I am curious if the person who came before me created these for any reason.


问:
Django Haystack. And, or in search queryset
Using: Haystack and Sorl.

I need to make a search queryset to search products by filter.

Firstly, I need to filter only products based on my site (Django site framework). So I do:

```<code>sqs = sqs.filter(site=site.pk)
</code>```

It returns such search query:

```<code>site:(6)
</code>```

OK.

Then I need to filter by attributes:

```<code>sqs = sqs.filter(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter(attribute_codes='power', attribute_values__range=(40, 50))
</code>```

And it generates such query:

```<code>(site:(6) AND attribute_codes:(power) AND attribute_values:(["20" TO "30"]) AND attribute_values:(["40" TO "50"]))
</code>```

But, I need to make a query like this:

```<code>(site=6) AND ((attributes1) OR (attributes2))
</code>```

So I tried to change filtering by attributes to filter_or:

```<code> sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(40, 50))
</code>```

And the result is:

```<code>(site:(6) OR (attribute_codes:(power) AND attribute_values:(["20" TO "30"])) OR (attribute_codes:(power) AND attribute_values:(["40" TO "50"])))
</code>```

But I need else:

```<code>    (site=6) AND ((attributes1) OR (attributes2))
</code>```

So, how to do this?
Help me, please

答:
Like Django's queryset Q object, django haystack has a SQ object, which allows using | and & operators in filtering

```<code>sqs = sqs.filter(site=6)
sqs = sqs.filter(SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))
</code>```

or

```<code>sqs = sqs.filter(
    SQ(site=6) & (SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))
)
</code>```

Body:
Using: Haystack and Sorl.

I need to make a search queryset to search products by filter.

Firstly, I need to filter only products based on my site (Django site framework). So I do:

sqs = sqs.filter(site=site.pk)

It returns such search query:

site:(6)

OK.

Then I need to filter by attributes:

sqs = sqs.filter(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter(attribute_codes='power', attribute_values__range=(40, 50))

And it generates such query:

(site:(6) AND attribute_codes:(power) AND attribute_values:(["20" TO "30"]) AND attribute_values:(["40" TO "50"]))

But, I need to make a query like this:

(site=6) AND ((attributes1) OR (attributes2))

So I tried to change filtering by attributes to filter_or:

 sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(40, 50))

And the result is:

(site:(6) OR (attribute_codes:(power) AND attribute_values:(["20" TO "30"])) OR (attribute_codes:(power) AND attribute_values:(["40" TO "50"])))

But I need else:

    (site=6) AND ((attributes1) OR (attributes2))

So, how to do this?
Help me, please

Body:
Like Django's queryset Q object, django haystack has a SQ object, which allows using | and & operators in filtering

sqs = sqs.filter(site=6)
sqs = sqs.filter(SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))

or

sqs = sqs.filter(
    SQ(site=6) & (SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))
)