问:
Not able to connect mongodb via redash
I am trying to connect to mongodb to redash from local machine.

1) Both mongo and redash are on standalone system.

2) I am able to connect to mongo from terminal. Please see the my terminal details after, I login to it.

```<code>rahul@rahul-VirtualBox:~$ mongo -u rahul -p
MongoDB shell version v3.6.3
Enter password:
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten]
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten]
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten]
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
>
</code>```

3) I am using Ubuntu 16.04 as my OS.

4) Details i am entering to connect to Mongo using redash

Name: Localhost_mongo
 Connection
  String:mongodb://rahul:password@127.0.0.1:27017

  Database Name:admin

5) I am getting error connection refused err no:111

6) Below is my config file details & location : /etc/mongodb.conf

```<code># mongodb.conf

# Where to store the data.
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

bind_ip = 0.0.0.0
port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

# Turn on/off security.  Off is currently the default
#noauth = true
#auth = true

# Verbose logging output.
#verbose = true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true

# Enable db quota management
#quota = true

# Set diagnostic logging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog = 0

# Diagnostic/debugging option
#nocursors = true

# Ignore query hints
#nohints = true

# Disable the HTTP interface (Defaults to localhost:27018).
#nohttpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Accout token for Mongo monitoring server.
#mms-token = <token>

# Server name for Mongo monitoring server.
#mms-name = <server-name>

# Ping interval for Mongo monitoring server.
#mms-interval = <seconds>

# Replication Options
#   3=both
#   7=W+some reads
#diaglog = 0

# Diagnostic/debugging option
#nocursors = true

# Ignore query hints
#nohints = true

# Disable the HTTP interface (Defaults to localhost:27018).
#nohttpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Accout token for Mongo monitoring server.
#mms-token = <token>

# Server name for Mongo monitoring server.
#mms-name = <server-name>

# Ping interval for Mongo monitoring server.
#mms-interval = <seconds>

# Replication Options
</code>```

Please help.
Thank you for your help.

答:
Have you added iptable rules since you have mentioned that redash and mongodb are both on  standalone systems? If you have already done check if you have  a conflict between multiple rules.

I have noticed a user suggesting to comment out bind_ip line which you shouldn't do, since bind_ip = 0.0.0.0 allows connection to be established from all hosts.

Title: Not able to connect mongodb via redash

Body:
I am trying to connect to mongodb to redash from local machine.

1) Both mongo and redash are on standalone system.

2) I am able to connect to mongo from terminal. Please see the my terminal details after, I login to it.

rahul@rahul-VirtualBox:~$ mongo -u rahul -p
MongoDB shell version v3.6.3
Enter password:
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Server has startup warnings:
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten]
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-05-24T20:05:14.788+0530 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten]
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-05-24T20:05:16.607+0530 I CONTROL  [initandlisten]
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
>

3) I am using Ubuntu 16.04 as my OS.

4) Details i am entering to connect to Mongo using redash

Name: Localhost_mongo
 Connection
  String:mongodb://rahul:password@127.0.0.1:27017

  Database Name:admin

5) I am getting error connection refused err no:111

6) Below is my config file details & location : /etc/mongodb.conf

# mongodb.conf

# Where to store the data.
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

bind_ip = 0.0.0.0
port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

# Turn on/off security.  Off is currently the default
#noauth = true
#auth = true

# Verbose logging output.
#verbose = true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true

# Enable db quota management
#quota = true

# Set diagnostic logging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog = 0

# Diagnostic/debugging option
#nocursors = true

# Ignore query hints
#nohints = true

# Disable the HTTP interface (Defaults to localhost:27018).
#nohttpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Accout token for Mongo monitoring server.
#mms-token = <token>

# Server name for Mongo monitoring server.
#mms-name = <server-name>

# Ping interval for Mongo monitoring server.
#mms-interval = <seconds>

# Replication Options
#   3=both
#   7=W+some reads
#diaglog = 0

# Diagnostic/debugging option
#nocursors = true

# Ignore query hints
#nohints = true

# Disable the HTTP interface (Defaults to localhost:27018).
#nohttpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Accout token for Mongo monitoring server.
#mms-token = <token>

# Server name for Mongo monitoring server.
#mms-name = <server-name>

# Ping interval for Mongo monitoring server.
#mms-interval = <seconds>

# Replication Options

Please help.
Thank you for your help.


来源: stackexchange

问:
What is the right way to enable contextual links on a field template with custom code?
I'm trying to figure out if there a way to enable contextual-links on a field twig template using custom code. I have an entity reference field and created a field templatefield--field-featured-page.html.twig below is a code snippet for the field template.

After clearing the cache I can't seem to enable the contextual links.

```<code><div class="related-links -home :three-column">

    {% for item in items  %}

        {% set entity = item.content['#options'].entity %}

        <div class="related-link">
            <a href="{{ path('entity.node.canonical', {'node': entity.id})  }}" class="thumbnail -landscape" style="background-image:url({{ file_url(entity.field_image.entity.uri.value) }})">
            </a>
            <h2 class="preamble-heading" data-preamble="{{ entity.field_preamble.value }}">{{ entity.label }}</h2>

        </div>

    {% endfor %}
</div>
</code>```

Below is a snippet of the markup for the contextual-link. Adding this markup and fetching the node ID might solve the problem but it seems to be hackish. What is the proper way to enable contextual-links on a field twig template?

```<code>{% set node_id = item.content['#options'].entity.id %}

{# Contextual Links #}

<div data-contextual-id="node:node={{ node_id }}:&langcode={{ lang_code }}" class="contextual contextual-button" role="form">
<button class="trigger focusable" type="button" aria-pressed="false"></button>

    <ul class="contextual-links" hidden="">
        <li class="entitynodeedit-form"><a href="{{ url('<front>') }}node/{{ node_id }}/edit">Edit</a></li>
        <li class="entitynodedelete-form"><a href="{{ url('<front>') }}node/{{ node_id }}/delete">Delete</a></li>
        <li class="content-translationcontextual-linksnode"><a href="{{ url('<front>') }}node/{{ node_id }}/translations">Translate</a></li>
    </ul>
</div>
</code>```

The code below is the template for a specific content type (Basic Page)

```<code>{{ page.header }}

<div {{attributes.addClass('iom-home')}}>
    {{ title_suffix }}

    {{ content.field_featured_page  }}

</div>

{{ page.footer }}
</code>```

答:
Just ran into this same issue -- seems like the contextual links are rendered by {{ title_suffix }} in each template. At least it seems to be the case for a block template. Not sure if it'll work for a field template.

So updating your snippet to the following might work (Assuming that it corresponds with the contents of your field--field-featured-page.html.twig):

```<code><div class="related-links -home :three-column">

    {{ title_suffix }}

    {% for item in items  %}

        {% set entity = item.content['#options'].entity %}

        <div class="related-link">
            <a href="{{ path('entity.node.canonical', {'node': entity.id})  }}" class="thumbnail -landscape" style="background-image:url({{ file_url(entity.field_image.entity.uri.value) }})">
            </a>
            <h2 class="preamble-heading" data-preamble="{{ entity.field_preamble.value }}">{{ entity.label }}</h2>

        </div>

    {% endfor %}
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to figure out if there a way to enable contextual-links on a field twig template using custom code. I have an entity reference field and created a field templatefield--field-featured-page.html.twig below is a code snippet for the field template.

After clearing the cache I can't seem to enable the contextual links.

    {% for item in items  %}

        {% set entity = item.content['#options'].entity %}

{{ entity.label }}

    {% endfor %}

Below is a snippet of the markup for the contextual-link. Adding this markup and fetching the node ID might solve the problem but it seems to be hackish. What is the proper way to enable contextual-links on a field twig template?

{% set node_id = item.content['#options'].entity.id %}

{# Contextual Links #}

<button class="trigger focusable" type="button" aria-pressed="false"></button>

<a href="{{ url('<front>') }}node/{{ node_id }}/edit">Edit

<a href="{{ url('<front>') }}node/{{ node_id }}/delete">Delete

<a href="{{ url('<front>') }}node/{{ node_id }}/translations">Translate

The code below is the template for a specific content type (Basic Page)

{{ page.header }}

    {{ title_suffix }}

    {{ content.field_featured_page  }}

{{ page.footer }}

Body:
Just ran into this same issue -- seems like the contextual links are rendered by {{ title_suffix }} in each template. At least it seems to be the case for a block template. Not sure if it'll work for a field template.

So updating your snippet to the following might work (Assuming that it corresponds with the contents of your field--field-featured-page.html.twig):

<div class="related-links -home :three-column">

    {{ title_suffix }}

    {% for item in items  %}

        {% set entity = item.content['#options'].entity %}

        <div class="related-link">
            <a href="{{ path('entity.node.canonical', {'node': entity.id})  }}" class="thumbnail -landscape" style="background-image:url({{ file_url(entity.field_image.entity.uri.value) }})">
            </a>
            <h2 class="preamble-heading" data-preamble="{{ entity.field_preamble.value }}">{{ entity.label }}</h2>

        </div>

    {% endfor %}
</div>


问:
how do you send email from R
I want to send emails from R. This is what I have so far:

```<code>library(sendmailR)

from <- "eamil@example.com"
to <- "email2@example.com"
subject <- "Performance Result"
body <- "This is the result of the test:"
mailControl=list(smtpServer="snmpt server address")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
</code>```

When I execute this script, my R session hangs. Any ideas what might be happening?

答:
There is a new package called emayili with two very interesting promises:

works on all manner of SMTP servers

has minimal dependencies (or dependencies which are easily satisfied)

It seems early stages but promising nonetheless. Sending email is as simple as:

```<code>devtools::install_github("datawookie/emayili")
library(emayili)
library(dplyr)

email <- envelope() %>%
  from("alice@yahoo.com") %>%
  to("bob@google.com") %>%
  subject("This is a plain text message!") %>%
  body("Hello!")

smtp <- server(host = "smtp.gmail.com",
               port = 465,
               username = "bob@gmail.com",
               password = "bd40ef6d4a9413de9c1318a65cbae5d7")

smtp(email, verbose = TRUE)
</code>```

ContentLicense: CC BY-SA 3.0

Title: how do you send email from R

Body:
I want to send emails from R. This is what I have so far:

library(sendmailR)

from <- "eamil@example.com"
to <- "email2@example.com"
subject <- "Performance Result"
body <- "This is the result of the test:"
mailControl=list(smtpServer="snmpt server address")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)

When I execute this script, my R session hangs. Any ideas what might be happening?

Body:
There is a new package called emayili with two very interesting promises:

works on all manner of SMTP servers

has minimal dependencies (or dependencies which are easily satisfied)

It seems early stages but promising nonetheless. Sending email is as simple as:

devtools::install_github("datawookie/emayili")
library(emayili)
library(dplyr)

email <- envelope() %>%
  from("alice@yahoo.com") %>%
  to("bob@google.com") %>%
  subject("This is a plain text message!") %>%
  body("Hello!")

smtp <- server(host = "smtp.gmail.com",
               port = 465,
               username = "bob@gmail.com",
               password = "bd40ef6d4a9413de9c1318a65cbae5d7")

smtp(email, verbose = TRUE)


问:
How to embed textview in react-google-maps?
How to embed textview in react-google-maps? I have successfully created a google map page in react using react-google-maps api. This is how I insert the marker and link the marker using polyline.

```<code>import React from "react";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  Polyline
} from "react-google-maps";

const pathCoordinates = [
        { lat: 1.322459, lng: 103.853972 },
        { lat: 1.39227, lng: 103.752 }
    ];

const CustomSkinMap = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={12}
      defaultCenter={{ lat: 1.322459, lng: 103.853972 }}
      defaultOptions={{
        scrollwheel: false,
        zoomControl: true,
        styles: [
          {
            featureType: "water",
            stylers: [
              { saturation: 43 },
              { lightness: -11 },
              { hue: "#0088ff" }
            ]
          },
          {
            featureType: "road",
            elementType: "geometry.fill",
            stylers: [
              { hue: "#ff0000" },
              { saturation: -100 },
              { lightness: 99 }
            ]
          },
          {
            featureType: "road",
            elementType: "geometry.stroke",
            stylers: [{ color: "#808080" }, { lightness: 54 }]
          },
          {
            featureType: "landscape.man_made",
            elementType: "geometry.fill",
            stylers: [{ color: "#ece2d9" }]
          },
          {
            featureType: "poi.park",
            elementType: "geometry.fill",
            stylers: [{ color: "#ccdca1" }]
          },
          {
            featureType: "road",
            elementType: "labels.text.fill",
            stylers: [{ color: "#767676" }]
          },
          {
            featureType: "road",
            elementType: "labels.text.stroke",
            stylers: [{ color: "#ffffff" }]
          },
          { featureType: "poi", stylers: [{ visibility: "off" }] },
          {
            featureType: "landscape.natural",
            elementType: "geometry.fill",
            stylers: [{ visibility: "on" }, { color: "#b8cb93" }]
          },
          { featureType: "poi.park", stylers: [{ visibility: "on" }] },
          {
            featureType: "poi.sports_complex",
            stylers: [{ visibility: "on" }]
          },
          { featureType: "poi.medical", stylers: [{ visibility: "on" }] },
          {
            featureType: "poi.business",
            stylers: [{ visibility: "simplified" }]
          }
        ]
      }}
    >
      <Marker label= {"1"} position={{ lat: 1.322459, lng: 103.853972 }} />
      <Marker label= {"2"} position={{ lat: 1.39227, lng: 103.752 }} />
      <Polyline
                path={pathCoordinates}
                geodesic={true}
                options={{
                    strokeColor: "#ff2527",
                    strokeOpacity: 0.75,
                    strokeWeight: 2
                }}
            />
    </GoogleMap>
  ))
);

function Maps({ ...props }) {
  return (
    <CustomSkinMap
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg"
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: `100vh` }} />}
      mapElement={<div style={{ height: `100%` }} />}
    />
  );
}

export default Maps;
</code>```

However,I have no idea how to embed textview inside this google map. I want to add a textview to let user select date then read the data from database.

答: I found the solution, just simply create a css file then set z-index as 100 and top:70px right:20px width:220px . Then the textview will display at right corner of the map. </p>

Body:
How to embed textview in react-google-maps? I have successfully created a google map page in react using react-google-maps api. This is how I insert the marker and link the marker using polyline.

import React from "react";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  Polyline
} from "react-google-maps";

const pathCoordinates = [
        { lat: 1.322459, lng: 103.853972 },
        { lat: 1.39227, lng: 103.752 }
    ];

const CustomSkinMap = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={12}
      defaultCenter={{ lat: 1.322459, lng: 103.853972 }}
      defaultOptions={{
        scrollwheel: false,
        zoomControl: true,
        styles: [
          {
            featureType: "water",
            stylers: [
              { saturation: 43 },
              { lightness: -11 },
              { hue: "#0088ff" }
            ]
          },
          {
            featureType: "road",
            elementType: "geometry.fill",
            stylers: [
              { hue: "#ff0000" },
              { saturation: -100 },
              { lightness: 99 }
            ]
          },
          {
            featureType: "road",
            elementType: "geometry.stroke",
            stylers: [{ color: "#808080" }, { lightness: 54 }]
          },
          {
            featureType: "landscape.man_made",
            elementType: "geometry.fill",
            stylers: [{ color: "#ece2d9" }]
          },
          {
            featureType: "poi.park",
            elementType: "geometry.fill",
            stylers: [{ color: "#ccdca1" }]
          },
          {
            featureType: "road",
            elementType: "labels.text.fill",
            stylers: [{ color: "#767676" }]
          },
          {
            featureType: "road",
            elementType: "labels.text.stroke",
            stylers: [{ color: "#ffffff" }]
          },
          { featureType: "poi", stylers: [{ visibility: "off" }] },
          {
            featureType: "landscape.natural",
            elementType: "geometry.fill",
            stylers: [{ visibility: "on" }, { color: "#b8cb93" }]
          },
          { featureType: "poi.park", stylers: [{ visibility: "on" }] },
          {
            featureType: "poi.sports_complex",
            stylers: [{ visibility: "on" }]
          },
          { featureType: "poi.medical", stylers: [{ visibility: "on" }] },
          {
            featureType: "poi.business",
            stylers: [{ visibility: "simplified" }]
          }
        ]
      }}
    >
      <Marker label= {"1"} position={{ lat: 1.322459, lng: 103.853972 }} />
      <Marker label= {"2"} position={{ lat: 1.39227, lng: 103.752 }} />
      <Polyline
                path={pathCoordinates}
                geodesic={true}
                options={{
                    strokeColor: "#ff2527",
                    strokeOpacity: 0.75,
                    strokeWeight: 2
                }}
            />
    </GoogleMap>
  ))
);

function Maps({ ...props }) {
  return (
    <CustomSkinMap
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg"
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: `100vh` }} />}
      mapElement={<div style={{ height: `100%` }} />}
    />
  );
}

export default Maps;

However,I have no idea how to embed textview inside this google map. I want to add a textview to let user select date then read the data from database.


问:
How can I default to IE for testing my ASP.NET application?
Three fine browsers I have installed: the inimitable Mozilla, the traditional Internet Explorer, and the hot new Chrome. I love them all dearly, but when testing my ASP.NET application, I would prefer to do so using IE.

Please note, I've not deployed this application. I'm merely launching it from the Visual Studio project in which it was conceived. Would someone here be so good as to suggest a way in which I might specify the browser it launches in? Thank you.

答:
Click and ASPX file in your solution explorer

Go > File > Browse with.. > Select IE then set it as your defautl browser.

Run your project.


问:
Building complex WHERE queries in Eloquent
I have been having troubles with this for a while, and I can not figure it out (even I know it might be straightforward). I am taking my first steps in Laravel, and I want to build a query like this using Eloquent.

// This should be condition one
WHERE status NOT IN (4,99)
```

<p>OR</p>

<pre class="lang-sql prettyprint-override"><code>// condition two
status NOT IN (4,99) AND ('column1' LIKE %XXXX% OR 'column2' LIKE %XXXX%)
</code>```

I am doing this:

$q->whereNotIn('order_stage_id', [99, 4])
->orWhere(function ($query) {
    $query->whereNotIn('order_stage_id', [99, 4])
        ->orWhere('reference_number', 'like', '%'.$request->key.'%')
        ->orWhere('seller_remark', 'like', '%'.$request->key.'%')
        ->orWhere('companies.name', 'like', '%'.$request->key.'%')
        ->orWhere('users.name', 'like', '%'.$request->key.'%');
});
```

答:
Based on your eloquent code, your current query would look something like this:

WHERE order_stage_id NOT IN (4,99) OR ( WHERE order_stage_id NOT IN (4,99) OR reference_number LIKE %XXXX% OR ...)

You need to use a where() method to get the SQL AND operator, then use a closure to nest the orWhere() methods.

```<code>$q->whereNotIn('order_stage_id',[99,4])
    ->orWhere(function($query) {

    $query->whereNotIn('order_stage_id',[99,4])
        ->where(function($query) {

        $query->where('column_1', 'like', '%XXX%')
            ->orWhere('column_2', 'like', '%XXX%')
            ->orWhere('column_2', 'like', '%XXX%');
    });
});
</code>```

Don't forget you will need to pass the $request object to each closure to be able to access it:

->where(function($query) use ($request) {

Body:
I have been having troubles with this for a while, and I can not figure it out (even I know it might be straightforward). I am taking my first steps in Laravel, and I want to build a query like this using Eloquent.

// This should be condition one
WHERE status NOT IN (4,99)

OR

// condition two
status NOT IN (4,99) AND ('column1' LIKE %XXXX% OR 'column2' LIKE %XXXX%)

I am doing this:

$q->whereNotIn('order_stage_id', [99, 4])
->orWhere(function ($query) {
    $query->whereNotIn('order_stage_id', [99, 4])
        ->orWhere('reference_number', 'like', '%'.$request->key.'%')
        ->orWhere('seller_remark', 'like', '%'.$request->key.'%')
        ->orWhere('companies.name', 'like', '%'.$request->key.'%')
        ->orWhere('users.name', 'like', '%'.$request->key.'%');
});

Body:
Based on your eloquent code, your current query would look something like this:

WHERE order_stage_id NOT IN (4,99) OR ( WHERE order_stage_id NOT IN (4,99) OR reference_number LIKE %XXXX% OR ...)

You need to use a where() method to get the SQL AND operator, then use a closure to nest the orWhere() methods.

$q->whereNotIn('order_stage_id',[99,4])
    ->orWhere(function($query) {

    $query->whereNotIn('order_stage_id',[99,4])
        ->where(function($query) {

        $query->where('column_1', 'like', '%XXX%')
            ->orWhere('column_2', 'like', '%XXX%')
            ->orWhere('column_2', 'like', '%XXX%');
    });
});

Don't forget you will need to pass the $request object to each closure to be able to access it:

->where(function($query) use ($request) {


问:
Receive TypeError when trying to upload an image to Cloudinary
I have been trying to upload an image straight from my form to cloudinary.
Whenever I try to upload an image, I receive the following error message:

```<code>/mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67
    var stream = _this.cloudinary.v2.uploader.upload_stream(params, cb);
                                         ^
    TypeError: Cannot read property 'uploader' of undefined
    at /mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67:42
    at end (/mnt/c/NodeApps/uploadFile/node_modules/run-parallel/index.js:18:15)
    at process._tickCallback (internal/process/next_tick.js:61:11)
</code>```

My form:

<form action='upload' method="POST" enctype="multipart/form-data">
    <input type='text' name='caption' placeholder="Name the image">
    <input type="file" name="new_image">
    <button type='submit'>Submit</button>
</form>
```

<p>From app.js</p>

```var multer                  = require('multer');
var cloudinary              = require('cloudinary').v2;
var cloudinaryStorage       = require('multer-storage-cloudinary');
var bodyParser              = require('body-parser');

var app = express();

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
```

<p>The Cloudinary config:</p>

```cloudinary.config({
    cloud_name: process.env.cloud_name,
    api_key: process.env.API_KEY,
    api_secret: process.env.API_SECRET
});

var storage = cloudinaryStorage({
    cloudinary: cloudinary,
    folder: "demo",
    allowedFormats: ['jpg', 'png'],
});
var parser = multer({ storage: storage });
```

<p>My Post route:</p>

```app.post('/upload', parser.single('new_image'), (req, res) => {
    cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
        if (err) { console.log('Error: ' + err); }
        image.url = result.secure_url;
        console.log(image.url);
    });
});
```

I am totally stumped trying to resolve this error, any advice on where I am going wrong will be greatly appreciated.

答:
I think you overlooked a small mistake - you already traversed into the v2 object of the SDK when you require it here:

```<code>var cloudinary = require('cloudinary').v2;
</code>```

So, in this code:

```<code>cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
    ...
}
</code>```

You are actually calling cloudinary.v2.v2.uploader instead of cloudinary.v2.uploader. Thus the error that it can't call the uploader method on undefined, since cloudinary.v2.v2 is undefined. Either remove the .v2 in your require line or from where you call uploader.

A separate issue is that it looks like you are going to be double-uploading images, based on your code. Since you have configured multer to use Cloudinary as the storage destination, having it as the middleware should mean that it uploads to Cloudinary by itself, so when you are calling .uploader.upload(), that would actually be a second upload. I believe this would be more correct code:

```<code>app.post('/upload', parser.single('new_image'), (req, res) => {
    // Since multer is the middleware & set to single, req.file should be an object with the results from cloudinary
    let image = {};
    image.url = req.file.secure_url;
    console.log(image.url);
});
</code>```

Some references I found helpful:

multer-storage-cloudinary readme

sample code on dev.to

Body:
I have been trying to upload an image straight from my form to cloudinary.
Whenever I try to upload an image, I receive the following error message:

/mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67
    var stream = _this.cloudinary.v2.uploader.upload_stream(params, cb);
                                         ^
    TypeError: Cannot read property 'uploader' of undefined
    at /mnt/c/NodeApps/uploadFile/node_modules/multer-storage-cloudinary/lib/index.js:67:42
    at end (/mnt/c/NodeApps/uploadFile/node_modules/run-parallel/index.js:18:15)
    at process._tickCallback (internal/process/next_tick.js:61:11)

My form:

<form action='upload' method="POST" enctype="multipart/form-data">
    <input type='text' name='caption' placeholder="Name the image">
    <input type="file" name="new_image">
    <button type='submit'>Submit</button>
</form>

From app.js

var multer                  = require('multer');
var cloudinary              = require('cloudinary').v2;
var cloudinaryStorage       = require('multer-storage-cloudinary');
var bodyParser              = require('body-parser');

var app = express();

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));

The Cloudinary config:

cloudinary.config({
    cloud_name: process.env.cloud_name,
    api_key: process.env.API_KEY,
    api_secret: process.env.API_SECRET
});

var storage = cloudinaryStorage({
    cloudinary: cloudinary,
    folder: "demo",
    allowedFormats: ['jpg', 'png'],
});
var parser = multer({ storage: storage });

My Post route:

app.post('/upload', parser.single('new_image'), (req, res) => {
    cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
        if (err) { console.log('Error: ' + err); }
        image.url = result.secure_url;
        console.log(image.url);
    });
});

I am totally stumped trying to resolve this error, any advice on where I am going wrong will be greatly appreciated.

Body:
I think you overlooked a small mistake - you already traversed into the v2 object of the SDK when you require it here:

var cloudinary = require('cloudinary').v2;

So, in this code:

cloudinary.v2.uploader.upload(req.file.path, (err, result) => {
    ...
}

You are actually calling cloudinary.v2.v2.uploader instead of cloudinary.v2.uploader. Thus the error that it can't call the uploader method on undefined, since cloudinary.v2.v2 is undefined. Either remove the .v2 in your require line or from where you call uploader.

A separate issue is that it looks like you are going to be double-uploading images, based on your code. Since you have configured multer to use Cloudinary as the storage destination, having it as the middleware should mean that it uploads to Cloudinary by itself, so when you are calling .uploader.upload(), that would actually be a second upload. I believe this would be more correct code:

app.post('/upload', parser.single('new_image'), (req, res) => {
    // Since multer is the middleware & set to single, req.file should be an object with the results from cloudinary
    let image = {};
    image.url = req.file.secure_url;
    console.log(image.url);
});

Some references I found helpful:

multer-storage-cloudinary readme

sample code on dev.to


问:
How to use “Windows.Networking.NetworkOperators” to get Esim Class object
There is an ESim class in Windows.Networking.NetworkOperators in Windows UWP API, I need to get the ESim object, but I don't know how to get it. Microsoft has not given an example.

ESim api description:
https://learn.microsoft.com/zh-cn/uwp/api/windows.networking.networkoperators.esim

答:
This is a restricted API, that is only available to network operators. It's stated so in the documentation:

This functionality is available only to mobile operator apps and UWP
  apps given privileged access by mobile network operators.

If you want to use this API and publish your app to the Microsoft
  Store, then you'll need to request special approval to use the custom
  capability Microsoft.eSIMManagement_8wekyb3d8bbwe. For more info, see
  Custom capabilities.

If you do have access to the privileged API space, you should use the GetProfiles() call to get the profile information.


问:
Firebase cloud function not running?
I have written the bellow code to detect when a comment has been added to the DB and then to respond by updating a timeline node the issue is that it does not actually update. Why is it not working?

```<code>    export const onCommentAdded = functions.database
.ref('/Comments/{receiverUID}/{postID}/{mediaNum}/{commentID}')
.onCreate((snapshot, context) => {
  const uid = context.params.uid
  const newCommentUID = snapshot.child("UID").val()
  console.log(newCommentUID, " the comment")
  return addNewCommentNotif(uid, newCommentUID)
})

function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
  return Promise.resolve();
}
</code>```

答:
ToraCode got it right in his comment when he said:

I think it because of your const uid = context.params.uid. I don't see any param name uid in your ref

Title: Firebase cloud function not running?

Body:
I have written the bellow code to detect when a comment has been added to the DB and then to respond by updating a timeline node the issue is that it does not actually update. Why is it not working?

    export const onCommentAdded = functions.database
.ref('/Comments/{receiverUID}/{postID}/{mediaNum}/{commentID}')
.onCreate((snapshot, context) => {
  const uid = context.params.uid
  const newCommentUID = snapshot.child("UID").val()
  console.log(newCommentUID, " the comment")
  return addNewCommentNotif(uid, newCommentUID)
})

function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
  return Promise.resolve();
}


问:
Sorted Lists not working properly in python
I'm sorting a csv file with 14 titles and 500,000 records in it. I organized them using the enumerate function. However, when I use the sorted() function to sort them using a key value (ex:total profit), it only returns numbers under 100,000 (ie. 99,992.36, when in reality some values go into the millions). </p>

<p>When I switch to a different key value (ex:total cost), I run into the same issue, however if that specific record happened to have a total profit over 100,000, that value does show. So I think I've narrowed it down to my sorted() function. </p>

```<code>def processStats(originalList, header):

    #sorting in descending order
    sortedListByTotalProfit = sorted(originalList, key = operator.itemgetter(11), reverse = True)

    max_item = sortedListByTotalProfit[0]
    print(max_intem)

def main():
    fileName = 'Records.csv'
    records = []
    recordHeader = []

    with open(fileName) as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            if i == 0: #first line is the header, store it in the list by splitting the first record by comma
                recordHeader=line.split(',')
                continue
            records.append(line.split(",")) #takes each record in the file and stores elements separated by commas as elements of a list

    processStats(records, recordHeader)
</code>```

答:
I guess the data type is string.
You can use

records.append(list(map(int, line.split(",")))) to replace records.append(line.split(","))

all code:

def processStats(originalList, header):

    #sorting in descending order
    sortedListByTotalProfit = sorted(originalList, key = operator.itemgetter(11), reverse = True)

    max_item = sortedListByTotalProfit[0]
    print(max_intem)

def main():
    fileName = 'Records.csv'
    records = []
    recordHeader = []

    with open(fileName) as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            if i == 0: #first line is the header, store it in the list by splitting the first record by comma
                recordHeader=line.split(',')
                continue
            records.append(records.append(list(map(int, line.split(","))))) #takes each record in the file and stores elements separated by commas as elements of a list

    processStats(records, recordHeader)
```

Body:
I'm sorting a csv file with 14 titles and 500,000 records in it. I organized them using the enumerate function. However, when I use the sorted() function to sort them using a key value (ex:total profit), it only returns numbers under 100,000 (ie. 99,992.36, when in reality some values go into the millions).

When I switch to a different key value (ex:total cost), I run into the same issue, however if that specific record happened to have a total profit over 100,000, that value does show. So I think I've narrowed it down to my sorted() function.

def processStats(originalList, header):

    #sorting in descending order
    sortedListByTotalProfit = sorted(originalList, key = operator.itemgetter(11), reverse = True)

    max_item = sortedListByTotalProfit[0]
    print(max_intem)

def main():
    fileName = 'Records.csv'
    records = []
    recordHeader = []

    with open(fileName) as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            if i == 0: #first line is the header, store it in the list by splitting the first record by comma
                recordHeader=line.split(',')
                continue
            records.append(line.split(",")) #takes each record in the file and stores elements separated by commas as elements of a list

    processStats(records, recordHeader)


问:
Send HTTP request to server hosted on AWS EC2 instance
I'm trying to send an HTTP POST request from the client to a server hosted on my AWS EC2 instance. I get this error when I try to set up the server on AWS.

```<code>Traceback (most recent call last):
  File "testReceive_AWS.py", line 197, in <module>
    httpd = server_class((server_address), MyHandler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
</code>```

Here's my code:

```<code>if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler

    server_address = ('EC2 instance public ip address', 9000)

    httpd = server_class((server_address), MyHandler)

    print time.asctime(), "Server Starts - %s:%s" % (server_address)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (server_address)
</code>```

I've confirmed that the IP address is correct. What am I doing wrong?

答:
You can only bind to the private IP address of an EC2 instance.  The IP stack on an EC2 instance is unaware of the public IP, because that address is automatically and transparently translated to/from the instance's private IP address by the VPC Internet Gateway.

Bind to the private address or whatever this library accepts as "any/all IPv4".  Typically this is 0.0.0.0, sometimes *, but in this case, BaseHTTPServer expects an empty string.

```<code>server_address = ('', 9000)
</code>```

Body:
I'm trying to send an HTTP POST request from the client to a server hosted on my AWS EC2 instance. I get this error when I try to set up the server on AWS.

Traceback (most recent call last):
  File "testReceive_AWS.py", line 197, in <module>
    httpd = server_class((server_address), MyHandler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address

Here's my code:

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler

    server_address = ('EC2 instance public ip address', 9000)

    httpd = server_class((server_address), MyHandler)

    print time.asctime(), "Server Starts - %s:%s" % (server_address)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (server_address)

I've confirmed that the IP address is correct. What am I doing wrong?

Body:
You can only bind to the private IP address of an EC2 instance.  The IP stack on an EC2 instance is unaware of the public IP, because that address is automatically and transparently translated to/from the instance's private IP address by the VPC Internet Gateway.

Bind to the private address or whatever this library accepts as "any/all IPv4".  Typically this is 0.0.0.0, sometimes *, but in this case, BaseHTTPServer expects an empty string.

server_address = ('', 9000)


问:
Troubleshooting connections stuck in CLOSE_WAIT status
I have a Java application running in WebLogic 11g on Windows, which after several days, becomes unresponsive. One suspicious symptom I've noticed is that a large number of connections (about 3000) show up in netstat with a CLOSE_WAIT status even when the server is idle. Since the application server is managing the client connections, I'm not sure what's causing this. We also make a number of web service calls that loopback to the same server, but I believe those connections get closed properly. What else could cause this and how does one troubleshoot a problem like this?

答:
I found this quote about CLOSE_WAIT pileups: "Something is either preventing progress to
occur in the HTTP session (we are stuck so never end up calling close), or some bug has been introduced that prevents the socket from being closed. There are a number of ways this can happen."

Think: Is there any way your application might be getting stuck while processing a request? Or WebLogic itself?

Examine: Can you do Java thread dumps (kill -SIGQUIT can be used for that on the Oracle JVM for Linux) to try to see if in fact any of your threads ARE getting stuck?

Examine the client side: First, find out the IP address or hostname of the clients that are connected to the CLOSE_WAIT sockets. Then, see if anything suspicious is happening on those clients.


问:
How to combine two arrays of integers and return average?
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

```<code>public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }
</code>```

UnitTest:

```<code>[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }
</code>```

答:
Without Linq. Just calculate the sum and divide with the length of the combined array.</p>

```<code>public double WeekendAverage(int[] saturday, int[] sunday)
{
    double sum = 0;
    for (int i = 0; i < saturday.Length; i++)
    {
        sum += saturday[i];
    }
    for (int i = 0; i < sunday.Length; i++)
    {
        sum += sunday[i];
    }
    return sum / (saturday.Length + sunday.Length);
}
</code>```

Body:
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }

UnitTest:

[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }

Body:
Without Linq. Just calculate the sum and divide with the length of the combined array.

public double WeekendAverage(int[] saturday, int[] sunday)
{
    double sum = 0;
    for (int i = 0; i < saturday.Length; i++)
    {
        sum += saturday[i];
    }
    for (int i = 0; i < sunday.Length; i++)
    {
        sum += sunday[i];
    }
    return sum / (saturday.Length + sunday.Length);
}


问:
Get a picture - Python-pptx
I am trying to read a .pptx file using python-pptx. I managed to get all the content except the image from the presentation. Below is the code i used to identify images other than textframes in the presentation. After identifying i am getting the auto_shape_type as RECTANGLE (1) but nothing about the image.

```<code>from pptx import Presentation
from pptx.shapes.picture import Picture

def read_ppt(file):
    prs = Presentation(file)
    for slide_no, slide in enumerate(prs.slides):
        for shape in slide.shapes:
            if not shape.has_text_frame:
                print(shape.auto_shape_type)
</code>```

Any help on understanding this problem appreciated. Alternative options are also welcome.

答:
try querying the shape.shape_type. by default, the auto_shape_type returns rectangle as you've observed, though pictures can be inserted into and masked by other shapes as well.

Note the default value for a newly-inserted picture is MSO_AUTO_SHAPE_TYPE.RECTANGLE, which performs no cropping because the extents of the rectangle exactly correspond to the extents of the picture.

the shape_type should return:

Unique integer identifying the type of this shape, unconditionally MSO_SHAPE_TYPE.PICTURE in this case.

You can extract the image content to a file by using its blob property and writing out the binary:

```<code>from pptx import Presentation
pres = Presentation('ppt_image.pptx')
slide = pres.slides[0]
shape = slide.shapes[0]
image = shape.image
blob = image.blob
ext = image.ext
with open(f'image.{ext}', 'wb') as file:
    file.write(blob)
</code>```

Title: Get a picture - Python-pptx

Body:
I am trying to read a .pptx file using python-pptx. I managed to get all the content except the image from the presentation. Below is the code i used to identify images other than textframes in the presentation. After identifying i am getting the auto_shape_type as RECTANGLE (1) but nothing about the image.

from pptx import Presentation
from pptx.shapes.picture import Picture

def read_ppt(file):
    prs = Presentation(file)
    for slide_no, slide in enumerate(prs.slides):
        for shape in slide.shapes:
            if not shape.has_text_frame:
                print(shape.auto_shape_type)

Any help on understanding this problem appreciated. Alternative options are also welcome.

Body:
try querying the shape.shape_type. by default, the auto_shape_type returns rectangle as you've observed, though pictures can be inserted into and masked by other shapes as well.

Note the default value for a newly-inserted picture is MSO_AUTO_SHAPE_TYPE.RECTANGLE, which performs no cropping because the extents of the rectangle exactly correspond to the extents of the picture.

the shape_type should return:

Unique integer identifying the type of this shape, unconditionally MSO_SHAPE_TYPE.PICTURE in this case.

You can extract the image content to a file by using its blob property and writing out the binary:

from pptx import Presentation
pres = Presentation('ppt_image.pptx')
slide = pres.slides[0]
shape = slide.shapes[0]
image = shape.image
blob = image.blob
ext = image.ext
with open(f'image.{ext}', 'wb') as file:
    file.write(blob)


问:
How to create the table in python for reading the 2D array in column wise
i have written code for continues update of data from .csv file ..in this code i have 31 column and 6 rows ..here 1)i dont no how to  converte into 2D form and after converting into 2D i want to read my data in column wise in table(how to create table in python for storing the element one after the other column wise )..Can anyone tell me how to read the row[1]column[1] data?..please can anyone help me to solve this problem..

```<code>def animate(i):
     filename = "tst.csv"
     fields = []
     rows = []
     Nrow = 0
     Ncol = 0
     cnt_row = 0
     cnt_col = 0

     with open(filename, 'r') as csvfile:
          csvreader = csv.reader(csvfile,delimiter = ",")
          data = list(csvreader)
          Nrow = len(data)
          for row in range(len(data)):
               for col in range(len(data[row])):
                    Ncol = data[row][col].split('.')
                    print(Ncol)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

   Column1  Column2
0     4        8
1     6        9
</code>```

i am expecting the result like this So that i can read my data in column wise

答:
I sugest you to use pandas to interact with tables (csv, excel, etc.)
All your code above could be done in a few lines with pandas:

import pandas as pd

table = pd.read_csv('tst.csv')

# you can access data easly this way:
table['Columns1'][0]

# Or convert it to array:
table.values[0,0]

# and can easly add data and overwrite the old data:
table.append({'Column1':5,
           'Column1':9}, ignore_index=True)
table.to_csv('tst.csv', index=False)
```

Body:
i have written code for continues update of data from .csv file ..in this code i have 31 column and 6 rows ..here 1)i dont no how to  converte into 2D form and after converting into 2D i want to read my data in column wise in table(how to create table in python for storing the element one after the other column wise )..Can anyone tell me how to read the row[1]column[1] data?..please can anyone help me to solve this problem..

def animate(i):
     filename = "tst.csv"
     fields = []
     rows = []
     Nrow = 0
     Ncol = 0
     cnt_row = 0
     cnt_col = 0

     with open(filename, 'r') as csvfile:
          csvreader = csv.reader(csvfile,delimiter = ",")
          data = list(csvreader)
          Nrow = len(data)
          for row in range(len(data)):
               for col in range(len(data[row])):
                    Ncol = data[row][col].split('.')
                    print(Ncol)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

   Column1  Column2
0     4        8
1     6        9

i am expecting the result like this So that i can read my data in column wise


问:
Cannot read property 'data' of undefined when user successfully register
I keep getting an error everytime a user signs up successfully,

Unhandled Rejection (TypeError): Cannot read property 'data' of
  undefined

dispatch({
        type: GET_ERRORS,
              payload: err.response.data
          })

why is it executing this catch method if their is no error when a user signs up successfully ?

console.log(err.response) shows when a user is registering with the same username or email.

What could i be doing wrong ?

authActions.js

```<code>export const registerUser = (userData) => dispatch => {

    Axios
      .post('/users/register', userData)
      .then( res => {
        const token = res.data.token;
        console.log(token);
        // pass the token in session
        sessionStorage.setItem("jwtToken", token);
        // set the auth token
        setAuthToken(token);
        // decode the auth token
        const decoded = jwt_decode(token);
        // pass the decoded token
        dispatch(setCurrentUser(decoded))
        this.props.history.push("/dashboard")
      }).catch( (err) => {

         console.log(err.response)
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data
            })
    })
};
</code>```

reducer

```<code>import {SET_CURRENT_USER } from '../actions/types';
import isEmpty from '../actions/utils/isEmpty';

const initialState = {
    isAuthenticated: false
}

export default  (state = initialState, action) => {
    switch (action.type) {
        case SET_CURRENT_USER:
            return{
                ...state,
                isAuthenticated: !isEmpty(action.payload),
                user:action.payload
            }

        default:
            return state;
    }
}
</code>```

console.log(res)

```<code>{
  "data": {
    "message": "user created",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NDEsImlhdCI6MTU1OTI2ODcxNX0.t7xK5VVdOmj2BbExBmOdUrZHwYuyEJgjvUTQq1Mw5qY",
    "auth": true
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-type": "application/json; charset=utf-8",
    "content-length": "165"
  },
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    "method": "post",
    "baseURL": "http://localhost:3000",
    "withCredentials": true,
    "url": "http://localhost:3000/users/register",
    "data": "{\"username\":\"billyssss999\",\"email\":\"j0hnnnysssraddddddin@yahoo.com\",\"password\":\"janeddmdddba\"}"
  },
  "request": {}
</code>```

答:
So it seems to be working after i remove this

this.props.history.push("/dashboard")

and redirects to the dashboard already by this existing code.

Signup

```<code>....

  componentDidMount() {
        // console.log(this.props.auth);
        if (this.props.auth.isAuthenticated) {
          this.props.history.push("/dashboard");
        }

      }

    componentWillReceiveProps(nextProps) {
        if (nextProps.auth.isAuthenticated) {
          this.props.history.push("/dashboard");
        }
        if (nextProps.errors) {
          this.setState({ errors: nextProps.errors });
        }
    }

    handleChange = (e) => {
        e.preventDefault();
        const {formData} = this.state;
        this.setState({
            formData: {
                ...formData,
                [e.target.name]: e.target.value
            }
        });
    }
    handleSubmit = (e) => {
        e.preventDefault();
        const {formData} = this.state;
        const {username, email, password, passwordConf} = formData;
        this.setState({
            username: this.state.username,
            password: this.state.password,
            passwordConf: this.state.passwordConf,
            email: this.state.email
        });
        const creds = {
            username,
            email,
            password
        }

        console.log(creds);
        if (password === passwordConf) {
            this.props.registerUser(creds, this.props.history);
        } else {
            this.setState({passErr: "Passwords Don't Match"})
        }
    }
</code>```

Body:
I keep getting an error everytime a user signs up successfully,

Unhandled Rejection (TypeError): Cannot read property 'data' of
  undefined

dispatch({
        type: GET_ERRORS,
              payload: err.response.data
          })

why is it executing this catch method if their is no error when a user signs up successfully ?

console.log(err.response) shows when a user is registering with the same username or email.

What could i be doing wrong ?

authActions.js

export const registerUser = (userData) => dispatch => {

    Axios
      .post('/users/register', userData)
      .then( res => {
        const token = res.data.token;
        console.log(token);
        // pass the token in session
        sessionStorage.setItem("jwtToken", token);
        // set the auth token
        setAuthToken(token);
        // decode the auth token
        const decoded = jwt_decode(token);
        // pass the decoded token
        dispatch(setCurrentUser(decoded))
        this.props.history.push("/dashboard")
      }).catch( (err) => {

         console.log(err.response)
            dispatch({
                type: GET_ERRORS,
                payload: err.response.data
            })
    })
};

reducer

import {SET_CURRENT_USER } from '../actions/types';
import isEmpty from '../actions/utils/isEmpty';

const initialState = {
    isAuthenticated: false
}

export default  (state = initialState, action) => {
    switch (action.type) {
        case SET_CURRENT_USER:
            return{
                ...state,
                isAuthenticated: !isEmpty(action.payload),
                user:action.payload
            }

        default:
            return state;
    }
}

console.log(res)

{
  "data": {
    "message": "user created",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NDEsImlhdCI6MTU1OTI2ODcxNX0.t7xK5VVdOmj2BbExBmOdUrZHwYuyEJgjvUTQq1Mw5qY",
    "auth": true
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-type": "application/json; charset=utf-8",
    "content-length": "165"
  },
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    "method": "post",
    "baseURL": "http://localhost:3000",
    "withCredentials": true,
    "url": "http://localhost:3000/users/register",
    "data": "{\"username\":\"billyssss999\",\"email\":\"j0hnnnysssraddddddin@yahoo.com\",\"password\":\"janeddmdddba\"}"
  },
  "request": {}

Body:
So it seems to be working after i remove this

this.props.history.push("/dashboard")

and redirects to the dashboard already by this existing code.

Signup

....

  componentDidMount() {
        // console.log(this.props.auth);
        if (this.props.auth.isAuthenticated) {
          this.props.history.push("/dashboard");
        }

      }

    componentWillReceiveProps(nextProps) {
        if (nextProps.auth.isAuthenticated) {
          this.props.history.push("/dashboard");
        }
        if (nextProps.errors) {
          this.setState({ errors: nextProps.errors });
        }
    }

    handleChange = (e) => {
        e.preventDefault();
        const {formData} = this.state;
        this.setState({
            formData: {
                ...formData,
                [e.target.name]: e.target.value
            }
        });
    }
    handleSubmit = (e) => {
        e.preventDefault();
        const {formData} = this.state;
        const {username, email, password, passwordConf} = formData;
        this.setState({
            username: this.state.username,
            password: this.state.password,
            passwordConf: this.state.passwordConf,
            email: this.state.email
        });
        const creds = {
            username,
            email,
            password
        }

        console.log(creds);
        if (password === passwordConf) {
            this.props.registerUser(creds, this.props.history);
        } else {
            this.setState({passErr: "Passwords Don't Match"})
        }
    }


问:
Flutter: Widget State: Is this code safe?
The code below is an example to illustrate this question. The code below works, however the following line:

```<code>class WidgetCustom extends StatefulWidget {
</code>```

has "WidgetCustom" underlined in green in vsCode, and when the cursor is positioned over it, it shows the message:
"This class (or a class this class inherits from) is marked as @immutable, but one or more of its instance fields are not final".

The code works fine.

Is it safe to use this code?

Is there a way to achieve this without the warning?

```<code>import 'package:flutter/material.dart';

class WidgetCustom extends StatefulWidget {

  _WidgetCustomState _state;

  WidgetCustom({@required int iCount}) {
    _state = _WidgetCustomState(iCount);
  }

  @override
  State<StatefulWidget> createState() {
    return _state;
  }

  int get getIcount => _state.iCount;
}

class _WidgetCustomState extends State<WidgetCustom> {
  int iCount;

  _WidgetCustomState(this.iCount);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: <Widget>[
      Column(
        children: <Widget>[
          RaisedButton(
              child: const Text("Please tap me"),
              onPressed: () {
                setState(() => iCount = iCount + 1);
              }),
          SizedBox(height: 40),
          Text("Tapped $iCount Times")
        ],
      ),
    ]));
  }
}
</code>```

Edited to add main.dart

```<code>import 'package:flutter/material.dart';
import 'widgetCustom.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: 99);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        _widgetCustom,
        SizedBox(height: 40),
        Text(_sMessage),
      ]),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage =
        "Value from last button click = ${_widgetCustom.getIcount}");
  }
}

</code>```

答: Pass the initial value to the constructor when creating the widget as a final value, and then get it from the State class.</p>

Body:
The code below is an example to illustrate this question. The code below works, however the following line:

class WidgetCustom extends StatefulWidget {

has "WidgetCustom" underlined in green in vsCode, and when the cursor is positioned over it, it shows the message:
"This class (or a class this class inherits from) is marked as @immutable, but one or more of its instance fields are not final".

The code works fine.

Is it safe to use this code?

Is there a way to achieve this without the warning?

import 'package:flutter/material.dart';

class WidgetCustom extends StatefulWidget {

  _WidgetCustomState _state;

  WidgetCustom({@required int iCount}) {
    _state = _WidgetCustomState(iCount);
  }

  @override
  State<StatefulWidget> createState() {
    return _state;
  }

  int get getIcount => _state.iCount;
}

class _WidgetCustomState extends State<WidgetCustom> {
  int iCount;

  _WidgetCustomState(this.iCount);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: <Widget>[
      Column(
        children: <Widget>[
          RaisedButton(
              child: const Text("Please tap me"),
              onPressed: () {
                setState(() => iCount = iCount + 1);
              }),
          SizedBox(height: 40),
          Text("Tapped $iCount Times")
        ],
      ),
    ]));
  }
}

Edited to add main.dart

import 'package:flutter/material.dart';
import 'widgetCustom.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: 99);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        _widgetCustom,
        SizedBox(height: 40),
        Text(_sMessage),
      ]),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage =
        "Value from last button click = ${_widgetCustom.getIcount}");
  }
}


问:
package sun.awt does not exist
When compiling with ant, calls to sun.awt.AppContext work, however the same code compiled with IntelliJ fails using AdoptOpenJDK11.

sun.awt.AppContext with Oracle JDK8 works with IntelliJ

sun.awt.AppContext with AdoptOpenJDK11 does NOT work with IntelliJ

Although Sun/Oracle has warned for a while about avoiding the sun.* packages, there are certain features (bugs?) in Java that still require them and stranger, the command line seems happy.

Sample code:

```<code>package test;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import sun.awt.AppContext;

public class Main {

    public static void main(String[] args) {
        //Update printer list in CUPS immediately
        AppContext.getAppContext().put(PrintServiceLookup.class.getDeclaredClasses()[0], null);

        PrintService[] printers = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService p : printers) {
            System.out.println(p.getName());
        }
    }
}
</code>```

How does one configure IntelliJ to behave like ant and allow access to sun.awt.* packages?

答:
Disable the Use '--release' option...:

See this answer for details.

Title: package sun.awt does not exist

Body:
When compiling with ant, calls to sun.awt.AppContext work, however the same code compiled with IntelliJ fails using AdoptOpenJDK11.

sun.awt.AppContext with Oracle JDK8 works with IntelliJ

sun.awt.AppContext with AdoptOpenJDK11 does NOT work with IntelliJ

Although Sun/Oracle has warned for a while about avoiding the sun.* packages, there are certain features (bugs?) in Java that still require them and stranger, the command line seems happy.

Sample code:

package test;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import sun.awt.AppContext;

public class Main {

    public static void main(String[] args) {
        //Update printer list in CUPS immediately
        AppContext.getAppContext().put(PrintServiceLookup.class.getDeclaredClasses()[0], null);

        PrintService[] printers = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService p : printers) {
            System.out.println(p.getName());
        }
    }
}

How does one configure IntelliJ to behave like ant and allow access to sun.awt.* packages?


问:
Deploying 32 or 64bit ELMAH with website depending on server
I am currently building an ASP MVC 2 site and I am looking at hooking ELMAH in for my error logging however I'm not sure how to handle the different build environments.

Both my development machine and current test server are 32-Bit and the production server is 64-bit. I can set the MVC site to deploy in x86 and x64 without any problems but is there any way I can get it to use the 32bit and 64bit ELMAH binaries on their respective servers without needing to change the referenced DLL between builds?

答:
I had the same problem, and not using SQLite was not enough to make it work. I tried removing all configuration for SQLite.

I noticed that the SQLite dll was published with my project, so i removed it from the folder containing the Elmah dll. Now my application works in both 32-bit and 64-bit.

ContentLicense: CC BY-SA 2.5


问:
How to access Sharepoint REST api in ajax call
I'm new to working with sharepoint. When i tried to call share point API url from ajax call in JavaScript. But, it's continuously failing and throws the error. I can say, that is CORS error. So, i've made changes in web.config like below.

```<code><add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,Accept,X- FORMS_BASED_AUTH_ACCEPTED,crossDomain,credentials " />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</code>```

and ajax call as below

```<code> $.ajax({
            url: url,
            headers: {
                Accept: "application/json;odata=verbose"
            },
            xhrFields: { withCredentials: true },
            async: false,
            success: function (data) {
                var items = data.d;
                console.log("Login Name: " + items.LoginName);
                console.log("Email: " + items.Email);
                console.log("ID: " + items.Id);
                console.log("Title: " + items.Title);
            },
            error: function (jqxr, errorCode, errorThrown) {
                console.log(jqxr.responseText);
            }
        });
</code>```

Please help me regarding this. I'm trying since 2 days.

Update:

This error I'm getting.

Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

答:
Use the PowerShell script below to add the web.config modifications:

```<code>Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

$localFarm = Get-SPFarm

$webapp = Get-SPWebApplication "http://sp:12001"

# Remove old web.config modifications of MyAuthenticationProvider
$oldMods = @();
$webapp.WebConfigModifications | ? { $_.Owner -eq "CrossSiteScripting" } | % {
    $oldMods = $oldMods + $_
}

$oldMods | % {
    $webapp.WebConfigModifications.Remove($_)
}

# update the Web Application and apply all existing web.config modifications - this executes the "remove" actions from above
$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
    Write-Host "." -NoNewline
    Start-Sleep 1
}

# New web.config modifications for MyAuthenticationProvider
$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Origin'][@value='http://localhost:31699']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
#0 = for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Origin' value='http://localhost:31699' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Method'][@value='GET,POST,HEAD,OPTIONS']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Method' value='GET,POST,HEAD,OPTIONS' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Headers'][@value='Content-Type,Authorization']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Headers' value='Content-Type,Authorization' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Credentials'][@value='true']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Credentials' value='true' />"
$webapp.WebConfigModifications.Add($myModification1)

$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
    Write-Host "." -NoNewline
    Start-Sleep 1
}
</code>```

Then use the REST API in jQuery Ajax like below.

```<code>$.support.cors = true;
$.ajax({
    url: url,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    headers: { "Accept": "application/json; odata=verbose" },
    xhrFields: { withCredentials: true },
    async: false,
    success: function (data) {
        var items = data.d;
        console.log("Login Name: " + items.LoginName);
        console.log("Email: " + items.Email);
        console.log("ID: " + items.Id);
        console.log("Title: " + items.Title);
    },
    error: function (jqxr, errorCode, errorThrown) {
        console.log(jqxr.responseText);
    }
});
</code>```

Reference: Cross Site Scripting with SharePoint 2013 REST calls

Body:
I'm new to working with sharepoint. When i tried to call share point API url from ajax call in JavaScript. But, it's continuously failing and throws the error. I can say, that is CORS error. So, i've made changes in web.config like below.

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,Accept,X- FORMS_BASED_AUTH_ACCEPTED,crossDomain,credentials " />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />

and ajax call as below

 $.ajax({
            url: url,
            headers: {
                Accept: "application/json;odata=verbose"
            },
            xhrFields: { withCredentials: true },
            async: false,
            success: function (data) {
                var items = data.d;
                console.log("Login Name: " + items.LoginName);
                console.log("Email: " + items.Email);
                console.log("ID: " + items.Id);
                console.log("Title: " + items.Title);
            },
            error: function (jqxr, errorCode, errorThrown) {
                console.log(jqxr.responseText);
            }
        });

Please help me regarding this. I'm trying since 2 days.

Update:

This error I'm getting.

Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

Body:
Use the PowerShell script below to add the web.config modifications:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

$localFarm = Get-SPFarm

$webapp = Get-SPWebApplication "http://sp:12001"

# Remove old web.config modifications of MyAuthenticationProvider
$oldMods = @();
$webapp.WebConfigModifications | ? { $_.Owner -eq "CrossSiteScripting" } | % {
    $oldMods = $oldMods + $_
}

$oldMods | % {
    $webapp.WebConfigModifications.Remove($_)
}

# update the Web Application and apply all existing web.config modifications - this executes the "remove" actions from above
$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
    Write-Host "." -NoNewline
    Start-Sleep 1
}

# New web.config modifications for MyAuthenticationProvider
$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Origin'][@value='http://localhost:31699']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
#0 = for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Origin' value='http://localhost:31699' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Method'][@value='GET,POST,HEAD,OPTIONS']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Method' value='GET,POST,HEAD,OPTIONS' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Headers'][@value='Content-Type,Authorization']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Headers' value='Content-Type,Authorization' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Credentials'][@value='true']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Credentials' value='true' />"
$webapp.WebConfigModifications.Add($myModification1)

$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
    Write-Host "." -NoNewline
    Start-Sleep 1
}

Then use the REST API in jQuery Ajax like below.

$.support.cors = true;
$.ajax({
    url: url,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    headers: { "Accept": "application/json; odata=verbose" },
    xhrFields: { withCredentials: true },
    async: false,
    success: function (data) {
        var items = data.d;
        console.log("Login Name: " + items.LoginName);
        console.log("Email: " + items.Email);
        console.log("ID: " + items.Id);
        console.log("Title: " + items.Title);
    },
    error: function (jqxr, errorCode, errorThrown) {
        console.log(jqxr.responseText);
    }
});

Reference: Cross Site Scripting with SharePoint 2013 REST calls


问:
How to implement a pythonic line continuation read
I am trying to implement a python script to read and extract lines from an ASCII text file. This seems to be a rather easy thing, however I ended up with an issue which I can't resolve myself.
The file I am trying to read contains test and some of the lines
begin with *tr999. This pattern can have either big or small letters and the number of digits and the presence of the * is optional. The asterisk can also be before and after. This signal keyword is followed by numbers, either int or folat.  To catch the signal, I use a python regexp expression

```<code>re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line)
</code>```

The text file looks like this

```<code>tr10* 1 2 3 22 1 1 13 12 33 33 33
*Tr20 12 22 -1 2  2 2 5 5 5 6 6 6 77
Tr20 1 1 1 &
           2 0 0
           1 1 1
           2 2 2
c that is a comment and below is the problem case '&' is missing
*tr22221 2 2 2
         1 1 1
         2 2 2
</code>```

The code I wrote can't catch the last case. Where the continue line signal & is missing. The use of & to continue line is optional and can be replaced by a number of white spaces at the begging of the continued  line .

The code I wrote is

```<code>import sys

fp=open(sys.argv[1],'r')
import re

# get the integers only
def loop_conv(string):
        conv=[]
        for i in string.split(" "):
            try:
                conv.append(float(i))
            except ValueError:
                pass
        return conv

# extract the information
def extract_trans_card(line,fp):
            extracted=False
            if len(line)>2 and not re.search("[cC]",line.split()[0]) and re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line) :
                extracted=True
                trans_card=[]
                trans_card.append(line.split()[0])
                line_old=line
   # this part here is because after the read signal,
   # data to be extracted might be on the same line
                for val in loop_conv(line):
                        trans_card.append(val)
# this part here fails. I am not able to catch the case '&' missing.
# i tried to peek the next line with seek() but it i got a system error.
# the idea is to loop until i have a continue line case
                while (re.search("^(\s){5,60}",line) or re.search("[&$]",line_old)) and len(trans_card) <13:

                    line=fp.readline()
                    for val in loop_conv(line):
                        trans_card.append(val)
                    line_old=line

                #print('M',trans_card)
                print('value',trans_card)
                trans_card=[]
            return extracted

# read the file with a loop
for line in fp:
        if not extract_trans_card(line,fp) :
            print(line,end='')
</code>```

The output is:

```<code>value ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
    c that is a comment and below is the problem case '&' is missing
value ['*tr22221', 2.0, 2.0, 2.0]
             1 1 1
             2 2 2
</code>```

The last line is the problem. Since the 1 1 1 and 2 2 2 get ignored and are just echoed.
This problem looks similar to how python does continue line. Either by spaces or by using &.
I hope someone will help we with this and would point the proper manner to do this problem

答:
The problem with your code workflow is when the continue line signal is optional, it will be hard to detect the last line associated with the current trans_card without messing up with the next trans_card.

Since the beginning (header) of a trans_card can be found with re.search(r"[*]?[Tt][Rr][0-9]{1,5}[*]?", it would be easier to process the previous trans_card whenever this header pattern is detected.

Below is a sample code which I roughly copied from your code logic and saved the resulting trans_card into a list of lists:

```<code>import sys
import re

# get the floats only from line, copied from your code
def loop_conv(string):
    conv=[]
    for i in string.split(" "):
      try:
        conv.append(float(i))
      except ValueError:
        pass
    return conv

# set previous trans_card with non-EMPTY vals list
def set_prev_trans_card(card, vals):
    if len(vals):
        card.append(vals)
        #print ('value: {}'.format(vals))

# below new code logic:
with open(sys.argv[1], 'r') as fp:
    trans_card = []

    # a list to save items retrieved from lines associated with the same trans_card
    values = []

    # set up a flag to identify header
    is_header = 0

    for line in fp:
        # if line is a comment, then skip it
        if re.search("[cC]",line.split()[0]):
            #print(line, end='')
            continue

        # if line is a header, append the existing values[] (from the previous trans_card)
        # list to trans_card[] and then reset values[]
        if len(line)>2 and re.search(r"[*]?[Tt][Rr][0-9]{1,5}[*]?", line):
            # append values[] to trans_card
            set_prev_trans_card(trans_card, values)

            # reset values[] to the first \S+ on the header
            values = [ line.split()[0] ]

            # set is_header flag to 1
            is_header = 1

        # if line ends with &\n, then concatenate the next lines
        while line.endswith('&\n'):
            line += ' ' + fp.readline()

        # add all numbers(floats) from header or lines starts with 5-60 white-spaces into the values[] list, and reset is_header flag to 0
        if is_header or re.search("^(\s){5,60}",line):
            values.extend(loop_conv(line))
            is_header = 0

    # append the last values[] to trans_card
    set_prev_trans_card(trans_card, values)

for v in trans_card:
    print ('value: {}'.format(v))
</code>```

output is:

```<code>value: ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value: ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value: ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
value: ['*tr22221', 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
</code>```

Note: I skipped the condition of len(trans_card) <13 in your code, thought it's just used to prevent infinite while loop. if not, it should be easy to add into the above example code.

BTW. you might want to add ^ to patterns of comment and header so that they only match the beginning of strings instead of anywhere in the searching strings.

Body:
I am trying to implement a python script to read and extract lines from an ASCII text file. This seems to be a rather easy thing, however I ended up with an issue which I can't resolve myself.
The file I am trying to read contains test and some of the lines
begin with *tr999. This pattern can have either big or small letters and the number of digits and the presence of the * is optional. The asterisk can also be before and after. This signal keyword is followed by numbers, either int or folat.  To catch the signal, I use a python regexp expression

re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line)

The text file looks like this

tr10* 1 2 3 22 1 1 13 12 33 33 33
*Tr20 12 22 -1 2  2 2 5 5 5 6 6 6 77
Tr20 1 1 1 &
           2 0 0
           1 1 1
           2 2 2
c that is a comment and below is the problem case '&' is missing
*tr22221 2 2 2
         1 1 1
         2 2 2

The code I wrote can't catch the last case. Where the continue line signal & is missing. The use of & to continue line is optional and can be replaced by a number of white spaces at the begging of the continued  line .

The code I wrote is

import sys

fp=open(sys.argv[1],'r')
import re

# get the integers only
def loop_conv(string):
        conv=[]
        for i in string.split(" "):
            try:
                conv.append(float(i))
            except ValueError:
                pass
        return conv

# extract the information
def extract_trans_card(line,fp):
            extracted=False
            if len(line)>2 and not re.search("[cC]",line.split()[0]) and re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line) :
                extracted=True
                trans_card=[]
                trans_card.append(line.split()[0])
                line_old=line
   # this part here is because after the read signal,
   # data to be extracted might be on the same line
                for val in loop_conv(line):
                        trans_card.append(val)
# this part here fails. I am not able to catch the case '&' missing.
# i tried to peek the next line with seek() but it i got a system error.
# the idea is to loop until i have a continue line case
                while (re.search("^(\s){5,60}",line) or re.search("[&$]",line_old)) and len(trans_card) <13:

                    line=fp.readline()
                    for val in loop_conv(line):
                        trans_card.append(val)
                    line_old=line

                #print('M',trans_card)
                print('value',trans_card)
                trans_card=[]
            return extracted

# read the file with a loop
for line in fp:
        if not extract_trans_card(line,fp) :
            print(line,end='')

The output is:

value ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
    c that is a comment and below is the problem case '&' is missing
value ['*tr22221', 2.0, 2.0, 2.0]
             1 1 1
             2 2 2

The last line is the problem. Since the 1 1 1 and 2 2 2 get ignored and are just echoed.
This problem looks similar to how python does continue line. Either by spaces or by using &.
I hope someone will help we with this and would point the proper manner to do this problem

Body:
The problem with your code workflow is when the continue line signal is optional, it will be hard to detect the last line associated with the current trans_card without messing up with the next trans_card.

Since the beginning (header) of a trans_card can be found with re.search(r"[*]?[Tt][Rr][0-9]{1,5}[*]?", it would be easier to process the previous trans_card whenever this header pattern is detected.

Below is a sample code which I roughly copied from your code logic and saved the resulting trans_card into a list of lists:

import sys
import re

# get the floats only from line, copied from your code
def loop_conv(string):
    conv=[]
    for i in string.split(" "):
      try:
        conv.append(float(i))
      except ValueError:
        pass
    return conv

# set previous trans_card with non-EMPTY vals list
def set_prev_trans_card(card, vals):
    if len(vals):
        card.append(vals)
        #print ('value: {}'.format(vals))

# below new code logic:
with open(sys.argv[1], 'r') as fp:
    trans_card = []

    # a list to save items retrieved from lines associated with the same trans_card
    values = []

    # set up a flag to identify header
    is_header = 0

    for line in fp:
        # if line is a comment, then skip it
        if re.search("[cC]",line.split()[0]):
            #print(line, end='')
            continue

        # if line is a header, append the existing values[] (from the previous trans_card)
        # list to trans_card[] and then reset values[]
        if len(line)>2 and re.search(r"[*]?[Tt][Rr][0-9]{1,5}[*]?", line):
            # append values[] to trans_card
            set_prev_trans_card(trans_card, values)

            # reset values[] to the first \S+ on the header
            values = [ line.split()[0] ]

            # set is_header flag to 1
            is_header = 1

        # if line ends with &\n, then concatenate the next lines
        while line.endswith('&\n'):
            line += ' ' + fp.readline()

        # add all numbers(floats) from header or lines starts with 5-60 white-spaces into the values[] list, and reset is_header flag to 0
        if is_header or re.search("^(\s){5,60}",line):
            values.extend(loop_conv(line))
            is_header = 0

    # append the last values[] to trans_card
    set_prev_trans_card(trans_card, values)

for v in trans_card:
    print ('value: {}'.format(v))

output is:

value: ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value: ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value: ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
value: ['*tr22221', 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]

Note: I skipped the condition of len(trans_card) <13 in your code, thought it's just used to prevent infinite while loop. if not, it should be easy to add into the above example code.

BTW. you might want to add ^ to patterns of comment and header so that they only match the beginning of strings instead of anywhere in the searching strings.


问:
How do I get a MongoDB import script to close the db after inserting results?
I am running a quick little nodejs script to find documents in one collection and insert them into another collection but on the same DB. I came up with this guy, but it has no way to close because I think its running open or async?

I have tried placing the db.close() in various places and tried mongoClient.close(). No luck which had me thinking about trying to force a timeout for the async call. Added a connection Time out but it did not have the desired behaviour.

```<code>var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
const async = require("async");

// Connection URL
var url = 'mongodb://localhost:27017/sourceDB';

// Use connect method to connect to the Server
MongoClient.connect(url,{connectTimeoutMS: "5"}, (err, db) => {

db.collection('source.collection', function(err, col) {
assert.equal(null, err);

col.find().forEach(function (data) {
console.log(data);

db.collection('destination.collection').insertOne(data, function(err, res) {
assert.equal(null, err);
});

console.log("Moved");

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

The script does well and picks up the collection and inserts, but the connection remains open.

答:
It is not recommended to explicitly close the connection as shown by this SO thread.

Rather, allow the client library to manage the connection for you.

Body:
I am running a quick little nodejs script to find documents in one collection and insert them into another collection but on the same DB. I came up with this guy, but it has no way to close because I think its running open or async?

I have tried placing the db.close() in various places and tried mongoClient.close(). No luck which had me thinking about trying to force a timeout for the async call. Added a connection Time out but it did not have the desired behaviour.

var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
const async = require("async");

// Connection URL
var url = 'mongodb://localhost:27017/sourceDB';

// Use connect method to connect to the Server
MongoClient.connect(url,{connectTimeoutMS: "5"}, (err, db) => {

db.collection('source.collection', function(err, col) {
assert.equal(null, err);

col.find().forEach(function (data) {
console.log(data);

db.collection('destination.collection').insertOne(data, function(err, res) {
assert.equal(null, err);
});

console.log("Moved");

});
});
});

The script does well and picks up the collection and inserts, but the connection remains open.