问:
Add row to the top of other dataframe
Here's the thing, I need to put one row from other dataframe to the top of main dataframe in pandas, above first row where are columns named.

Sample :

```<code>      1value  2value 3value 4value 5value
acity    4       3       6      2     6
bcity    2       6       6      4     1
ccity    5       11      53     6     3
dcity    5       1       4      6     3
gcity    6       4       2      7     4
</code>```

And the other sample:

```<code>1value 2value 3value 4value 5value
 2       5       2      6     3
</code>```

And now I need to add value of second sample to the top of first sample. Desired output:

```<code>        2       5       2      6     3
      1value  2value 3value 4value 5value
acity    4       3       6      2     6
bcity    2       6       6      4     1
ccity    5       11      53     6     3
dcity    5       1       4      6     3
gcity    6       4       2      7     4
</code>```

And just for mention, I have about 3000 rows, and 250 columns in this Sample dataframe.

I have tried with multiindex, but doesn't working, it said : TypeError: unhashable type: 'dict'

TypeErrorTraceback

```<code>(most recent call last)
    <ipython-input-230-e17cd26b6b7f> in <module>()
    ----> 1 pd.MultiIndex.from_arrays([newdf.columns.to_series().map(topframe.iloc[0].to_dict()), newdf.columns])

    /opt/anaconda2/lib/python2.7/site-packages/pandas/indexes/multi.pyc in from_arrays(cls, arrays, sortorder, names)
        841             return Index(arrays[0], name=name)
        842
    --> 843         cats = [Categorical.from_array(arr, ordered=True) for arr in arrays]
        844         levels = [c.categories for c in cats]
        845         labels = [c.codes for c in cats]

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in from_array(cls, data, **kwargs)
        385             the unique values of `data`.
        386         """
    --> 387         return Categorical(data, **kwargs)
        388
        389     @classmethod

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in __init__(self, values, categories, ordered, name, fastpath, levels)
        286                 codes, categories = factorize(values, sort=True)
        287             except TypeError:
    --> 288                 codes, categories = factorize(values, sort=False)
        289                 if ordered:
        290                     # raise, as we don't have a sortable data structure and so

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/algorithms.pyc in factorize(values, sort, order, na_sentinel, size_hint)
        183     table = hash_klass(size_hint or len(vals))
        184     uniques = vec_klass()
    --> 185     labels = table.get_labels(vals, uniques, 0, na_sentinel, True)
        186
        187     labels = com._ensure_platform_int(labels)

    pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_labels (pandas/hashtable.c:14033)()

    TypeError: unhashable type 'dict
</code>```

答:
You can use map by dict created by first row of second df2 with iloc:

```<code>print (df2.iloc[0].to_dict())
{'2value': 5, '5value': 3, '1value': 2, '4value': 6, '3value': 2}

print (df1.columns.to_series().map(df2.iloc[0].to_dict()))
1value    2
2value    5
3value    2
4value    6
5value    3
dtype: int64

df1.columns = [df1.columns.to_series().map(df2.iloc[0].to_dict()), df1.columns]
print (df1)
           2      5      2      6      3
      1value 2value 3value 4value 5value
acity      4      3      6      2      6
bcity      2      6      6      4      1
ccity      5     11     53      6      3
dcity      5      1      4      6      3
gcity      6      4      2      7      4
</code>```

Another solution is rename columns by dict:

```<code>print (df1.rename(columns=df2.iloc[0].to_dict()))
       2   5   2  6  3
acity  4   3   6  2  6
bcity  2   6   6  4  1
ccity  5  11  53  6  3
dcity  5   1   4  6  3
gcity  6   4   2  7  4

df1.columns = [df1.rename(columns=df2.iloc[0].to_dict()).columns, df1.columns]
print (df1)
           2      5      2      6      3
      1value 2value 3value 4value 5value
acity      4      3      6      2      6
bcity      2      6      6      4      1
ccity      5     11     53      6      3
dcity      5      1      4      6      3
gcity      6      4      2      7      4
</code>```

Title: Add row to the top of other dataframe

Body:
Here's the thing, I need to put one row from other dataframe to the top of main dataframe in pandas, above first row where are columns named.

Sample :

      1value  2value 3value 4value 5value
acity    4       3       6      2     6
bcity    2       6       6      4     1
ccity    5       11      53     6     3
dcity    5       1       4      6     3
gcity    6       4       2      7     4

And the other sample:

1value 2value 3value 4value 5value
 2       5       2      6     3

And now I need to add value of second sample to the top of first sample. Desired output:

        2       5       2      6     3
      1value  2value 3value 4value 5value
acity    4       3       6      2     6
bcity    2       6       6      4     1
ccity    5       11      53     6     3
dcity    5       1       4      6     3
gcity    6       4       2      7     4

And just for mention, I have about 3000 rows, and 250 columns in this Sample dataframe.

I have tried with multiindex, but doesn't working, it said : TypeError: unhashable type: 'dict'

TypeErrorTraceback

(most recent call last)
    <ipython-input-230-e17cd26b6b7f> in <module>()
    ----> 1 pd.MultiIndex.from_arrays([newdf.columns.to_series().map(topframe.iloc[0].to_dict()), newdf.columns])

    /opt/anaconda2/lib/python2.7/site-packages/pandas/indexes/multi.pyc in from_arrays(cls, arrays, sortorder, names)
        841             return Index(arrays[0], name=name)
        842
    --> 843         cats = [Categorical.from_array(arr, ordered=True) for arr in arrays]
        844         levels = [c.categories for c in cats]
        845         labels = [c.codes for c in cats]

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in from_array(cls, data, **kwargs)
        385             the unique values of `data`.
        386         """
    --> 387         return Categorical(data, **kwargs)
        388
        389     @classmethod

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/categorical.pyc in __init__(self, values, categories, ordered, name, fastpath, levels)
        286                 codes, categories = factorize(values, sort=True)
        287             except TypeError:
    --> 288                 codes, categories = factorize(values, sort=False)
        289                 if ordered:
        290                     # raise, as we don't have a sortable data structure and so

    /opt/anaconda2/lib/python2.7/site-packages/pandas/core/algorithms.pyc in factorize(values, sort, order, na_sentinel, size_hint)
        183     table = hash_klass(size_hint or len(vals))
        184     uniques = vec_klass()
    --> 185     labels = table.get_labels(vals, uniques, 0, na_sentinel, True)
        186
        187     labels = com._ensure_platform_int(labels)

    pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_labels (pandas/hashtable.c:14033)()

    TypeError: unhashable type 'dict

Body:
You can use map by dict created by first row of second df2 with iloc:

print (df2.iloc[0].to_dict())
{'2value': 5, '5value': 3, '1value': 2, '4value': 6, '3value': 2}

print (df1.columns.to_series().map(df2.iloc[0].to_dict()))
1value    2
2value    5
3value    2
4value    6
5value    3
dtype: int64

df1.columns = [df1.columns.to_series().map(df2.iloc[0].to_dict()), df1.columns]
print (df1)
           2      5      2      6      3
      1value 2value 3value 4value 5value
acity      4      3      6      2      6
bcity      2      6      6      4      1
ccity      5     11     53      6      3
dcity      5      1      4      6      3
gcity      6      4      2      7      4

Another solution is rename columns by dict:

print (df1.rename(columns=df2.iloc[0].to_dict()))
       2   5   2  6  3
acity  4   3   6  2  6
bcity  2   6   6  4  1
ccity  5  11  53  6  3
dcity  5   1   4  6  3
gcity  6   4   2  7  4

df1.columns = [df1.rename(columns=df2.iloc[0].to_dict()).columns, df1.columns]
print (df1)
           2      5      2      6      3
      1value 2value 3value 4value 5value
acity      4      3      6      2      6
bcity      2      6      6      4      1
ccity      5     11     53      6      3
dcity      5      1      4      6      3
gcity      6      4      2      7      4


来源: stackexchange

问:
Putting arrays in a table using PHP
I'm a beginner in PHP and working on an API project which has to get results from a server I connected via API.

I am getting the results, but I would like to have them well arranged in a simple table.

This is what I am getting:

I used the following code:

```<code>$api = new SplynxAPI($api_url, $key, $secret);

$locationsApiUrl = "admin/administration/locations";

echo "```";

echo "List locations\n";
$result = $api->api_call_get($locationsApiUrl);

echo "Result: ";

if ($result) {
  echo "Ok!\n";
  print_r($api->response);
} else {
  echo "Fail! Error code: $api->response_code\n";
  print_r($api->response);
}

echo "\n-------------------------------------------------\n";
```

Kindly assist me on this one.

答:
You are directly getting the response "$api->response" as an array. So simply use a loop and populate it in table as you like.</p>

```<code>Ex:

foreach($api->response as $apiData) {
 // Your code
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Putting arrays in a table using PHP

Body:
I'm a beginner in PHP and working on an API project which has to get results from a server I connected via API.

I am getting the results, but I would like to have them well arranged in a simple table.

This is what I am getting:

I used the following code:

$api = new SplynxAPI($api_url, $key, $secret);

$locationsApiUrl = "admin/administration/locations";

echo "
";

echo "List locations\n";
$result = $api->api_call_get($locationsApiUrl);

echo "Result: ";

if ($result) {
  echo "Ok!\n";
  print_r($api->response);
} else {
  echo "Fail! Error code: $api->response_code\n";
  print_r($api->response);
}

echo "\n-------------------------------------------------\n";

Kindly assist me on this one.

Body:
You are directly getting the response "$api->response" as an array. So simply use a loop and populate it in table as you like.

Ex:

foreach($api->response as $apiData) {
 // Your code
}


问:
AsyncHttpClient post request connection refused
Im currently having a problem regarding asynchttpclient post request. i was able to perform a get request using the loopj's asynchttpclient but im stuck with a problem regarding post request.

here is my code for my post request.

```<code> AsyncHttpClient client = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                params.put("username", username);
                params.put("password", password);

            client.post("http://localhost/lin/mobile_login/", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String response = new String(responseBody);
                    Log.d("RAW", String.valueOf(responseBody));
                    Log.d("RESPONSE",response);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    String err = new String(responseBody);
                    Log.d("ERROR", err);
                    Log.d("EXCE", String.valueOf(error));
                }
            });
</code>```

and it throws

```<code> java.net.ConnectException: Connection refused
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
     at java.net.Socket.connect(Socket.java:605)
     at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
     at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:157)
     at cz.msebera.android.httpclient.conn.scheme.SchemeSocketFactoryAdaptor.connectSocket(SchemeSocketFactoryAdaptor.java:65)
     at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
     at cz.msebera.android.httpclient.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:131)
     at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
     at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
     at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:860)
     at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
     at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:146)
     at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:177)
     at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:106)
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
     at java.lang.Thread.run(Thread.java:761)
</code>```

im trying to pass 2 parameter to my post request. hope you can help me regarding my problem.

答:
Problem is with your url http://localhost/lin/mobile_login/

Url cannot have the localhost in it. You have to add the IP address here instead of the localhost for example http://192.168.42.37/lin/mobile_login/ whereas 192.168.42.37 will be ip address. You need to find the IP address first. Also make sure server and mobile are on same network.

Body:
Im currently having a problem regarding asynchttpclient post request. i was able to perform a get request using the loopj's asynchttpclient but im stuck with a problem regarding post request.

here is my code for my post request.

 AsyncHttpClient client = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                params.put("username", username);
                params.put("password", password);

            client.post("http://localhost/lin/mobile_login/", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String response = new String(responseBody);
                    Log.d("RAW", String.valueOf(responseBody));
                    Log.d("RESPONSE",response);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    String err = new String(responseBody);
                    Log.d("ERROR", err);
                    Log.d("EXCE", String.valueOf(error));
                }
            });

and it throws

 java.net.ConnectException: Connection refused
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
     at java.net.Socket.connect(Socket.java:605)
     at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
     at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:157)
     at cz.msebera.android.httpclient.conn.scheme.SchemeSocketFactoryAdaptor.connectSocket(SchemeSocketFactoryAdaptor.java:65)
     at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
     at cz.msebera.android.httpclient.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:131)
     at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
     at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
     at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:860)
     at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
     at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:146)
     at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:177)
     at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:106)
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
     at java.lang.Thread.run(Thread.java:761)

im trying to pass 2 parameter to my post request. hope you can help me regarding my problem.


问:
How to get component (div) rendering time in AngularJS
How to calculate the rendering time of each component (Divs) and show it to the users in a graph. Eg: Calculating the time taken for UI-Grid to load and render JSON, etc.

I tried https://www.npmjs.com/package/angular-performance , it calculates loaded time, but before the DOM renders the items.

How to calculate the component(div) rendering time in AngularJS?

Please Help.

答:
After some trial and error, I found a way to calculate the rendering time of each component (Divs)

HTML:

```<code> <div ng-controller="Controller1">
    <div custom-performance="log1" content="Content1">{{log1}}</div>
</div>
 <div ng-controller="Controller2">
    <div custom-performance="log2" content="Content2">{{log2}}</div>
</div>
</code>```

Angular:

```<code>'use strict';

var app = angular.module('myApp', []);

app.controller('Controller1', ['$scope', '$http', function($scope, $http) {
  $http({
    method: 'POST',
    url: 'JSON/catlog.json'
  }).success(function(response) {
    $scope.log1 = response;
  }).error(function(error) {

  });
}]);

app.controller('Controller2', ['$scope', function($scope) {
  $scope.log2 = "Hello World";
}]);

app.directive('customPerformance', ['$rootScope', function($rootScope) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $rootScope.graphOutput = [];
      var start = new Date();
      var endTime = null;
      scope.$watch(attrs.customPerformance, function(newval) {
        if (newval != undefined) {
          setTimeout(function() {
            endTime = (new Date() - start);
            $rootScope.graphOutput.push({
              'content': attrs.content,
              'timeTaken': endTime
            });
            console.log(JSON.stringify($rootScope.graphOutput));
          });
        }
      });
    }
  }
}]);
</code>```

Body:
After some trial and error, I found a way to calculate the rendering time of each component (Divs)

HTML:

 <div ng-controller="Controller1">
    <div custom-performance="log1" content="Content1">{{log1}}</div>
</div>
 <div ng-controller="Controller2">
    <div custom-performance="log2" content="Content2">{{log2}}</div>
</div>

Angular:

'use strict';

var app = angular.module('myApp', []);

app.controller('Controller1', ['$scope', '$http', function($scope, $http) {
  $http({
    method: 'POST',
    url: 'JSON/catlog.json'
  }).success(function(response) {
    $scope.log1 = response;
  }).error(function(error) {

  });
}]);

app.controller('Controller2', ['$scope', function($scope) {
  $scope.log2 = "Hello World";
}]);

app.directive('customPerformance', ['$rootScope', function($rootScope) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $rootScope.graphOutput = [];
      var start = new Date();
      var endTime = null;
      scope.$watch(attrs.customPerformance, function(newval) {
        if (newval != undefined) {
          setTimeout(function() {
            endTime = (new Date() - start);
            $rootScope.graphOutput.push({
              'content': attrs.content,
              'timeTaken': endTime
            });
            console.log(JSON.stringify($rootScope.graphOutput));
          });
        }
      });
    }
  }
}]);


问:
How to add an image to a button with GTK
I am trying to add an image to a button with label, but the image doesn't show and the broken image doesn't display either.

```<code>stop_button = gtk_button_new_with_label("stop");
image = gtk_image_new_from_file ("/home/cendit/Escritorio/index.jpeg");
gtk_button_set_image (GTK_BUTTON(stop_button),image);
</code>```

I tried a different path "file:///home/cendit/Escritorio/index.jpeg" but it was not successful.

答:
Images inside buttons are not visible by default, as we transitioned from GTK+ 2.x to 3.x. Sadly, the API hasn't been cleaned up to reflect this change, so it's a bit of a trap.

If you want to display a button with only an image inside it, you can use:

```<code>GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new ();

gtk_button_set_image (GTK_BUTTON (button), image);
</code>```

On the other hand, if you want to have a button with both text and an image inside it, you can use:

```<code>GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new_with_label ("...");

gtk_button_set_always_show_image (GTK_BUTTON (button), TRUE);
gtk_button_set_image (GTK_BUTTON (button), image);
</code>```

See the documentation of gtk_button_set_image() for further information.

Body:
I am trying to add an image to a button with label, but the image doesn't show and the broken image doesn't display either.

stop_button = gtk_button_new_with_label("stop");
image = gtk_image_new_from_file ("/home/cendit/Escritorio/index.jpeg");
gtk_button_set_image (GTK_BUTTON(stop_button),image);

I tried a different path "file:///home/cendit/Escritorio/index.jpeg" but it was not successful.

Body:
Images inside buttons are not visible by default, as we transitioned from GTK+ 2.x to 3.x. Sadly, the API hasn't been cleaned up to reflect this change, so it's a bit of a trap.

If you want to display a button with only an image inside it, you can use:

GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new ();

gtk_button_set_image (GTK_BUTTON (button), image);

On the other hand, if you want to have a button with both text and an image inside it, you can use:

GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new_with_label ("...");

gtk_button_set_always_show_image (GTK_BUTTON (button), TRUE);
gtk_button_set_image (GTK_BUTTON (button), image);

See the documentation of gtk_button_set_image() for further information.


问:
how to call oracle procedure that has in out cursor
I have this procedure and I want to know how to execute it in PL/SQL. Can someone please help me?</p>

```<code>create or replace PROCEDURE "P_TEST"
 (
    c$inchidere  IN OUT  softys.pk_utils.GenericCursor,
    p_OLD IN   empl.code%type,
    p_NEW IN   empl.code%type,
    p_NXT IN   empl.code%type,
    p_ORGID IN   empl.ORGID%type
  )
is
begin
    open c$inchidere  for
        select
     ...

end
</code>```

答:
Calling a procedure in PL/SQL is easy. The tricky part is reading the REF CURSOR. We need to fetch it into variables or a record type which match the projection of the executed query. That your code uses something called softys.pk_utils.GenericCursor makes me think you might have problems with that bit.

Anyway, this example presumes the result set returns a single numeric column. You will need to adjust the target variables to match the actual projection.

```<code>declare
    rc sys_refcursor;
    l_id number;
begin

    P_TEST (
       c$inchidere  => rc,
      p_OLD => 'whatever',
      p_NEW => 'meh',
      p_NXT => 'ABC',
      p_ORGID => 123456  );
    loop
        fetch rc into l_id;
        exit when rc%notfound;
    end loop;
end;
</code>```

Not sure why the ref cursor parameter is defined as IN OUT. As you open it immediately it only needs to be OUT.

Body:
I have this procedure and I want to know how to execute it in PL/SQL. Can someone please help me?

create or replace PROCEDURE "P_TEST"
 (
    c$inchidere  IN OUT  softys.pk_utils.GenericCursor,
    p_OLD IN   empl.code%type,
    p_NEW IN   empl.code%type,
    p_NXT IN   empl.code%type,
    p_ORGID IN   empl.ORGID%type
  )
is
begin
    open c$inchidere  for
        select
     ...

end

Body:
Calling a procedure in PL/SQL is easy. The tricky part is reading the REF CURSOR. We need to fetch it into variables or a record type which match the projection of the executed query. That your code uses something called softys.pk_utils.GenericCursor makes me think you might have problems with that bit.

Anyway, this example presumes the result set returns a single numeric column. You will need to adjust the target variables to match the actual projection.

declare
    rc sys_refcursor;
    l_id number;
begin

    P_TEST (
       c$inchidere  => rc,
      p_OLD => 'whatever',
      p_NEW => 'meh',
      p_NXT => 'ABC',
      p_ORGID => 123456  );
    loop
        fetch rc into l_id;
        exit when rc%notfound;
    end loop;
end;

Not sure why the ref cursor parameter is defined as IN OUT. As you open it immediately it only needs to be OUT.


问:
How can I use PowerShell to get RAM / Memory details of multiple computers?
I need to inventory the RAM of the computers that are listed in a text file. I have this script:

```<code>$($servers = Get-Content D:\123.txt

Foreach ($s in $servers) {
    $s
    get-wmiobject Win32_Processor -ComputerName $s -ErrorAction SilentlyContinue| select Name | Format-List
    Get-WmiObject win32_baseboard -ComputerName $s -ErrorAction SilentlyContinue| Select product | Format-List

    $colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $s

    $colRAM | ForEach {
           “Memory Installed: ” + $_.DeviceLocator
           “Memory Size: ” + ($_.Capacity / 1GB) + ” GB”
           $SlotsFilled = $SlotsFilled + 1
           $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB)
    }

    Write-Host "_____________________________________ "
}) *>&1 > output.txt
</code>```

Which returns this result:

computer1

Name : Intel(R) Core(TM)2 Duo CPU     E8500  @ 3.16GHz

product : DG31PR

Memory Installed: J6H2 Memory Size: 1 GB

I would like the result to be like this and exported to CSV:

```<code>Name      TotalRam      Type      Motherboard
comp1     2gb           ddr3      h81m-k
comp2     2gb           ddr3      h81m-k
          2gb
comp3     1gb           ddr2      DG31PR
          0,5gb
</code>```

答:
This is a modified version of your script to get the result you requested.

```<code>#For more types https://msdn.microsoft.com/en-us/library/aa394347(v=vs.85).aspx
$memtype = @{
    0 = 'Unknown'
    1 = 'Other'
    2 = 'DRAM'
    20 = 'DDR'
    21 = 'DDR-2'
    22= 'DDR2 FB-DIMM'
    24 = 'DDR3'
    25 = 'FBD2'
}

$Result = @()

$servers = Get-Content D:\123.txt

Foreach ($s in $servers) {

    $Motherboard = (Get-WmiObject win32_baseboard -ComputerName $s -ErrorAction SilentlyContinue).product
    $colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $s

    $TotMemPopulated = 0
    $SlotsFilled = 0

    $colRAM | ForEach-Object {
        $SlotsFilled = $SlotsFilled + 1
        $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB)

        $Props =[ordered]@{
            Name = $s
            TotalRam = "$TotMemPopulated`gb"
            Type = $memtype[[int]$_.MemoryType]
            MotherBoard = $Motherboard
        }
        $Object = New-Object -TypeName PSCustomObject -Property $Props

    }

    $Result += $Object
}

$Result | Export-CSV RamReport.csv
</code>```

Explanation:

$memtype is a hashtable that converts the numeric MemoryType number from the win32_PhysicalMemory WMI class to the friendly name. You may need to add more references to this hashtable depending on the variety of RAM in your environment (I have provided a link to the numeric code references).

$result is defined as an empty array, which is used during the script to collate the results in to an object.

The script creates an object as $object with a hashtable of the properties you wished to collate and then adds each object to the $result collection. This is an ordered hashtable so that we respect the column order that you requested in the final output.

Finally we export $result to CSV using Export-CSV.

Body:
I need to inventory the RAM of the computers that are listed in a text file. I have this script:

$($servers = Get-Content D:\123.txt

Foreach ($s in $servers) {
    $s
    get-wmiobject Win32_Processor -ComputerName $s -ErrorAction SilentlyContinue| select Name | Format-List
    Get-WmiObject win32_baseboard -ComputerName $s -ErrorAction SilentlyContinue| Select product | Format-List

    $colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $s

    $colRAM | ForEach {
           “Memory Installed: ” + $_.DeviceLocator
           “Memory Size: ” + ($_.Capacity / 1GB) + ” GB”
           $SlotsFilled = $SlotsFilled + 1
           $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB)
    }

    Write-Host "_____________________________________ "
}) *>&1 > output.txt

Which returns this result:

computer1

Name : Intel(R) Core(TM)2 Duo CPU     E8500  @ 3.16GHz

product : DG31PR

Memory Installed: J6H2 Memory Size: 1 GB

I would like the result to be like this and exported to CSV:

Name      TotalRam      Type      Motherboard
comp1     2gb           ddr3      h81m-k
comp2     2gb           ddr3      h81m-k
          2gb
comp3     1gb           ddr2      DG31PR
          0,5gb

Body:
This is a modified version of your script to get the result you requested.

#For more types https://msdn.microsoft.com/en-us/library/aa394347(v=vs.85).aspx
$memtype = @{
    0 = 'Unknown'
    1 = 'Other'
    2 = 'DRAM'
    20 = 'DDR'
    21 = 'DDR-2'
    22= 'DDR2 FB-DIMM'
    24 = 'DDR3'
    25 = 'FBD2'
}

$Result = @()

$servers = Get-Content D:\123.txt

Foreach ($s in $servers) {

    $Motherboard = (Get-WmiObject win32_baseboard -ComputerName $s -ErrorAction SilentlyContinue).product
    $colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $s

    $TotMemPopulated = 0
    $SlotsFilled = 0

    $colRAM | ForEach-Object {
        $SlotsFilled = $SlotsFilled + 1
        $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB)

        $Props =[ordered]@{
            Name = $s
            TotalRam = "$TotMemPopulated`gb"
            Type = $memtype[[int]$_.MemoryType]
            MotherBoard = $Motherboard
        }
        $Object = New-Object -TypeName PSCustomObject -Property $Props

    }

    $Result += $Object
}

$Result | Export-CSV RamReport.csv

Explanation:

$memtype is a hashtable that converts the numeric MemoryType number from the win32_PhysicalMemory WMI class to the friendly name. You may need to add more references to this hashtable depending on the variety of RAM in your environment (I have provided a link to the numeric code references).

$result is defined as an empty array, which is used during the script to collate the results in to an object.

The script creates an object as $object with a hashtable of the properties you wished to collate and then adds each object to the $result collection. This is an ordered hashtable so that we respect the column order that you requested in the final output.

Finally we export $result to CSV using Export-CSV.


问:
optimize elasticsearch query using filter, query or mix of both
I am trying to improve the performance of a elasticsearch query. The goal o the query is just retrieve those document that match the query, so score does not matter, also is important to mention we got an index per day, so the quer. As far as I know for this cases is better to use filter, avoiding to calculate scoring, but also I just red that there is/are some alternative using finter inside query retrieving all document score 1, so The first query I made was the followig:

```<code>{
 "filter": {
  "bool": {
   "must": [{
     "match": {
      "from": "john.doe@example.com"
     }
    }, {
     "range": {
      "receivedDate": {
       "gte": "date1",
       "lte": "date2"
      }
     }
    }
   ]
  }
 }
}
</code>```

Then I made my first test and I change "filter" for "query" and most of the time I get better times using "query" then "filter", that is my first question, why? What I have doing wrong on my query to have filter slower than a query?

After than I keep reading trying to improve it and I got this:

```<code>{
    "query": {
        "bool": {
            "must": {
                "match_all": {}
            },
            "filter": {
                "bool": {
                    "must": [{
                            "match": {
                                "from": "john.doe@example.com"
                            }
                        }, {
                            "range": {
                                "receivedDate": {
                                    "gte": "date1",
                                    "lte": "date2"
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}
</code>```

With the latter I have the impression have been improved a little bit. So according with your experience could you tell me which one is better (at least in theory) to have a faster result, also Exist the chance that using one of this queries cache the results improving the queries made forward. There is a better way to make this query? Thanks in advance for your help. I forgot to mention I am using Elasticsearch v2.3

答:
In your first query, you were only using a post_filter. Your second query is the way to go, but it can be optimized to this (no need to wrap bool/filter inside bool/must):

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "receivedDate": {
              "gte": "date1",
              "lte": "date2"
            }
          }
        },
        {
          "term": {
            "from": "john.doe@example.com"
          }
        }
      ]
    }
  }
}
</code>```

Body:
I am trying to improve the performance of a elasticsearch query. The goal o the query is just retrieve those document that match the query, so score does not matter, also is important to mention we got an index per day, so the quer. As far as I know for this cases is better to use filter, avoiding to calculate scoring, but also I just red that there is/are some alternative using finter inside query retrieving all document score 1, so The first query I made was the followig:

{
 "filter": {
  "bool": {
   "must": [{
     "match": {
      "from": "john.doe@example.com"
     }
    }, {
     "range": {
      "receivedDate": {
       "gte": "date1",
       "lte": "date2"
      }
     }
    }
   ]
  }
 }
}

Then I made my first test and I change "filter" for "query" and most of the time I get better times using "query" then "filter", that is my first question, why? What I have doing wrong on my query to have filter slower than a query?

After than I keep reading trying to improve it and I got this:

{
    "query": {
        "bool": {
            "must": {
                "match_all": {}
            },
            "filter": {
                "bool": {
                    "must": [{
                            "match": {
                                "from": "john.doe@example.com"
                            }
                        }, {
                            "range": {
                                "receivedDate": {
                                    "gte": "date1",
                                    "lte": "date2"
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}

With the latter I have the impression have been improved a little bit. So according with your experience could you tell me which one is better (at least in theory) to have a faster result, also Exist the chance that using one of this queries cache the results improving the queries made forward. There is a better way to make this query? Thanks in advance for your help. I forgot to mention I am using Elasticsearch v2.3

Body:
In your first query, you were only using a post_filter. Your second query is the way to go, but it can be optimized to this (no need to wrap bool/filter inside bool/must):

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "receivedDate": {
              "gte": "date1",
              "lte": "date2"
            }
          }
        },
        {
          "term": {
            "from": "john.doe@example.com"
          }
        }
      ]
    }
  }
}


问:
What's the equivalent of mysql RLIKE operator in Hibernate Query?
I have the following query which runs perfectly in mysql.

```<code>SELECT * FROM Orders as o, Products as p  where o.productinfo RLIKE p.code;
</code>```

Here I am joining two tables Orders and Products with RLIKE.

I am trying to implement the same in Hibernate.

```<code>Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo RLIKE p.code");
List<Object[]> results = query.getResultList();
</code>```

When I used RLIKE, the following error is thrown in run time.

```<code>{"errormessage":"org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: RLIKE
</code>```

I tried to implement the same with LIKE query and matched it with '%p.code%'.

```<code>Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo LIKE '%p.code%'");
</code>```

But it matches with the string "p.code" rather then the value.

What is the equivalent of RLIKE in HQL?
Is there a different way to join two tables with LIKE in HQL?

Thanks.

Answer by @YCF_L:
For any one trying to join two tables with like operator in Hibernate (mysql) can do it the following way.

```<code>SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');
</code>```

答:
You can check regular expression way something like this way:     Restrictions.sqlRestriction(word REGEXP '^[A-Z][A-Za-z]*$')

Please check the link which will be helpful for this case: Regular expression with criteria

Body:
I have the following query which runs perfectly in mysql.

SELECT * FROM Orders as o, Products as p  where o.productinfo RLIKE p.code;

Here I am joining two tables Orders and Products with RLIKE.

I am trying to implement the same in Hibernate.

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo RLIKE p.code");
List<Object[]> results = query.getResultList();

When I used RLIKE, the following error is thrown in run time.

{"errormessage":"org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: RLIKE

I tried to implement the same with LIKE query and matched it with '%p.code%'.

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo LIKE '%p.code%'");

But it matches with the string "p.code" rather then the value.

What is the equivalent of RLIKE in HQL?
Is there a different way to join two tables with LIKE in HQL?

Thanks.

Answer by @YCF_L:
For any one trying to join two tables with like operator in Hibernate (mysql) can do it the following way.

SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');


问:
Laravel Checking If a Record Exists
I am new to Laravel. How do I find if a record exists?

$user = User::where('email', '=', Input::get('email'));
```

What can I do here to see if $user has a record?

答:
this is simple code to check email is exist or not in database

```

    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }

```

ContentLicense: CC BY-SA 4.0

Title: Laravel Checking If a Record Exists

Body:
I am new to Laravel. How do I find if a record exists?

$user = User::where('email', '=', Input::get('email'));

What can I do here to see if $user has a record?

Body:
this is simple code to check email is exist or not in database

    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }


问:
Multiple values of the same column name in SQL
this might seem like a weird question, earlier I posted another question on ASP multiple values through a session variable, I've now figured that out and have managed to pass all three values for instance to a label. Now however I need to pass the three IDs to create a gridview for the three values... So for my SQL statement I have:

SelectCommand="SELECT [BookID], [book_title] FROM [tblBook] WHERE ([BookID] = ?)">

So I need there to be 3 BookID=?,?,? for instance, is this possible?

Or is there another way to do it in ASP?

答:
i think what you're looking for is something like this:</p>

```<code>SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] in (?,?,?)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i think what you're looking for is something like this:

SELECT [BookID], [book_title] FROM [tblBook] WHERE [BookID] in (?,?,?)


问:
Read Data from GPS device
I am building a location tracking system for one of our client. They have GPS devicees installed in vehicles and each device has programmed with a server IP and a port number. GPS device communicate on given IP address and port. I would like to read the packet comes from GPS device (like latitude, longitude and other information, as packet contains information in binary) without doing any read operation.

What i am looking for :

A. Read data from Device and store in some intermediate location, since we have TCP listener by which Device communicate with us.

B. I don't want to do any operation, as simple as that whatever or any format data, if GPS device sent to listener, it must listen ans store it, without any manipulation.

Thanks

答:
I provide sample code for it check:</p>

```<code>public class ServerListener {

public static void main(String[] args) {
    new ServerListener().startServer();
}

public void startServer() {
    final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(03);

    Runnable serverTask = new Runnable() {
        @SuppressWarnings("resource")
        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(5094);
                System.out.println("Waiting for clients to connect...");
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    clientProcessingPool.submit(new ClientTask(clientSocket));
                }
            } catch (IOException e) {
                System.err.println("Unable to process client request");
                e.printStackTrace();
            }
        }
    };
    Thread serverThread = new Thread(serverTask);
    serverThread.start();
}

private class ClientTask implements Runnable {
    private final Socket clientSocket;

    private ClientTask(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        System.out.println("Got a client !");
        while (true) {

        try {
            BufferedReader reader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
            String clientData = "";

            clientData = reader.readLine();
            System.out.println("clientdata::::"+clientData);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

 }
}
</code>```

Title: Read Data from GPS device

Body:
I provide sample code for it check:

public class ServerListener {

public static void main(String[] args) {
    new ServerListener().startServer();
}

public void startServer() {
    final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(03);

    Runnable serverTask = new Runnable() {
        @SuppressWarnings("resource")
        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(5094);
                System.out.println("Waiting for clients to connect...");
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    clientProcessingPool.submit(new ClientTask(clientSocket));
                }
            } catch (IOException e) {
                System.err.println("Unable to process client request");
                e.printStackTrace();
            }
        }
    };
    Thread serverThread = new Thread(serverTask);
    serverThread.start();
}

private class ClientTask implements Runnable {
    private final Socket clientSocket;

    private ClientTask(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        System.out.println("Got a client !");
        while (true) {

        try {
            BufferedReader reader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
            String clientData = "";

            clientData = reader.readLine();
            System.out.println("clientdata::::"+clientData);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

 }
}


问:
Entity Framework Code Migrations - Stuck on Initial Migration
I have added EF 5 to my project via Nuget and enabled migrations with the "Enable-Migrations" command. I have then called "Add-Migration" to generate the base code for generating the schema.

I then added a property to one of my domain objects (string property called "TestProperty") and added a mapping to my EntityTypeConfiguration file (we're ignoring the conventions at the moment).

Calling "Add-Migration" again produces the error:

```<code>Unable to generate an explicit migration because the following explicit migrations are pending: [201303262144218_Initial]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
</code>```

But calling "Update-Database" produces a sql exception because the tables already exist:

```<code>There is already an object named 'Customer' in the database
</code>```

In my constructor for my DbContext I have tried the different update strategies, e.g.:

```<code>Database.SetInitializer<UnitOfWork>(new DropCreateDatabaseAlways<UnitOfWork>());
</code>```

Am I missing something obvious?
I tried the solution here but it didn't work: Automatic Migrations for ASP.NET

Thanks

EDIT: Update
The key to getting past the first step is to create the initial migration and then delete the generated code from the Up and Down methods (http://thedatafarm.com/blog/data-access/using-ef-migrations-with-an-existing-database/).

I can then update the model and the EF map and then run Add-Migration. This generates a migration with the correct Up and Down code.

The problem is then trying to apply the update. Update-Database produces the error "Unable to update database to match the current model because there are pending changes and automatic migration is disabled...automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
You can use the Add-Migration command to write the pending model changes to a code-based migration". Ok, so I try Add-Migration again and it produces another migration with the exact same code as the last one.

I run Update-Database and get the same error again. I try "Update-Database -TargetMigration 201304080859556_MyMigration -Force" but this produces "The specified target migration '201304080859556_MyMigration' does not exist. Ensure that target migration refers to an existing migration id" - It does!

Very frustrating!

答:
Trying to migrate an old db version to a new model, either the database didn't match the new model or i got errors like :

Type is not resolved for member 'Npgsql.PostgresException,Npgsql,
  Version=3.2.2.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'

Here's how it worked (using automatic migration) :

Delete Migrations folder

Execute enable-migrations

Set this two properties to true in the newly created Configuration.cs

```<code>public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}
</code>```

Execute Update-Database -Force

Your database will be updated to latest scheme and ready.

hope this helps.

Body:
I have added EF 5 to my project via Nuget and enabled migrations with the "Enable-Migrations" command. I have then called "Add-Migration" to generate the base code for generating the schema.

I then added a property to one of my domain objects (string property called "TestProperty") and added a mapping to my EntityTypeConfiguration file (we're ignoring the conventions at the moment).

Calling "Add-Migration" again produces the error:

Unable to generate an explicit migration because the following explicit migrations are pending: [201303262144218_Initial]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

But calling "Update-Database" produces a sql exception because the tables already exist:

There is already an object named 'Customer' in the database

In my constructor for my DbContext I have tried the different update strategies, e.g.:

Database.SetInitializer<UnitOfWork>(new DropCreateDatabaseAlways<UnitOfWork>());

Am I missing something obvious?
I tried the solution here but it didn't work: Automatic Migrations for ASP.NET

Thanks

EDIT: Update
The key to getting past the first step is to create the initial migration and then delete the generated code from the Up and Down methods (http://thedatafarm.com/blog/data-access/using-ef-migrations-with-an-existing-database/).

I can then update the model and the EF map and then run Add-Migration. This generates a migration with the correct Up and Down code.

The problem is then trying to apply the update. Update-Database produces the error "Unable to update database to match the current model because there are pending changes and automatic migration is disabled...automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
You can use the Add-Migration command to write the pending model changes to a code-based migration". Ok, so I try Add-Migration again and it produces another migration with the exact same code as the last one.

I run Update-Database and get the same error again. I try "Update-Database -TargetMigration 201304080859556_MyMigration -Force" but this produces "The specified target migration '201304080859556_MyMigration' does not exist. Ensure that target migration refers to an existing migration id" - It does!

Very frustrating!

Body:
Trying to migrate an old db version to a new model, either the database didn't match the new model or i got errors like :

Type is not resolved for member 'Npgsql.PostgresException,Npgsql,
  Version=3.2.2.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'

Here's how it worked (using automatic migration) :

Delete Migrations folder

Execute enable-migrations

Set this two properties to true in the newly created Configuration.cs

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

Execute Update-Database -Force

Your database will be updated to latest scheme and ready.

hope this helps.


问:
Unable to update Nullable field with Null
Facing a strange problem with EF at the moment. I have a table in database with nvarchar(MAX) data type and is a nullable field. While updating the entries in the table when I assign null to this field its not saving that null, rather keeping the old value intact. But saving the empty string in it works.
My code looks like this,

```<code>myobject.field1 = null; // assigning **null** here.
dbcontext.update();
dbcontext.saveChanges();
</code>```

Any solution or guidance will be really appreciated.

What I have tried:

```<code>UseCSharpNullComparisonBehavior
</code>```

and

```<code>UseDatabaseNullSemantics
</code>```

EDIT:

Found the culprit, Our application has Unit of Work and Repositories implemented and we have a base Repository which includes a update method like below,

```<code>public virtual void Update(T entity)
        {

            //Ensure only modified fields are updated.
            _dbEntities.Set<T>().Attach(entity);
            var dbEntityEntry = _dbEntities.Entry<T>(entity);
            foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
            {
                var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
                if (current != null)
                    dbEntityEntry.Property(property).IsModified = true;
            }

        }
</code>```

In this function, updation is restricted in the null case. Though In my opinion this logic is invalid as it does not let the user change the existing value to null if user wants to.

Would love to hear the expert's opinion on this.

Sorry to bother you all.I am new to this kind of advanced logics and that make me stuck.

答:
Try do this:</p>

```<code>myobject.field1 = null;
dbcontext.Entry(myobject).Property(x => x.field1).IsModified = true;
dbcontext.saveChanges()
</code>```

Body:
Facing a strange problem with EF at the moment. I have a table in database with nvarchar(MAX) data type and is a nullable field. While updating the entries in the table when I assign null to this field its not saving that null, rather keeping the old value intact. But saving the empty string in it works.
My code looks like this,

myobject.field1 = null; // assigning **null** here.
dbcontext.update();
dbcontext.saveChanges();

Any solution or guidance will be really appreciated.

What I have tried:

UseCSharpNullComparisonBehavior

and

UseDatabaseNullSemantics

EDIT:

Found the culprit, Our application has Unit of Work and Repositories implemented and we have a base Repository which includes a update method like below,

public virtual void Update(T entity)
        {

            //Ensure only modified fields are updated.
            _dbEntities.Set<T>().Attach(entity);
            var dbEntityEntry = _dbEntities.Entry<T>(entity);
            foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
            {
                var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
                if (current != null)
                    dbEntityEntry.Property(property).IsModified = true;
            }

        }

In this function, updation is restricted in the null case. Though In my opinion this logic is invalid as it does not let the user change the existing value to null if user wants to.

Would love to hear the expert's opinion on this.

Sorry to bother you all.I am new to this kind of advanced logics and that make me stuck.

Body:
Try do this:

myobject.field1 = null;
dbcontext.Entry(myobject).Property(x => x.field1).IsModified = true;
dbcontext.saveChanges()


问:
Chart.js — drawing an arbitrary vertical line
How can I draw an vertical line at a particular point on the x-axis using Chart.js?

In particular, I want to draw a line to indicate the current day on a LineChart. Here's a mockup of the chart:
http://i.stack.imgur.com/VQDWR.png

答:
Sharing my solution for chartjs.org version 2.5. I wanted to use a plugin, to make the implementation reusable.

const verticalLinePlugin = {
  getLinePosition: function (chart, pointIndex) {
      const meta = chart.getDatasetMeta(0); // first dataset is used to discover X coordinate of a point
      const data = meta.data;
      return data[pointIndex]._model.x;
  },
  renderVerticalLine: function (chartInstance, pointIndex) {
      const lineLeftOffset = this.getLinePosition(chartInstance, pointIndex);
      const scale = chartInstance.scales['y-axis-0'];
      const context = chartInstance.chart.ctx;

      // render vertical line
      context.beginPath();
      context.strokeStyle = '#ff0000';
      context.moveTo(lineLeftOffset, scale.top);
      context.lineTo(lineLeftOffset, scale.bottom);
      context.stroke();

      // write label
      context.fillStyle = "#ff0000";
      context.textAlign = 'center';
      context.fillText('MY TEXT', lineLeftOffset, (scale.bottom - scale.top) / 2 + scale.top);
  },

  afterDatasetsDraw: function (chart, easing) {
      if (chart.config.lineAtIndex) {
          chart.config.lineAtIndex.forEach(pointIndex => this.renderVerticalLine(chart, pointIndex));
      }
  }
  };

  Chart.plugins.register(verticalLinePlugin);```
</div>
</div>
</p>

<p>Usage is simple then:</p>

``` new Chart(ctx, {
     type: 'line',
     data: data,
     label: 'Progress',
     options: options,
     lineAtIndex: [2,4,8],
 })
```

The code above inserts red vertical lines at positions 2,4 and 8, running through points of first dataset at those positions.

Body:
Sharing my solution for chartjs.org version 2.5. I wanted to use a plugin, to make the implementation reusable.

const verticalLinePlugin = {
  getLinePosition: function (chart, pointIndex) {
      const meta = chart.getDatasetMeta(0); // first dataset is used to discover X coordinate of a point
      const data = meta.data;
      return data[pointIndex]._model.x;
  },
  renderVerticalLine: function (chartInstance, pointIndex) {
      const lineLeftOffset = this.getLinePosition(chartInstance, pointIndex);
      const scale = chartInstance.scales['y-axis-0'];
      const context = chartInstance.chart.ctx;

      // render vertical line
      context.beginPath();
      context.strokeStyle = '#ff0000';
      context.moveTo(lineLeftOffset, scale.top);
      context.lineTo(lineLeftOffset, scale.bottom);
      context.stroke();

      // write label
      context.fillStyle = "#ff0000";
      context.textAlign = 'center';
      context.fillText('MY TEXT', lineLeftOffset, (scale.bottom - scale.top) / 2 + scale.top);
  },

  afterDatasetsDraw: function (chart, easing) {
      if (chart.config.lineAtIndex) {
          chart.config.lineAtIndex.forEach(pointIndex => this.renderVerticalLine(chart, pointIndex));
      }
  }
  };

  Chart.plugins.register(verticalLinePlugin);

Usage is simple then:

 new Chart(ctx, {
     type: 'line',
     data: data,
     label: 'Progress',
     options: options,
     lineAtIndex: [2,4,8],
 })

The code above inserts red vertical lines at positions 2,4 and 8, running through points of first dataset at those positions.


问:
Distribution Provisioning Problems
I had an app that I finally got finalized and am ready to post it to the App Store so I started the amazingly awful process...

I have been developing on my laptop, testing on my device, and having no issues with my development certificate and provisioning.

I ended up having to rename my project (Project->rename for anyone who needs to know).  I then rebuilt my project, tested it out on my devices and all is ok.

I went online and created my AppID for the project and then created my App Dist Profile.  I Downloaded it and dragged it into XCode's organizer.  I immediately see "A valid signing identity matching this profile could not be found in your keychain."  I've checked my certificates and double checked that I created the right AppID, profile, etc.. What could possibly cause this?

Am I the only one that is constantly blown away at the amount of work that it takes to actually get ON the app store once the app is done?  Anyone else kind of miss the J2ME days (minus the fee's, J-verified, and VeriSign crap.. haha)

Thanks,

-d

答: Have you created and downloaded the Distribution (not Developer) certificate? Did you also install the WWDR certificate (if needed)?</p>

Title: Distribution Provisioning Problems


问:
Ansible Escaping in Shell Module
I was trying to configure an application to connect to ldap and noticed it was failing authentication, so I thought I would check the two commands that get executed to set this up to see what the shell command that ansible executes looks like.
So I disabled the mqsichangeproperties and mqsisetdbparms commands on the server and created the below little test playbook to see what the command string looks like... I run the playbook expecting an error of mqsisetdbparms: command not found
but this would allow me to see cmd and _raw_params keys when running with verbose output.

I noticed that the command for the first task is in the form that I expect:

"cmd": "mqsichangeproperties QM -b webadmin -o server -n ldapAuthenticationUri –v \"ldap://abc.company.com:389/OU=Users,OU=City,OU=Country,DC=company,DC=com\""

However, the command for the second task contains additional blackslashes, resulting in the incorrect username and password being set for the application...

Incorrect command form:

"cmd": "mqsisetdbparms QM -n ldap::company.com -u \"DOMAIN\\username\" -p \"pwd@pwd\""

Expected command form:

"cmd": "mqsisetdbparms QM -n ldap::company.com -u "DOMAIN\username" -p "pwd@pwd""

I feel as if have tried all possible options such as

using double quotes for the variables

escaping in the variables

combination of single and double quotes with the variables and the shell command string

Escaping the backslash in the ldap_usr variable

The test playbook I am using is below...

```<code>---
# file: test.yml
# desc: Test playbook
#
- hosts: target
  gather_facts: no
  vars:
    ldap_server: "ldap://abc.company.com"
    ldap_port: 389
    ldap_baseDN: "OU=Users,OU=City,OU=Country,DC=company,DC=com"
    ldap_usr: 'DOMAIN\username'
    ldap_pwd: 'pwd@pwd'
    ldap_auth_uri: "\"{{ldap_server}}:{{ldap_port}}/{{ldap_baseDN}}\""
  tasks:
#    - name: test setting URI
#      shell: "mqsichangeproperties QM -b webadmin -o server -n ldapAuthenticationUri -v {{ldap_auth_uri}}"
    - name: test setting user
      shell: "mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\""
</code>```

Using Ansible Version 2.2.0.0

答:
Looks to me like the following should work:

```<code>ldap_usr: 'DOMAIN\\username'
</code>```

```<code>shell: mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\"
</code>```

When I echo the resulting string to a file with:

```<code>shell: echo mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\" > ./check.txt
</code>```

or

```<code>shell: printf "mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\"" > ./check.txt
</code>```

I get:

```<code>mqsisetdbparms QM -n ldap::company.com -u "DOMAIN\username" -p "pwd@pwd"
</code>```

which is what you requested.

By the way, you shouldn't rely on the Ansible log to determine what is the real command, as it prints escaped JSON.

Title: Ansible Escaping in Shell Module

Body:
I was trying to configure an application to connect to ldap and noticed it was failing authentication, so I thought I would check the two commands that get executed to set this up to see what the shell command that ansible executes looks like.
So I disabled the mqsichangeproperties and mqsisetdbparms commands on the server and created the below little test playbook to see what the command string looks like... I run the playbook expecting an error of mqsisetdbparms: command not found
but this would allow me to see cmd and _raw_params keys when running with verbose output.

I noticed that the command for the first task is in the form that I expect:

"cmd": "mqsichangeproperties QM -b webadmin -o server -n ldapAuthenticationUri –v \"ldap://abc.company.com:389/OU=Users,OU=City,OU=Country,DC=company,DC=com\""

However, the command for the second task contains additional blackslashes, resulting in the incorrect username and password being set for the application...

Incorrect command form:

"cmd": "mqsisetdbparms QM -n ldap::company.com -u \"DOMAIN\\username\" -p \"pwd@pwd\""

Expected command form:

"cmd": "mqsisetdbparms QM -n ldap::company.com -u "DOMAIN\username" -p "pwd@pwd""

I feel as if have tried all possible options such as

using double quotes for the variables

escaping in the variables

combination of single and double quotes with the variables and the shell command string

Escaping the backslash in the ldap_usr variable

The test playbook I am using is below...

---
# file: test.yml
# desc: Test playbook
#
- hosts: target
  gather_facts: no
  vars:
    ldap_server: "ldap://abc.company.com"
    ldap_port: 389
    ldap_baseDN: "OU=Users,OU=City,OU=Country,DC=company,DC=com"
    ldap_usr: 'DOMAIN\username'
    ldap_pwd: 'pwd@pwd'
    ldap_auth_uri: "\"{{ldap_server}}:{{ldap_port}}/{{ldap_baseDN}}\""
  tasks:
#    - name: test setting URI
#      shell: "mqsichangeproperties QM -b webadmin -o server -n ldapAuthenticationUri -v {{ldap_auth_uri}}"
    - name: test setting user
      shell: "mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\""

Using Ansible Version 2.2.0.0

Body:
Looks to me like the following should work:

ldap_usr: 'DOMAIN\\username'

shell: mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\"

When I echo the resulting string to a file with:

shell: echo mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\" > ./check.txt

or

shell: printf "mqsisetdbparms QM -n ldap::company.com -u \"{{ldap_usr}}\" -p \"{{ldap_pwd}}\"" > ./check.txt

I get:

mqsisetdbparms QM -n ldap::company.com -u "DOMAIN\username" -p "pwd@pwd"

which is what you requested.

By the way, you shouldn't rely on the Ansible log to determine what is the real command, as it prints escaped JSON.


问:
how can I access List type of data in django
client side, I sent a JSON data including list type data like this.

```<code> $.ajax({
     url: '/man/manual',
     type: 'POST',
     data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]},
     dataType : 'JSON',
     success : function(data) {
         console.log(data);
     }
 });
</code>```

I tried to access these data.

```<code>title = request.POST['title']
description = request.POST['description']
steps = request.POST['steps']

for step in steps:
    print(step.title)
</code>```

but I got an error.

```<code>Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response

132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view

71. return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post
77. self.createManual(request)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual
27. steps = request.POST['steps']
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__
322. raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /man/manual
Exception Value: "'steps'"
Request information:
GET: No GET data

POST:
description = 'desc'
steps[1][title] = '2'
steps[0][title] = '1'
title = 'ttt'
id = ''
</code>```

How can I change my to code for correct data from client side.

答:
First, what I would send in the data attribute of the AJAX request would be JSON.stringify({...}) of what you are sending now.

Then, on the python code, I would do : import json; json.loads(request.body) and that would give you the initial JS dictionary in python. Then you can use it as a normal dictionary.

Also step is a dictionary so the right way to print it would be print(step['title']) instead of print(step.title)

edit:
If the json string is not plain ASCII, you might need to decode it first using something like : json.loads(request.body.decode(), encoding='utf-8')

Body:
client side, I sent a JSON data including list type data like this.

 $.ajax({
     url: '/man/manual',
     type: 'POST',
     data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]},
     dataType : 'JSON',
     success : function(data) {
         console.log(data);
     }
 });

I tried to access these data.

title = request.POST['title']
description = request.POST['description']
steps = request.POST['steps']

for step in steps:
    print(step.title)

but I got an error.

Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response

132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view

71. return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post
77. self.createManual(request)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual
27. steps = request.POST['steps']
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__
322. raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /man/manual
Exception Value: "'steps'"
Request information:
GET: No GET data

POST:
description = 'desc'
steps[1][title] = '2'
steps[0][title] = '1'
title = 'ttt'
id = ''

How can I change my to code for correct data from client side.


问:
Laravel - Using allfiles gives back empty array
I've been using laravel for nearly all my projects and I've came across a problem when trying to list all files in a directory.

Here is my code below:

```<code>            $directory = ("upload/"."$username->username");

        $scanned_directory = storage::allfiles($directory);
</code>```

So as you can see First line is the directory which is in Upload followed by the username of the account.

The second line is meant to scan this directory and list only files. Sadly it always gives me back an empty array. Using Scandir() here works... But it gives me folders which I'm not wanting.

So... Any tips? I checked the API and I really can't see what is wrong here :(

答:
The reason you're getting no results when using the Storage::allFiles('directory') method is this method only looks inside of your application's storage folder, usually storage/app. Hence why modifying the storage path in configuration works as mentioned by @yassine (you shouldn't do this).

If you wish to use files outside of the storage folder, simply use the File facade instead. e.g. File::allFiles('directory')

Body:
I've been using laravel for nearly all my projects and I've came across a problem when trying to list all files in a directory.

Here is my code below:

            $directory = ("upload/"."$username->username");

        $scanned_directory = storage::allfiles($directory);

So as you can see First line is the directory which is in Upload followed by the username of the account.

The second line is meant to scan this directory and list only files. Sadly it always gives me back an empty array. Using Scandir() here works... But it gives me folders which I'm not wanting.

So... Any tips? I checked the API and I really can't see what is wrong here :(


问:
Module parse failed: es6 react component with JSX inside .JS file
Webpack Babel loader fails when importing an es6 react component with .js as the filename extension. If the filename extension is changed to .jsx babel compiles properly. Any clue?

var config = {
  entry : {
    "login" : PAGE_DIR + '/login/index.js',
    "app" : PAGE_DIR + '/app/index.js'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name]-bundle.js'
  },
  module : {
  rules : [
     {
        test : /\.(js|jsx)$/,
        include : PAGE_DIR,
    exclude: [
      path.resolve(__dirname, "node_modules"),
    ],
        loaders : ['babel-loader']
      }
  ]
  }
};```
</div>
</div>
</p>

<p>EDIT:</p>

<p>Updating the logs below.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>> webpack -d

Hash: 83d5fd2d0c1113e55b32
Version: webpack 2.2.1
Time: 2057ms
          Asset     Size  Chunks                    Chunk Names
  app-bundle.js  2.28 MB       0  [emitted]  [big]  app
login-bundle.js  1.98 MB       1  [emitted]  [big]  login
  [18] ./~/react-dom/lib/ReactReconciler.js 6.21 kB {0} {1} [built]
  [19] ./~/react/lib/React.js 2.69 kB {0} {1} [built]
  [31] ./~/react/react.js 56 bytes {0} {1} [built]
  [80] ./~/react-dom/index.js 59 bytes {0} {1} [built]
 [109] ./~/react-dom/lib/ReactDOM.js 5.14 kB {0} {1} [built]
 [179] ./~/redux/es/index.js 1.08 kB {0} [built]
 [192] ./app/state/store.js 330 bytes {0} [built]
 [193] ./~/react-redux/es/index.js 194 bytes {0} [built]
 [196] ./app/state/reducer.js 766 bytes {0} [built]
 [209] ./~/react-redux/es/connect/connect.js 5.34 kB {0} [built]
 [215] ./~/react-redux/es/utils/Subscription.js 2.59 kB {0} [built]
 [216] ./~/react-redux/es/utils/shallowEqual.js 677 bytes {0} [built]
 [220] ./~/redux-logger/lib/index.js 4.45 kB {0} [built]
 [228] ./app/pages/app/index.jsx 694 bytes {0} [built]
 [229] ./app/pages/login/index.jsx 2.33 kB {1} [built]
    + 215 hidden modules

ERROR in ./app/components/login.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/login.jsx Unexpected token (15:6)
You may need an appropriate loader to handle this file type.
|   render () {
|     return (
|       <form className="login">
|         <input type="email" name="emailid" placeholder="Email ID" onChange={this.changeEmailId.bind(this)} /><br/>
|         <input type="password" name="password" placeholder="Password" onChange={this.changePassword.bind(this)} /><br/>
 @ ./app/pages/login/index.jsx 11:13-50

ERROR in ./app/components/app.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/app.jsx Unexpected token (30:3)
You may need an appropriate loader to handle this file type.
|
|     return (
|    <div className='row'>
|     <div className='twelve columns'>
|      Logout
 @ ./app/pages/app/index.jsx 15:11-46</code>```

答:
You may need to install configure presets in you webpack config like

```<code>module : {
        rules : [
           {
            test : /\.(js|jsx)$/,
            include : PAGE_DIR,
            exclude: [
                  path.resolve(__dirname, "node_modules"),
            ],
            loaders : ['babel-loader'],
            query: {
                 presets: ['react','es2015', 'stage-0']
             }
            }
        ]
  }
</code>```

Install them first using

```<code>npm install -S babel-preset-es2015 babel-preset-react babel-preset-stage-0
</code>```

Body:
Webpack Babel loader fails when importing an es6 react component with .js as the filename extension. If the filename extension is changed to .jsx babel compiles properly. Any clue?

var config = {
  entry : {
    "login" : PAGE_DIR + '/login/index.js',
    "app" : PAGE_DIR + '/app/index.js'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name]-bundle.js'
  },
  module : {
  rules : [
     {
        test : /\.(js|jsx)$/,
        include : PAGE_DIR,
    exclude: [
      path.resolve(__dirname, "node_modules"),
    ],
        loaders : ['babel-loader']
      }
  ]
  }
};

EDIT:

Updating the logs below.

> webpack -d

Hash: 83d5fd2d0c1113e55b32
Version: webpack 2.2.1
Time: 2057ms
          Asset     Size  Chunks                    Chunk Names
  app-bundle.js  2.28 MB       0  [emitted]  [big]  app
login-bundle.js  1.98 MB       1  [emitted]  [big]  login
  [18] ./~/react-dom/lib/ReactReconciler.js 6.21 kB {0} {1} [built]
  [19] ./~/react/lib/React.js 2.69 kB {0} {1} [built]
  [31] ./~/react/react.js 56 bytes {0} {1} [built]
  [80] ./~/react-dom/index.js 59 bytes {0} {1} [built]
 [109] ./~/react-dom/lib/ReactDOM.js 5.14 kB {0} {1} [built]
 [179] ./~/redux/es/index.js 1.08 kB {0} [built]
 [192] ./app/state/store.js 330 bytes {0} [built]
 [193] ./~/react-redux/es/index.js 194 bytes {0} [built]
 [196] ./app/state/reducer.js 766 bytes {0} [built]
 [209] ./~/react-redux/es/connect/connect.js 5.34 kB {0} [built]
 [215] ./~/react-redux/es/utils/Subscription.js 2.59 kB {0} [built]
 [216] ./~/react-redux/es/utils/shallowEqual.js 677 bytes {0} [built]
 [220] ./~/redux-logger/lib/index.js 4.45 kB {0} [built]
 [228] ./app/pages/app/index.jsx 694 bytes {0} [built]
 [229] ./app/pages/login/index.jsx 2.33 kB {1} [built]
    + 215 hidden modules

ERROR in ./app/components/login.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/login.jsx Unexpected token (15:6)
You may need an appropriate loader to handle this file type.
|   render () {
|     return (
|       <form className="login">
|         <input type="email" name="emailid" placeholder="Email ID" onChange={this.changeEmailId.bind(this)} />

|         <input type="password" name="password" placeholder="Password" onChange={this.changePassword.bind(this)} />

 @ ./app/pages/login/index.jsx 11:13-50

ERROR in ./app/components/app.jsx
Module parse failed: /Users/vsank1/Documents/workspace/registration/kudumbayogam/app/components/app.jsx Unexpected token (30:3)
You may need an appropriate loader to handle this file type.
|
|     return (
|

|

|      Logout
 @ ./app/pages/app/index.jsx 15:11-46

Body:
You may need to install configure presets in you webpack config like

module : {
        rules : [
           {
            test : /\.(js|jsx)$/,
            include : PAGE_DIR,
            exclude: [
                  path.resolve(__dirname, "node_modules"),
            ],
            loaders : ['babel-loader'],
            query: {
                 presets: ['react','es2015', 'stage-0']
             }
            }
        ]
  }

Install them first using

npm install -S babel-preset-es2015 babel-preset-react babel-preset-stage-0


问:
(PYTHON) How to get sub elements (Selenium)
so I'm really new to python and I wanna get my number of friends I got on a site named roblox for the sake of learning. This is where my code is right now:

```<code> from selenium import webdriver
 ff = webdriver.FireFox()
 ff.get("https://www.roblox.com/home")
 element = driver.find_element_by_class("col-xs-12 section home-friends"[0])
</code>```

where I am currently

I want to get the text "Friends (2)"

any ways of doing that?

答:
What you need is:

```<code>    text = driver.find_element_by_class("col-xs-12 section home-friends")
.find_element_by_tag_name("h3").text
</code>```

If you have more than 1 , you can find the element with class = "container-header" first:

```<code>    text = driver.find_element_by_class("col-xs-12 section home-friends")
.find_element_by_class_name("container-header").find_element_by_tag_name("h3").text
</code>```

Body:
so I'm really new to python and I wanna get my number of friends I got on a site named roblox for the sake of learning. This is where my code is right now:

 from selenium import webdriver
 ff = webdriver.FireFox()
 ff.get("https://www.roblox.com/home")
 element = driver.find_element_by_class("col-xs-12 section home-friends"[0])

where I am currently

I want to get the text "Friends (2)"

any ways of doing that?

Body:
What you need is:

    text = driver.find_element_by_class("col-xs-12 section home-friends")
.find_element_by_tag_name("h3").text

If you have more than 1 , you can find the element with class = "container-header" first:

    text = driver.find_element_by_class("col-xs-12 section home-friends")
.find_element_by_class_name("container-header").find_element_by_tag_name("h3").text


问:
Pull variable name through to constructor on object instantiation
Here's an example constructor

```<code>function AnObject(a, b){
    this.a = a;
    this.b = b;
}
</code>```

and an instantiation of it

```<code>var example = new AnObject('test', 'test');
</code>```

Lets say that the constructor had a property .name

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

In the case above, the name would be example

-EDIT-

The reason I am trying to achieve this is to be as "D.R.Y" as possible.

I would like to NOT have to:

```<code>var example = new ObjectWithName('example');
</code>```

答:
is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

When you create a new object with

```<code>new AnObject('test', 'test')
</code>```

this results in an object reference, which can be then just used directly:

```<code>(new AnObject("test","test")).a
</code>```

or discarded

```<code> new AnObject('test', 'test')
</code>```

or assigned to some other object property:

```<code> myotherobject["b"]=new AnObject('test', 'test')
</code>```

or pushed into an array:

```<code> myarr.push(new AnObject('test', 'test'))
</code>```

or assigned to multiple variables at once

```<code>a=b=c=d=e = new AnObject('test', 'test');
</code>```

and there is no way your constructor can know in which way the object (reference) will be used, or know the name of the variable it will be assigned to (in case of simple variable assignment).

In other words creating an object and doing something with the resulting object reference are two completely independent actions.

So unless you explicitly pass the "name" value into the constructor as the argument:

```<code>var example = new AnObject('example','test','test')
</code>```

or set it later on

```<code>example.name="example"
</code>```

there is no way you can achieve that.

Body:
Here's an example constructor

function AnObject(a, b){
    this.a = a;
    this.b = b;
}

and an instantiation of it

var example = new AnObject('test', 'test');

Lets say that the constructor had a property .name

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

In the case above, the name would be example

-EDIT-

The reason I am trying to achieve this is to be as "D.R.Y" as possible.

I would like to NOT have to:

var example = new ObjectWithName('example');

Body:
is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with?

When you create a new object with

new AnObject('test', 'test')

this results in an object reference, which can be then just used directly:

(new AnObject("test","test")).a

or discarded

 new AnObject('test', 'test')

or assigned to some other object property:

 myotherobject["b"]=new AnObject('test', 'test')

or pushed into an array:

 myarr.push(new AnObject('test', 'test'))

or assigned to multiple variables at once

a=b=c=d=e = new AnObject('test', 'test');

and there is no way your constructor can know in which way the object (reference) will be used, or know the name of the variable it will be assigned to (in case of simple variable assignment).

In other words creating an object and doing something with the resulting object reference are two completely independent actions.

So unless you explicitly pass the "name" value into the constructor as the argument:

var example = new AnObject('example','test','test')

or set it later on

example.name="example"

there is no way you can achieve that.


问:
Update database table using ajax call
I have HTML page which contains a Editable table, Where I am fetching the data from database using PHP and inserting into the that table. As my table is Editable, I want to update the values into the database when the user update any row value.

Please suggest me,because I don't know how to make AJAX call when user edits and click anywhere on browser.

答:
You have to catch the moment where the datas are saved in your datatable: Often a click on a button.
So you need a code like that :

```<code>$(document).ready(function(){
 $('#save-row-4').on('click', function(){
   // Your ajax call here
 });
});
</code>```

The ajax have to be like :

```<code>$.ajax({
    url: '/path/to/php/script.php',
    type: 'POST',
    data: {
       variable1: 'val1',
       variable2: 'val2',
       variable3: 'val3'
    },
    error: function(return) {
        alert("error");
    },
    success: function(return) {
        console.log("Datas saved");
    },
});
</code>```

Don't forget to replace val1, val2 with the value of your inputs. Then, in your php script, you will be able to get these datas with $_POST['variable1'] .

Title: Update database table using ajax call

Body:
You have to catch the moment where the datas are saved in your datatable: Often a click on a button.
So you need a code like that :

$(document).ready(function(){
 $('#save-row-4').on('click', function(){
   // Your ajax call here
 });
});

The ajax have to be like :

$.ajax({
    url: '/path/to/php/script.php',
    type: 'POST',
    data: {
       variable1: 'val1',
       variable2: 'val2',
       variable3: 'val3'
    },
    error: function(return) {
        alert("error");
    },
    success: function(return) {
        console.log("Datas saved");
    },
});

Don't forget to replace val1, val2 with the value of your inputs. Then, in your php script, you will be able to get these datas with $_POST['variable1'] .


问:
Embedding MySQL Database into application in C#
I am currently looking into developing an application in C#. The application will need to use a database backend but I was wondering if it possible to embed a database into the application itself. I.e. the user would not need to install MSSQL or MySQL onto the computers separately to my own app but instead install my program and the database is installed with it. If possible I would like to use something like a MySQL Database but not needing the user to install the MySQL Server. Is there a free option to resolve this problem.

Thanks for your help

答:
Look at System.Data.SQLite which can be embedded into your program.

System.Data.SQLite is the original
  SQLite database engine and a complete
  ADO.NET 2.0/3.5 provider all rolled
  into a single mixed mode assembly.  It
  is a complete drop-in replacement for
  the original sqlite3.dll (you can even
  rename it to sqlite3.dll if you're
  using it natively).


问:
React-router and server sided rendering
I would like to render server sided with react-router and Koa. However I only got it to work if I included the full node build. This is duo to my components requiring sass compiling, image handling and the like.

It would be great if my front end application is pre-compiled and routes and their relative pages rendered to string are obtained from there.

Right now I import routes from a routes.js file which exports the following and with it the uncompiled components:

```<code>export default (
    <Route path="/" component={Shell}>
        <IndexRoute component={Home} />
        <Route path="sub">
            <Route path="zero" component={SubZero} />
        </Route>
        <Route path="finish" component={Him} />
    </Route>
)
</code>```

答:
I will dig through https://github.com/RickWong/react-isomorphic-starterkit

It will probably shine light upon my question.

Edit: Infact it does. Compiling the server.js file which imports routes with webpack will compile into an server file which has all magic (image minifying, sass compiling etc) done.

Title: React-router and server sided rendering

Body:
I would like to render server sided with react-router and Koa. However I only got it to work if I included the full node build. This is duo to my components requiring sass compiling, image handling and the like.

It would be great if my front end application is pre-compiled and routes and their relative pages rendered to string are obtained from there.

Right now I import routes from a routes.js file which exports the following and with it the uncompiled components:

export default (
    <Route path="/" component={Shell}>
        <IndexRoute component={Home} />
        <Route path="sub">
            <Route path="zero" component={SubZero} />
        </Route>
        <Route path="finish" component={Him} />
    </Route>
)


问:
S3ResponseError: 301 Moved Permanently - Django
I have a very big issue with Amazon S3. I am working on a Django app and I want to store file on S3:
My settings are:

```<code>AWS_STORAGE_BUCKET_NAME = 'tfjm2-inscriptions'
AWS_ACCESS_KEY_ID = 'id'
AWS_SECRET_ACCESS_KEY = 'key'
AWS_S3_CUSTOM_DOMAIN = '%s.s3-eu-west-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
</code>```

And I get this error: S3ResponseError: 301 Moved Permanently

Some same issues on the Internet say that it is because it is a non-US bucket and I did tried with a US-standard bucket but it get a 401 Forbidden error.....

I do not know what to do.

Please help me.

Thank you

答:
in terminal run 'nano ~/.boto'
if there is some configs try to comment or rename file and connect again. (it helps me)
http://boto.cloudhackers.com/en/latest/boto_config_tut.html
there is boto config file directories. take a look one by one and clean them all, it will work by default configs. also configs may be in .bash_profile, .bash_source...
I guess you must allow only KEY-SECRET</p>

Body:
I have a very big issue with Amazon S3. I am working on a Django app and I want to store file on S3:
My settings are:

AWS_STORAGE_BUCKET_NAME = 'tfjm2-inscriptions'
AWS_ACCESS_KEY_ID = 'id'
AWS_SECRET_ACCESS_KEY = 'key'
AWS_S3_CUSTOM_DOMAIN = '%s.s3-eu-west-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

And I get this error: S3ResponseError: 301 Moved Permanently

Some same issues on the Internet say that it is because it is a non-US bucket and I did tried with a US-standard bucket but it get a 401 Forbidden error.....

I do not know what to do.

Please help me.

Thank you


问:
how i can just choose only 1 radio button in my html
i have problem in radio button, i need just choosed 1 answer.
but in my codes i can choose all of answer... help me pls

```<code>    <div class="row">
        <div class="col-md-10">
            <div class="input-group input-group">
               <span class="input-group-addon"><strong>A.</strong></span>
                {{Form::textarea('Jawaban_A', Input::old('Jawaban_A'), array('class' => 'form-control' , 'rows' =>
                2))}}
        <span class="input-group-addon">
            {{Form::radio('a_is_benar', 1, Input::old('a_is_benar'), array('id' => 'a_is_benar'))}}
            {{Form::label('a_is_benar', 'Benar', array('class' => 'control-label'));}}
        </span>
            </div>
        </div>
        <div class="col-md-2">
            <div class="input-group input-group">
                <span class="input-group-addon">Poin</span>
                {{Form::text('Point_Jawaban_A', Input::old('Point_Jawaban_A') ? Input::old('Point_Jawaban_A') : 0,
                array('class' => 'form-control input-lg'))}}
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-10">
            <div class="input-group input-group">
                <span class="input-group-addon"><strong>B.</strong></span>
                {{Form::textarea('Jawaban_B', Input::old('Jawaban_B'), array('class' => 'form-control' , 'rows' =>
                2))}}
        <span class="input-group-addon">
            {{Form::radio('b_is_benar', 1, Input::old('b_is_benar'), array('id' => 'b_is_benar'))}}
            {{Form::label('b_is_benar', 'Benar', array('class' => 'control-label'));}}
        </span>
            </div>
        </div>
        <div class="col-md-2">
            <div class="input-group input-group">
                <span class="input-group-addon">Poin</span>
                {{Form::text('Point_Jawaban_B', Input::old('Point_Jawaban_B') ? Input::old('Point_Jawaban_B') : 0,
                array('class' => 'form-control input-lg'))}}
            </div>
        </div>
    </div>
</code>```

im using laravel, this is blade view...
maybe have trick for my problem

答:
Put it inside a single Form tag.
Then Use Radio Button with same name for Uniquely Selection which you are doing right now.

The Only thing you need to do is to add it inside a single form.

Body:
i have problem in radio button, i need just choosed 1 answer.
but in my codes i can choose all of answer... help me pls

               A.
                {{Form::textarea('Jawaban_A', Input::old('Jawaban_A'), array('class' => 'form-control' , 'rows' =>
                2))}}

            {{Form::radio('a_is_benar', 1, Input::old('a_is_benar'), array('id' => 'a_is_benar'))}}
            {{Form::label('a_is_benar', 'Benar', array('class' => 'control-label'));}}

                Poin
                {{Form::text('Point_Jawaban_A', Input::old('Point_Jawaban_A') ? Input::old('Point_Jawaban_A') : 0,
                array('class' => 'form-control input-lg'))}}

                B.
                {{Form::textarea('Jawaban_B', Input::old('Jawaban_B'), array('class' => 'form-control' , 'rows' =>
                2))}}

            {{Form::radio('b_is_benar', 1, Input::old('b_is_benar'), array('id' => 'b_is_benar'))}}
            {{Form::label('b_is_benar', 'Benar', array('class' => 'control-label'));}}

                Poin
                {{Form::text('Point_Jawaban_B', Input::old('Point_Jawaban_B') ? Input::old('Point_Jawaban_B') : 0,
                array('class' => 'form-control input-lg'))}}

im using laravel, this is blade view...
maybe have trick for my problem


问:
Multiple values of the same column name in SQL
this might seem like a weird question, earlier I posted another question on ASP multiple values through a session variable, I've now figured that out and have managed to pass all three values for instance to a label. Now however I need to pass the three IDs to create a gridview for the three values... So for my SQL statement I have:

SelectCommand="SELECT [BookID], [book_title] FROM [tblBook] WHERE ([BookID] = ?)">

So I need there to be 3 BookID=?,?,? for instance, is this possible?

Or is there another way to do it in ASP?

答:
I'm not certain by your question, but I think you're after an IN statement

```<code>SelectCommand="SELECT [BookID], [book_title] FROM [tblBook] WHERE ([BookID] in (1,2,3)">
</code>```

Body:
I'm not certain by your question, but I think you're after an IN statement

SelectCommand="SELECT [BookID], [book_title] FROM [tblBook] WHERE ([BookID] in (1,2,3)">