问:
Converting an array's type to Mongoose Model
In nodejs post route I saved mongoose model objects into an array now I want to to save that array to mongodb, in order to do this I need to invoke array.save() method which is mongoose built in method. To do this I need to convert this array to Mongoose model type that is Form in this case. Please tell how to apply this conversion, or do I need any other solution?
Mongoose schema is:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

module.exports = mongoose.model('Form', formSchema);
</code>```

NodeJS post route:

```<code>router.post('/userform', function (req, res, next) {

    var form = [];
    for (var key in req.body) {
        if (req.body.hasOwnProperty(key)) {
            var formObj = new Form({
                controlType: req.body[key].controlType,
                label: req.body[key].label,
                required: req.body[key].required,
                placeholder: req.body[key].placeholder,
                options: req.body[key].options
            });
        }
        form.push(formObj);
    }
    console.log('type of form 0528');
    console.log(typeof(form));

    form.save(function(err, result) { // here is the issue, this line is not working because form is not type of mongoose model
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api 0528',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

module.exports = router;
</code>```

答:
Model.create can take an array of objects to create multiple documents.

So you could build an array of objects rather than model instances and then pass that array to Form.create:

```<code>var formArr = []

for (var key in req.body) {

  if (req.body.hasOwnProperty(key)) {

    var formObj = {
      controlType: req.body[key].controlType,
      label: req.body[key].label,
      required: req.body[key].required,
      placeholder: req.body[key].placeholder,
      options: req.body[key].options
    }

    formArr.push(formObj)

  }

}

Form.create(formArr, function(err, results) {

  ...

})
</code>```

If you want to save an array of objects  in a single document, then try using a nested schema:

```<code>var controlSchema = new Schema({
  controlType: {type: String, required: true},
  label: {type: String, required: true},
  required: {type: Boolean},
  placeholder: {type: String},
  options: [String]
}, {collection: 'inputForm'})

var formSchema = new Schema({
  controls: [controlSchema]
})

module.exports = mongoose.model('Form', formSchema)
</code>```

...and then save the array as the controls field in a new document like this:

```<code>var controlsArr = []

for (var key in req.body) {

  if (req.body.hasOwnProperty(key)) {

    var controlObj = {
      controlType: req.body[key].controlType,
      label: req.body[key].label,
      required: req.body[key].required,
      placeholder: req.body[key].placeholder,
      options: req.body[key].options
    }

    controlsArr.push(controlObj)

  }

}

var form = new Form({
  controls: controlsArr
})

form.save(function(err, result) {

  ...

})
</code>```

Body:
In nodejs post route I saved mongoose model objects into an array now I want to to save that array to mongodb, in order to do this I need to invoke array.save() method which is mongoose built in method. To do this I need to convert this array to Mongoose model type that is Form in this case. Please tell how to apply this conversion, or do I need any other solution?
Mongoose schema is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

module.exports = mongoose.model('Form', formSchema);

NodeJS post route:

router.post('/userform', function (req, res, next) {

    var form = [];
    for (var key in req.body) {
        if (req.body.hasOwnProperty(key)) {
            var formObj = new Form({
                controlType: req.body[key].controlType,
                label: req.body[key].label,
                required: req.body[key].required,
                placeholder: req.body[key].placeholder,
                options: req.body[key].options
            });
        }
        form.push(formObj);
    }
    console.log('type of form 0528');
    console.log(typeof(form));

    form.save(function(err, result) { // here is the issue, this line is not working because form is not type of mongoose model
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api 0528',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

module.exports = router;

Body:
Model.create can take an array of objects to create multiple documents.

So you could build an array of objects rather than model instances and then pass that array to Form.create:

var formArr = []

for (var key in req.body) {

  if (req.body.hasOwnProperty(key)) {

    var formObj = {
      controlType: req.body[key].controlType,
      label: req.body[key].label,
      required: req.body[key].required,
      placeholder: req.body[key].placeholder,
      options: req.body[key].options
    }

    formArr.push(formObj)

  }

}

Form.create(formArr, function(err, results) {

  ...

})

If you want to save an array of objects  in a single document, then try using a nested schema:

var controlSchema = new Schema({
  controlType: {type: String, required: true},
  label: {type: String, required: true},
  required: {type: Boolean},
  placeholder: {type: String},
  options: [String]
}, {collection: 'inputForm'})

var formSchema = new Schema({
  controls: [controlSchema]
})

module.exports = mongoose.model('Form', formSchema)

...and then save the array as the controls field in a new document like this:

var controlsArr = []

for (var key in req.body) {

  if (req.body.hasOwnProperty(key)) {

    var controlObj = {
      controlType: req.body[key].controlType,
      label: req.body[key].label,
      required: req.body[key].required,
      placeholder: req.body[key].placeholder,
      options: req.body[key].options
    }

    controlsArr.push(controlObj)

  }

}

var form = new Form({
  controls: controlsArr
})

form.save(function(err, result) {

  ...

})


来源: stackexchange

问:
How can I join two tables but only return rows that don't match specific column which include NULL as well?
I have two tables which look like this:

```<code>T1:  ID  |  oldID

T2:  ID  |  newID
</code>```

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

答:
For SQL Server

```<code>SELECT  T1.ID ,T1.oldID,T2.[newID]
FROM    T1
INNER JOIN T2   ON  T1.ID = T2.ID AND   ISNULL(T1.oldID,0) <> ISNULL(T2.[newID],0)
</code>```

For MySql, use IFNULL instead of ISNULL.

If zero(0) is a value in either oldID or newID, you can use any other unused values for ISNULL function(ie -1 )

ContentLicense: CC BY-SA 3.0

Body:
I have two tables which look like this:

T1:  ID  |  oldID

T2:  ID  |  newID

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

Body:
For SQL Server

SELECT  T1.ID ,T1.oldID,T2.[newID]
FROM    T1
INNER JOIN T2   ON  T1.ID = T2.ID AND   ISNULL(T1.oldID,0) <> ISNULL(T2.[newID],0)

For MySql, use IFNULL instead of ISNULL.

If zero(0) is a value in either oldID or newID, you can use any other unused values for ISNULL function(ie -1 )


问:
Nagios alert integration with external tool
I'm integrating alerts and events from Nagios to my system. On searching I have found an integration of Moogsoft with Nagios(click). I have followed this, but it was not successful.

In their 'Step 2: Configurations:' they mentioned about 'HOSTNAME',
'BASIC_AUTH' etc. I can't found any of these keys in the respective downloaded file. Can anyone provide clarification or suggest any other solution? Any help would be greatful.

答:
Check out this link I found.

By the looks of it, you set the variables in the send-host-event.sh and send-service-event.sh files in the following way:

<FIELD>=<value>

So I assume you can place the variables directly after the recStation and recPort declarations.

Try this (change the values between the "<>"):

```<code># Host name, IP and Port should match those set for recStation
HOSTNAME="<hostname/ipaddress:9000>"
BASIC_AUTH=<false/true>
# Only need to set these variables if BASIC_AUTH is set to true
BASIC_AUTH_USER="<auth_username>"
BASIC_AUTH_PASS="<auth_password>"
</code>```

I hope that helps?

Body:
Check out this link I found.

By the looks of it, you set the variables in the send-host-event.sh and send-service-event.sh files in the following way:

<FIELD>=<value>

So I assume you can place the variables directly after the recStation and recPort declarations.

Try this (change the values between the "<>"):

# Host name, IP and Port should match those set for recStation
HOSTNAME="<hostname/ipaddress:9000>"
BASIC_AUTH=<false/true>
# Only need to set these variables if BASIC_AUTH is set to true
BASIC_AUTH_USER="<auth_username>"
BASIC_AUTH_PASS="<auth_password>"

I hope that helps?


问:
Im trying to retrieve data from mysql database into a html table
Almost everything is working fine except on the first column, the data is preceded by "1".

Here's my output :

The first column,ie,strength is preceded with 1. The data in my database is just a single digit number.

    <?php
    include 'index.php';
    $sql = "SELECT  t.strength, t.timeslot, t.cust_phno , c.fname, c.lname  FROM tables t,customer c WHERE t.cust_phno = c.cust_phno";
    $result = mysqli_query($con,$sql);
    ?>

         Table Strength
         Time Slot
         Customer Phone Number
         Customer Name

      <?php
      while( $array = mysqli_fetch_assoc($result)) {
        echo
        print "
 ";
      echo $array["strength"];
      print "	 ";
      echo $array["timeslot"];

      print "	 ";
      echo $array["cust_phno"];
      print "	 ";
      echo $array["fname"];
      print "&nbsp";
      echo $array["lname"];

      print "
";

          }
        ?>

```

答:
The 1 is the result of echoing the return from print... the following lines need to be slightly different..

```<code> while( $array = mysqli_fetch_assoc($result)) {
    echo
    print "<tr> <td>";
</code>```

You don't need the echo...

```<code> while( $array = mysqli_fetch_assoc($result)) {
    print "<tr> <td>";
</code>```

Body:
The 1 is the result of echoing the return from print... the following lines need to be slightly different..

 while( $array = mysqli_fetch_assoc($result)) {
    echo
    print "<tr> <td>";

You don't need the echo...

 while( $array = mysqli_fetch_assoc($result)) {
    print "<tr> <td>";


问:
git-svn branching without copying every subdirectory
Our project's trunk looks something like:

```<code>trunk/foo
trunk/bar
trunk/baz
</code>```

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

```<code>branches/branch1/foo
branches/branch2/foo
</code>```

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

```<code>branches/branch1/foo
branches/branch1/bar
</code>```

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

答:
It is common that one giant svn repository is represented by many git repositories. You should have used git svn init .. -t trunk/foo -b branches/branch1/foo -b branches/branch1/foo etc. Note: init, not clone. Then edit .git/config:

```<code>[svn-remote "foo"]
    url = http://server.org/svn
    fetch = trunk/foo:refs/remotes/foo/trunk
    branches = branches/*/foo:refs/remotes/foo/branches/*
    tags = tags/*/foo:refs/remotes/foo/tags/*
</code>```

Then do git svn fetch. In addition you could specify --ignore-paths e.g., to ignore docs directory.

After that git svn branch should do the right thing. See git-svn manual.

ContentLicense: CC BY-SA 2.5

Body:
Our project's trunk looks something like:

trunk/foo
trunk/bar
trunk/baz

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

branches/branch1/foo
branches/branch2/foo

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

branches/branch1/foo
branches/branch1/bar

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

Body:
It is common that one giant svn repository is represented by many git repositories. You should have used git svn init .. -t trunk/foo -b branches/branch1/foo -b branches/branch1/foo etc. Note: init, not clone. Then edit .git/config:

[svn-remote "foo"]
    url = http://server.org/svn
    fetch = trunk/foo:refs/remotes/foo/trunk
    branches = branches/*/foo:refs/remotes/foo/branches/*
    tags = tags/*/foo:refs/remotes/foo/tags/*

Then do git svn fetch. In addition you could specify --ignore-paths e.g., to ignore docs directory.

After that git svn branch should do the right thing. See git-svn manual.


问:
Unable to generate an explicit migration in entity framework
I am adding a new migration but this message shows:

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

Can any one help me?

答:
I suffered exactly the same problem just after reverting from a migration to another.

In my case I "targetedmigration" from "migration06" to "migration04".

I needed to delete the "migration0"6 and then I was able to force creating the "migration05". This basically means that you need to just keep the next migration after the targeted one.


问:
AWS CLI get status of deployment after deploying to elastic beanstalk
The last line of my deployment task using the AWS CLI is

```<code>aws elasticbeanstalk update-environment --application-name DevApi --environment-name Dev --version-label v2
</code>```

How can I check that the deployment of v2 was successful? At the moment I have another browser window open console.aws.amazon.com/elasticbeanstalk/ and check there. But there has to be a better way to automate it as part of my deployment by adding another step (cli command?) so I only need to check the deployment output?

EDIT: I should also mention I am running a Windows Elastic Beanstalk instance.

答:
One way I can think of is to check the EBS Health Reports.

If you are using Basic Monitoring, use the below cli:

```<code>aws elasticbeanstalk describe-environments --application-name DevApi  --environment-name Dev --query 'Environments[*].{Status: Status,Health: Health} --output json'
</code>```

Sample output:

```<code>[
    {
        "Status": "Ready",
        "Health": "Green"
    }
]
</code>```

For more info about each indicator, read Basic Health Reporting.

If you are using Enhanced Monitoring (for extra cost), then there is an additional parameter available which makes it much more clear.

```<code>aws elasticbeanstalk describe-environments --application-name DevApi  --environment-name Dev --query 'Environments[*].{Status: Status,Health: Health,HealthStatus: HealthStatus} --output json'
</code>```

Sample Output:

```<code>[
    {
        "Status": "Ready",
        "HealthStatus": "Ok",
        "Health": "Green"
    }
]
</code>```

Once the above status is reached, you can conclude the deployment is complete and is healthy.
If the HealthStatus is Info and Health is Green, It indicates An operation is in progress on an instance (or) on several instances in an environment. Example: A new application version is being deployed to running instances.

For more info about each health indicator, do read Enhanced Health reporting.

Body:
The last line of my deployment task using the AWS CLI is

aws elasticbeanstalk update-environment --application-name DevApi --environment-name Dev --version-label v2

How can I check that the deployment of v2 was successful? At the moment I have another browser window open console.aws.amazon.com/elasticbeanstalk/ and check there. But there has to be a better way to automate it as part of my deployment by adding another step (cli command?) so I only need to check the deployment output?

EDIT: I should also mention I am running a Windows Elastic Beanstalk instance.

Body:
One way I can think of is to check the EBS Health Reports.

If you are using Basic Monitoring, use the below cli:

aws elasticbeanstalk describe-environments --application-name DevApi  --environment-name Dev --query 'Environments[*].{Status: Status,Health: Health} --output json'

Sample output:

[
    {
        "Status": "Ready",
        "Health": "Green"
    }
]

For more info about each indicator, read Basic Health Reporting.

If you are using Enhanced Monitoring (for extra cost), then there is an additional parameter available which makes it much more clear.

aws elasticbeanstalk describe-environments --application-name DevApi  --environment-name Dev --query 'Environments[*].{Status: Status,Health: Health,HealthStatus: HealthStatus} --output json'

Sample Output:

[
    {
        "Status": "Ready",
        "HealthStatus": "Ok",
        "Health": "Green"
    }
]

Once the above status is reached, you can conclude the deployment is complete and is healthy.
If the HealthStatus is Info and Health is Green, It indicates An operation is in progress on an instance (or) on several instances in an environment. Example: A new application version is being deployed to running instances.

For more info about each health indicator, do read Enhanced Health reporting.


问:
ios voiceover for UITableView sections
Is there some way that I can avoid the section titles of the UITableView from saying "heading" in the voiceover mode after the text on the section is read? I am providing custom views in viewForHeaderInSection: . I have tried setting isAccessibilityElement to NO and accessibilityTraits to UIAccessibilityTraitNone for the custom view that I return in viewForHeaderInSection. But I cannot suppress the callout "heading" in voiceover mode. For e.g. if I set the label in the section as "Dates", it will be read out as Dates "pause" heading.

The reason I need to do this is that some of the sections are just custom messages with 0 rows, they are not really headings of any kind. I do not want to have them as rows within a section.

答:
You can implement accessibilityElementDidBecomeFocused method in your custom view,when this view did become focused and post UIAccessibilityLayoutChangedNotification to VoiceOver and focus to itself, and then return the traits UIAccessibilityTraitNone</p>

```<code>- (void)accessibilityElementDidBecomeFocused {
       UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,   self);
}

- (UIAccessibilityTraits)accessibilityTraits {
    return UIAccessibilityTraitNone;
}
</code>```

Title: ios voiceover for UITableView sections

Body:
You can implement accessibilityElementDidBecomeFocused method in your custom view,when this view did become focused and post UIAccessibilityLayoutChangedNotification to VoiceOver and focus to itself, and then return the traits UIAccessibilityTraitNone

- (void)accessibilityElementDidBecomeFocused {
       UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,   self);
}

- (UIAccessibilityTraits)accessibilityTraits {
    return UIAccessibilityTraitNone;
}


问:
What changes needs to be made so the output of a.b.c() is "I should be 'this'"
```<code>var a = {"b": {"c": function() {console.log( this );}}};
var x = {"b": "I should be 'this'"};

a.b.c();
</code>```

答:
You could bind the property or take the property as this object.

Without converting to string, you get an array like object in this console.

Methods:

Function#bind:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Function#call:

The call() method calls a function with a given this value and arguments provided individually.

Mabe you have a look here, too: this.

var a = { b: { c: function() { console.log(this.toString()); } } },
    x = { b: "I should be 'this'"};

a.b.c.bind(x.b)();
a.b.c.call(x.b);```


问:
Matlab Plotting with Labels
I'm trying to plot a knn result from my data, which has 3 columns: x, y , label. There are 3 classes and for each of them I would like to used a different symbol. Here's the way I'm plotting now:

```<code>t1 = data(:,3) == 1;
t2 = data(:,3) == 2;
t3 = data(:,3) == 3;

train1 = data(t1,:);
train2 = data(t2,:);
train3 = data(t3,:);

figure(1);

plot(train1(:,1),train1(:,2),'#',train2(:,1),train2(:,2),'*',train3(:,1),train3(:,2),'o');
</code>```

I want to know if there's a more concise way of doing this. Thanks

答:
Here's the most concise (and working) way to plot your data:

```<code>figure(1);
hold all
plot(train1(:,1),train1(:,2),'o')
plot(train2(:,1),train2(:,2),'x')
plot(train3(:,1),train3(:,2),'s')
</code>```

Here's an example that does what you want in a robust and modular manner. You can easily add classes or modify the figure output.

```<code>data = [0.53,0.17,2;0.78,0.60,3;0.93,0.26,1;0.13,0.65,2;0.57,0.69,1;...
        0.47,0.75,3;0.010,0.45,1;0.34,0.080,3;0.16,0.23,3;0.79,0.91,3;...
        0.31,0.15,1;0.53,0.83,2];

categories = [1,2,3];
symbols = {'s','<','o','d','v','+','x','*'};
figure;
hold all
for loopj = 1:length(categories)
    t = data(:,3) == categories(loopj);
    train = data(t,:);
    label = strcat('Class ',num2str(categories(loopj)));
    plot(train(:,1),train(:,2),symbols{loopj},'DisplayName',label,'LineWidth',1.3)
end
lg = legend('show');
lg.Location = 'best';
</code>```

Use hold all to write on the figure without erasing the previous axi and let Matlab pick line colors.

In any case, you need to manually define the different symbols and each plot command comes with one unique type of line and markers.

Title: Matlab Plotting with Labels

Body:
I'm trying to plot a knn result from my data, which has 3 columns: x, y , label. There are 3 classes and for each of them I would like to used a different symbol. Here's the way I'm plotting now:

t1 = data(:,3) == 1;
t2 = data(:,3) == 2;
t3 = data(:,3) == 3;

train1 = data(t1,:);
train2 = data(t2,:);
train3 = data(t3,:);

figure(1);

plot(train1(:,1),train1(:,2),'#',train2(:,1),train2(:,2),'*',train3(:,1),train3(:,2),'o');

I want to know if there's a more concise way of doing this. Thanks

Body:
Here's the most concise (and working) way to plot your data:

figure(1);
hold all
plot(train1(:,1),train1(:,2),'o')
plot(train2(:,1),train2(:,2),'x')
plot(train3(:,1),train3(:,2),'s')

Here's an example that does what you want in a robust and modular manner. You can easily add classes or modify the figure output.

data = [0.53,0.17,2;0.78,0.60,3;0.93,0.26,1;0.13,0.65,2;0.57,0.69,1;...
        0.47,0.75,3;0.010,0.45,1;0.34,0.080,3;0.16,0.23,3;0.79,0.91,3;...
        0.31,0.15,1;0.53,0.83,2];

categories = [1,2,3];
symbols = {'s','<','o','d','v','+','x','*'};
figure;
hold all
for loopj = 1:length(categories)
    t = data(:,3) == categories(loopj);
    train = data(t,:);
    label = strcat('Class ',num2str(categories(loopj)));
    plot(train(:,1),train(:,2),symbols{loopj},'DisplayName',label,'LineWidth',1.3)
end
lg = legend('show');
lg.Location = 'best';

Use hold all to write on the figure without erasing the previous axi and let Matlab pick line colors.

In any case, you need to manually define the different symbols and each plot command comes with one unique type of line and markers.


问:
Laravel session Convert tags to html entity
I want to convert this message value to an html entity :

```<code>return redirect('/')->withErrors(['success' => 'register done .<br> Thanks for register.']);
</code>```

but in my blade :

```<code>@if($errors->first('success'))
       $('.top-right').notify({
        message: { html: " <b>{{ $errors->first('success') }}</b> " },
        type: 'success',
        fadeOut: { enabled: true, delay: 7000 }
    }).show();
@endif
</code>```

{{ $errors->first('success') }}
 show this:

```<code>register done .<br> Thanks for register
</code>```

答:
you should use :

```<code>{!! $errors->first('success') !!}
</code>```

instead of

```<code>{{ $errors->first('success') }}
</code>```

Body:
I want to convert this message value to an html entity :

return redirect('/')->withErrors(['success' => 'register done .
 Thanks for register.']);

but in my blade :

@if($errors->first('success'))
       $('.top-right').notify({
        message: { html: " {{ $errors->first('success') }} " },
        type: 'success',
        fadeOut: { enabled: true, delay: 7000 }
    }).show();
@endif

{{ $errors->first('success') }}
 show this:

register done .
 Thanks for register

Body:
you should use :

{!! $errors->first('success') !!}

instead of

{{ $errors->first('success') }}


问:
Weird issue with spiking cpu on w3wp process
I'm having the strangest issue... I have a monorail website (a .NET solution, similar to ASP.NET MVC).. and on one of the pages there is a save button. When the save button is clicked, it executes some code to save the object to the database, and then redirects to another page. However, what it does is immediately after you click the save button, it executes all of the save code, and then it sits there for a while, and then it redirects to the other page and executes its code. Here are some facts about the situation that make it especially strange.

Every time you go through the process of clicking save and waiting for it to finish and redirect, it takes 2-4 seconds longer than the previous time you tried. So first time it'll take 2 seconds, then maybe 5, then 8, etc...

If you recycle the app pool, it makes it run fast again, but then fact #1 kicks in and it gets slower the more times you do it.

I added in logging and it executes the save and redirect code in 1 millisecond, then it waits for a while, and then it executes the new page's code quickly.

I tried changing it to redirect to google.com and it still behaves this way.

I tried making it not redirect at all, just serve up the existing page again after saving, and it still behaves this way.

Every time you click save, it spikes the cpu (specifically the w3wp process.)

Other pages do not behave this way, even other save methods.

Commenting out the code that saves to the database makes it work correctly, with no wait.

So does anyone have any idea what would cause this? The save code uses Active Record and NHibernate. The code itself runs super fast, like I said it's less than 1ms, but it seems like there's something happening asynchronously AFTER the code finishes executing that makes it hang for a long time..

Any ideas would be greatly appreciated, the code is at http://pastebin.com/XGLAWPgK.

答:
My Monorail is a bit rusty ...

Are you disposing of your ActiveRecord/nHibernate context after every request or caching it in the Session state? You shold create a new context for every request.

Are you Eager loading data entities? If you are Saving data, it may be fetching all associated entites.


问:
Vim Regex: Capture *first* instance of word between characters
My organization has an in-house language, with syntax like:

```<code>cmo/create/mo1///tri
createpts/brick/xyz/2,2,2/0.,0.,0./1.,1.,1./1,1,1
</code>```

I am writing a Vim syntax file, and would like to capture the first instance of a word enclosed by two characters (in this case, /), without capturing the characters themselves.

I.e., the regex would capture, from the lines above,

```<code>create
brick
</code>```

My solution so far is to use this pattern:

```<code>[,/=" "].\{-}[,/=" "]
</code>```

But from /this/and/this/and/this, it will capture /this/and/this/and/this/.

As you can see, the issue is two-fold: (i) my current solution is greedy, and (ii) captures the / characters as well, when I just want the words enclosed by these.

Thanks!

答:
One possible solution:

```<code>^[^\/]\+\/\zs[^\/]\+\ze\/
</code>```

^ anchor the search to the BOL,

[^\/]\+ one or more non-slash characters, as many as possible,

\/ a slash,

\zs start the match here,

[^\/]\+ one or more non-slash characters, as many as possible.

Body:
My organization has an in-house language, with syntax like:

cmo/create/mo1///tri
createpts/brick/xyz/2,2,2/0.,0.,0./1.,1.,1./1,1,1

I am writing a Vim syntax file, and would like to capture the first instance of a word enclosed by two characters (in this case, /), without capturing the characters themselves.

I.e., the regex would capture, from the lines above,

create
brick

My solution so far is to use this pattern:

[,/=" "].\{-}[,/=" "]

But from /this/and/this/and/this, it will capture /this/and/this/and/this/.

As you can see, the issue is two-fold: (i) my current solution is greedy, and (ii) captures the / characters as well, when I just want the words enclosed by these.

Thanks!

Body:
One possible solution:

^[^\/]\+\/\zs[^\/]\+\ze\/

^ anchor the search to the BOL,

[^\/]\+ one or more non-slash characters, as many as possible,

\/ a slash,

\zs start the match here,

[^\/]\+ one or more non-slash characters, as many as possible.


问:
different behaviour for current location latitude and longitude in iOS7 to IOS8
Using xamarin for current location currentLocation example
I used the above Link for getting current location latitude and longitude.

In IOS 7  before upgrade to IOS 8 Its shows my current location latitude and longitude on both simulator and device.(Its looks strange for me in simulator for getting current location latitude and longitude).

After upgrade to iOS 8 and run same code it give

In simulator:(Turn on wifi no sim card location service App always.)

```<code>Result:
latitude = 37.785834.
longitude = -122.406517.
</code>```

On Device IPhone5c (Turn on wifi no sim card location service App always.)

```<code>Result:
latitude = 37.785834.
longitude = -122.406517.
</code>```

(But I expected my current location latitude and longitude )

After upgrade it does not ask, that application like use the Your Current Location GPS. an Alert message with YES, NO options.

How to get my current location latitude and longitude?

答:
I tried above solutions but that did not work. Problem is when you are targeting IOS >= 9.0 then Location manager change some permission variables, which are supposed to mention explicitly in info.pList.

```<code><key>NSLocationWhenInUseUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationWhileInUsage</key>
<string>Why you need Location</string>
</code>```

use these four keys if you want to target  all versions .. before and after 9.0.

Also note that this line means whether user is in foreground or background use locations (apple discourage this because it has potential of privacy) check documentation here

```<code>[locationManager requestAlwaysAuthorization];
</code>```

whereas this means,

```<code>[locationManager requestWhenInUseAuthorization];
</code>```

Only use when app is in foreground check documentation here

Body:
Using xamarin for current location currentLocation example
I used the above Link for getting current location latitude and longitude.

In IOS 7  before upgrade to IOS 8 Its shows my current location latitude and longitude on both simulator and device.(Its looks strange for me in simulator for getting current location latitude and longitude).

After upgrade to iOS 8 and run same code it give

In simulator:(Turn on wifi no sim card location service App always.)

Result:
latitude = 37.785834.
longitude = -122.406517.

On Device IPhone5c (Turn on wifi no sim card location service App always.)

Result:
latitude = 37.785834.
longitude = -122.406517.

(But I expected my current location latitude and longitude )

After upgrade it does not ask, that application like use the Your Current Location GPS. an Alert message with YES, NO options.

How to get my current location latitude and longitude?

Body:
I tried above solutions but that did not work. Problem is when you are targeting IOS >= 9.0 then Location manager change some permission variables, which are supposed to mention explicitly in info.pList.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Why you need Location</string>

<key>NSLocationWhileInUsage</key>
<string>Why you need Location</string>

use these four keys if you want to target  all versions .. before and after 9.0.

Also note that this line means whether user is in foreground or background use locations (apple discourage this because it has potential of privacy) check documentation here

[locationManager requestAlwaysAuthorization];

whereas this means,

[locationManager requestWhenInUseAuthorization];

Only use when app is in foreground check documentation here


答:
```<code> <?php
      while( $array = mysqli_fetch_assoc($result)) {
        print "<tr> <td>";
      echo $array["strength"];
      print "</td> <td>";
      echo $array["timeslot"];

      print "</td> <td>";
      echo $array["cust_phno"];
      print "</td> <td>";
      echo $array["fname"];
      print "&nbsp";
      echo $array["lname"];

      print "</td> </tr>";

          }
        ?>
</code>```

Remove the echo from your code.

Title: Im trying to retrieve data from mysql database into a html table

Body:
Almost everything is working fine except on the first column, the data is preceded by "1".

Here's my output :

The first column,ie,strength is preceded with 1. The data in my database is just a single digit number.

    <?php
    include 'index.php';
    $sql = "SELECT  t.strength, t.timeslot, t.cust_phno , c.fname, c.lname  FROM tables t,customer c WHERE t.cust_phno = c.cust_phno";
    $result = mysqli_query($con,$sql);
    ?>

         Table Strength
         Time Slot
         Customer Phone Number
         Customer Name

      <?php
      while( $array = mysqli_fetch_assoc($result)) {
        echo
        print "
 ";
      echo $array["strength"];
      print "	 ";
      echo $array["timeslot"];

      print "	 ";
      echo $array["cust_phno"];
      print "	 ";
      echo $array["fname"];
      print "&nbsp";
      echo $array["lname"];

      print "
";

          }
        ?>

Body:
 <?php
      while( $array = mysqli_fetch_assoc($result)) {
        print "<tr> <td>";
      echo $array["strength"];
      print "</td> <td>";
      echo $array["timeslot"];

      print "</td> <td>";
      echo $array["cust_phno"];
      print "</td> <td>";
      echo $array["fname"];
      print "&nbsp";
      echo $array["lname"];

      print "</td> </tr>";

          }
        ?>

Remove the echo from your code.


问:
crop an image in react-native
User can move the crop functionalities according to their needs means downward,upward,left side or rightside may be.Anyone have any idea how to crop the image in react native,I want that image for scanning purpose.  </p>

答:
You can use react-native-perspective-image-cropper

https://github.com/Michaelvilleneuve/react-native-perspective-image-cropper

Title: crop an image in react-native


问:
How to set .htaccess for 2 type get value on the same page?
For this page test.php

i have to use 2 format url

```<code>www.example.com/test/1234
</code>```

and

```<code>www.example.com/test/1234/abcd
</code>```

My .htaccess is

```<code>RewriteRule ^test/([^-]*)/([^-]*)$ /test.php?one=$1&two=$2 [L]
</code>```

It's work good with www.example.com/test/1234/abcd but redirect internal error with www.example.com/test/1234

I want to know how can i edit .htaccess for work good with my 2 url format on test.php ?

答:
Try the following instead:

```<code>RewriteRule ^test/([^-]*)$ /test.php?one=$1&two=$2 [L]
</code>```

Just remove the 2nd /([^-]*) it is making no difference, as you can see here. Removing it will allow for you to access www.example.com/test/1234 too.

Body:
For this page test.php

i have to use 2 format url

www.example.com/test/1234

and

www.example.com/test/1234/abcd

My .htaccess is

RewriteRule ^test/([^-]*)/([^-]*)$ /test.php?one=$1&two=$2 [L]

It's work good with www.example.com/test/1234/abcd but redirect internal error with www.example.com/test/1234

I want to know how can i edit .htaccess for work good with my 2 url format on test.php ?

Body:
Try the following instead:

RewriteRule ^test/([^-]*)$ /test.php?one=$1&two=$2 [L]

Just remove the 2nd /([^-]*) it is making no difference, as you can see here. Removing it will allow for you to access www.example.com/test/1234 too.


问:
Get short date for System Nullable datetime (datetime ?) in C#
How to get short date for Get short date for System Nullable datetime (datetime ?)

for ed 12/31/2013 12:00:00 --> only should return 12/31/2013.

I don't see the ToShortDateString available.

答:
If you are using .cshtml then you can use as

```<code><td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>
</code>```

or if you try to find short date in action or method in c# then

```<code>yourDate.GetValueOrDefault().ToShortDateString();
</code>```

And is already answered above by Steve.

I have shared this as i used in my project. it works fine. Thank you.

Body:
If you are using .cshtml then you can use as

<td>@(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>

or if you try to find short date in action or method in c# then

yourDate.GetValueOrDefault().ToShortDateString();

And is already answered above by Steve.

I have shared this as i used in my project. it works fine. Thank you.


问:
magento create an account with billing info added
I want to have the customer give us their billing address and phone # on the create an account page.

Right now it is

First Name

Last Name

Email

(Phone Number) add on

(Billing Address) add on

Sign up for Newsletter

Password

Confirm Password

I am trying to figure out what page I would add these fields to. I seem to have these fields once you click create an account and get to the account dashboard. So I would like to just use these fields and move them forward a page to be required from the beginning.

答:
form fields are already present in registration template (in default theme)

simply add this to local.xml of your theme to enable them

```<code><customer_account_create>
  <reference name="customer_form_register">
    <action method="setShowAddressFields">
      <param>true</param>
    </action>
  </reference>
</customer_account_create>
</code>```

Body:
form fields are already present in registration template (in default theme)

simply add this to local.xml of your theme to enable them

<customer_account_create>
  <reference name="customer_form_register">
    <action method="setShowAddressFields">
      <param>true</param>
    </action>
  </reference>
</customer_account_create>


问:
Adding items to array with while loops
I'm trying to push 1 -> 10 into my "array1"  though I'm sure that it's not working.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]```

p0's innerhtml stays as "Random Array Item:" and does not change, though when I remove the while loop it seems to work fine, example output, "Random Array Item: | test | text | abc | abc | text | abc"

答:
You have an error when referencing your array, as you are using array but your array is named array1. You need to change that in order to work:

i=0;
array1 = ["123", "abc", "string", "text", "test", "ok"];
while (i <= 10){
    array1.push(i);
    i++;
}
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="p0">Random Array Item</p></code>```

Title: Adding items to array with while loops

Body:
I'm trying to push 1 -> 10 into my "array1"  though I'm sure that it's not working.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]

p0's innerhtml stays as "Random Array Item:" and does not change, though when I remove the while loop it seems to work fine, example output, "Random Array Item: | test | text | abc | abc | text | abc"

Body:
You have an error when referencing your array, as you are using array but your array is named array1. You need to change that in order to work:

i=0;
array1 = ["123", "abc", "string", "text", "test", "ok"];
while (i <= 10){
    array1.push(i);
    i++;
}
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];

<p id="p0">Random Array Item</p>


答:
If the use case is just to push 1...10 into a new array, this will work.</p>

```<code>var array1 = ["123", "abc", "string", "text", "test", "ok"],
[1,2,3,4,5,6,7,8,9,10].forEach(function(i){
 array1.push(i);
});

document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];
</code>```

Title: Adding items to array with while loops

Body:
If the use case is just to push 1...10 into a new array, this will work.

var array1 = ["123", "abc", "string", "text", "test", "ok"],
[1,2,3,4,5,6,7,8,9,10].forEach(function(i){
 array1.push(i);
});

document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];


问:
How do I strip down a URL into separate parts in Bash?
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

```<code>URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)
</code>```

答:
Just bash :)

```<code>URL="https://example.com/someone/something"

regex='(https?://[^/]*)/([^/]*)/(.*)'

if [[ "$URL" =~ $regex ]]
then
  DOMAIN=${BASH_REMATCH[1]}

  UUSER=${BASH_REMATCH[2]}

  THING=${BASH_REMATCH[3]}
fi

echo "$DOMAIN -- $UUSER -- $THING"
</code>```

I used UUSER to not be confused with the USER environment variable

Body:
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)

Body:
Just bash :)

URL="https://example.com/someone/something"

regex='(https?://[^/]*)/([^/]*)/(.*)'

if [[ "$URL" =~ $regex ]]
then
  DOMAIN=${BASH_REMATCH[1]}

  UUSER=${BASH_REMATCH[2]}

  THING=${BASH_REMATCH[3]}
fi

echo "$DOMAIN -- $UUSER -- $THING"

I used UUSER to not be confused with the USER environment variable


问:
How to get a list of all switches and all hosts?
I'm working with POX for the first time. What I'm trying to do is install rules in a switch to forward the packets that they were sended originally to hosts that they are connected to this switch.

H1---S1----S2---H3

```<code>         |---H4
</code>```

Example: H1 send a certain packet to H3 and H4 that when they arrive to S2 they have to be forwarded to the controller. What I had in mind is to install these rules when I start the controller but to do that I need to get the hosts connected to the switches.

Are there some method to know the hosts connected to a given switch?

答:
At first, Daniel you have to see some examples (e.g. on youtube) about mininet and then about pox and controllers. The first ping from h1 to h3 goes from h1 to s1 and then s1 asks controller about routing flow. Then the controller replies to s1 with the corresponding routing flow (depending on the controller logic) and s1 write the routing flow in its "routing flow table". Then s1 forwords the packet to s2 and then s2 to h3. That's why the next pings is faster than the first.
Ping from h1 to h4 follows the above procces.

To install rules on switches depends on the switch type. The general idea is to preconfigure from python script, or parsing commands from mininet cli, or via xterm on switches or via REST api (depending on controller).

Body:
I'm working with POX for the first time. What I'm trying to do is install rules in a switch to forward the packets that they were sended originally to hosts that they are connected to this switch.

H1---S1----S2---H3

         |---H4

Example: H1 send a certain packet to H3 and H4 that when they arrive to S2 they have to be forwarded to the controller. What I had in mind is to install these rules when I start the controller but to do that I need to get the hosts connected to the switches.

Are there some method to know the hosts connected to a given switch?


问:
copy data of a project(from a project table) from one database to other in Oracle
Could somebody tell me how to do this in Oracle:

I have a table named project in which there a multiple projects. I want to copy the data of a particular project from the source database to another database. The project doesn't exist(in the project table) in the destination database.

I want something like:
copy from sourceDatabase to destinationDatabase
           create new_table using select * from project where name='Name of the project to be copied'

答: You can also use the expdp and impdp command to extract tables and import it anywhere you want.</p>


问:
ExecuteNonQuery is not running
```<code>foreach (GridViewRow g1 in GridView1.Rows)
{
      SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, CONVERT(VARBINARY(MAX), @image), @price, @paymentMode, @holderName)", con);

      cmd.Parameters.AddWithValue("@buyersName", Label2.Text);
      cmd.Parameters.AddWithValue("@deliveryAddress", TextBox1.Text);
      cmd.Parameters.AddWithValue("@productID", g1.Cells[0].Text);
      cmd.Parameters.AddWithValue("@productName", g1.Cells[1].Text);
      cmd.Parameters.AddWithValue("@category", g1.Cells[2].Text);
      cmd.Parameters.AddWithValue("@image", g1.Cells[3].Text);
      cmd.Parameters.AddWithValue("@price", g1.Cells[4].Text);
      cmd.Parameters.AddWithValue("@paymentMode", checkRadioButton());
      cmd.Parameters.AddWithValue("@holderName", TextBox2.Text);

      int r = cmd.ExecuteNonQuery();
 }
</code>```

When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.

答:
you can't have expression like convert() within the VALUE ()

Change to use

```<code>INSERT INTO [Order] (column name, ...)
select @buyersName, convert() ,...
</code>```

by the way you should explicitly specify the column name in the INSERT clause or in future when you add a column to the table, your query will break

also why are you using reserved name as table name ?

Title: ExecuteNonQuery is not running

Body:
foreach (GridViewRow g1 in GridView1.Rows)
{
      SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, CONVERT(VARBINARY(MAX), @image), @price, @paymentMode, @holderName)", con);

      cmd.Parameters.AddWithValue("@buyersName", Label2.Text);
      cmd.Parameters.AddWithValue("@deliveryAddress", TextBox1.Text);
      cmd.Parameters.AddWithValue("@productID", g1.Cells[0].Text);
      cmd.Parameters.AddWithValue("@productName", g1.Cells[1].Text);
      cmd.Parameters.AddWithValue("@category", g1.Cells[2].Text);
      cmd.Parameters.AddWithValue("@image", g1.Cells[3].Text);
      cmd.Parameters.AddWithValue("@price", g1.Cells[4].Text);
      cmd.Parameters.AddWithValue("@paymentMode", checkRadioButton());
      cmd.Parameters.AddWithValue("@holderName", TextBox2.Text);

      int r = cmd.ExecuteNonQuery();
 }

When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.

Body:
you can't have expression like convert() within the VALUE ()

Change to use

INSERT INTO [Order] (column name, ...)
select @buyersName, convert() ,...

by the way you should explicitly specify the column name in the INSERT clause or in future when you add a column to the table, your query will break

also why are you using reserved name as table name ?


问:
How do I display "public gps traces" with Leaflet in my OSM map?
I can see the flag toggled in the querystring when I go openstreetmaps, but in my leaflet implementation of a map, I cannot get "Public GPS Traces" or"Cycle Map" to display. I am new to Leaflet, and assume its a layer. But there are many variants of layers and I'm not sure how to ask it to display these.

Here's my code...

```<code>var map = L.map( 'wwmap', {
  center: [41.2779, -72.7073],
  minZoom: 9,
  zoom: 13,
})
  L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
  subdomains: ['a', 'b', 'c']
}).addTo( map )
</code>```

In the following URL, I can see the layer flags being passed, (layers=CG). Not sure how to do get them to display in my embeded default map with leaflet.
Sample URL with querystring:
https://www.openstreetmap.org/#map=16/41.2812/-72.7147&layers=CG

答:
These flags (layers=CG) are irrelevant for you. They just tell which tile sources to activate.

Take a look at the images your browser loads and you will see the URLs for these tile sources. The GPS layer is located at http://gps-{s}.tile.openstreetmap.org/lines/ and the cycle layer is at http://{s}.tile.thunderforest.com/cycle/.

For a list of possible tile servers take a look at:

OSM Wiki

Leaflet Provider Demo

mapstyle.petschge.de

Map Compare

switch2osm.org

Note that each tile server has a specific usage policy you have to follow. Moreover, some (e.g. the tiles from Thunderforest) require an API key.

Body:
I can see the flag toggled in the querystring when I go openstreetmaps, but in my leaflet implementation of a map, I cannot get "Public GPS Traces" or"Cycle Map" to display. I am new to Leaflet, and assume its a layer. But there are many variants of layers and I'm not sure how to ask it to display these.

Here's my code...

var map = L.map( 'wwmap', {
  center: [41.2779, -72.7073],
  minZoom: 9,
  zoom: 13,
})
  L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap',
  subdomains: ['a', 'b', 'c']
}).addTo( map )

In the following URL, I can see the layer flags being passed, (layers=CG). Not sure how to do get them to display in my embeded default map with leaflet.
Sample URL with querystring:
https://www.openstreetmap.org/#map=16/41.2812/-72.7147&layers=CG


问:
Count number of "True" values in boolean Tensor
I understand that tf.where will return the locations of True values, so that I could use the result's shape[0] to get the number of Trues.

However, when I try and use this, the dimension is unknown (which makes sense as it needs to be computed at runtime). So my question is, how can I access a dimension and use it in an operation like a sum?

For example:

```<code>myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
myTensor.get_shape() #=> [None, 2]
sum = 0
sum += myTensor.get_shape().as_list()[0] # Well defined at runtime but considered None until then.
</code>```

答:
I think this is the easiest way to do it: </p>

```<code>In [38]: myOtherTensor = tf.constant([[True, True], [False, True]])

In [39]: if_true = tf.count_nonzero(myOtherTensor)

In [40]: sess.run(if_true)
Out[40]: 3
</code>```

Body:
I understand that tf.where will return the locations of True values, so that I could use the result's shape[0] to get the number of Trues.

However, when I try and use this, the dimension is unknown (which makes sense as it needs to be computed at runtime). So my question is, how can I access a dimension and use it in an operation like a sum?

For example:

myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
myTensor.get_shape() #=> [None, 2]
sum = 0
sum += myTensor.get_shape().as_list()[0] # Well defined at runtime but considered None until then.

Body:
I think this is the easiest way to do it:

In [38]: myOtherTensor = tf.constant([[True, True], [False, True]])

In [39]: if_true = tf.count_nonzero(myOtherTensor)

In [40]: sess.run(if_true)
Out[40]: 3


问:
each function not working as expected
So what I try to do is the following:

I got some items in 3 columns and default positioning (position:static).
And I'm trying to transition them to top:0; left:0 of the page.
Transitions between different positions (absolute and static) are not possible in CSS3, so I tried a jQuery workaround:

```<code>$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});
</code>```

What this is supposed to do, is to take every item with class item and "duplicate" it at the exisiting position with position:absolute
This is working perfectly for one item. But as soon as I got multiple items, it simply stacks them at the position of the  first item...

Here's a fiddle:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}</code>```

1

2

3

4

4

```

My desired result is that jQuery takes every item, gets its position on the page, and replaces the CSS, so it's at the same position as before, just with position:absolute, so I can transition it to top:0;left:0; afterwards.

答:
The best solution I was able to find is to append the new content in another hidden div, then remove the old div, and show the new one.

You was facing that problem, because while updating the divs to position absolute, the other divs styling was also being updated at the same time because they are floating.

$(function() {
  $(".item").each(function(){
    var items = $(this);

    var _text = items.text() ;
    var _css = "width:" + items.width() + "px" +
        "; height:" + items.height() + "px" +
        "; position:absolute" +
        "; top:" + items.offset().top + "px" +
        "; left:" + items.offset().left + "px" + ";"
    var _style = "style='" + _css + "'" ;

    var _div = "
" + _text + "
" ;

    $("#items_clone").append(_div) ;
  });

  $("#items").remove() ;
  $("#items_clone").show().attr("id", "items") ;
}) ;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
#items_clone{
  display:none;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}</code>```

1

2

3

4

5

```

Title: each function not working as expected

Body:
So what I try to do is the following:

I got some items in 3 columns and default positioning (position:static).
And I'm trying to transition them to top:0; left:0 of the page.
Transitions between different positions (absolute and static) are not possible in CSS3, so I tried a jQuery workaround:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});

What this is supposed to do, is to take every item with class item and "duplicate" it at the exisiting position with position:absolute
This is working perfectly for one item. But as soon as I got multiple items, it simply stacks them at the position of the  first item...

Here's a fiddle:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});

#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}

1

2

3

4

4

My desired result is that jQuery takes every item, gets its position on the page, and replaces the CSS, so it's at the same position as before, just with position:absolute, so I can transition it to top:0;left:0; afterwards.

Body:
The best solution I was able to find is to append the new content in another hidden div, then remove the old div, and show the new one.

You was facing that problem, because while updating the divs to position absolute, the other divs styling was also being updated at the same time because they are floating.

$(function() {
  $(".item").each(function(){
    var items = $(this);

    var _text = items.text() ;
    var _css = "width:" + items.width() + "px" +
        "; height:" + items.height() + "px" +
        "; position:absolute" +
        "; top:" + items.offset().top + "px" +
        "; left:" + items.offset().left + "px" + ";"
    var _style = "style='" + _css + "'" ;

    var _div = "<div class='item' " + _style + ">" + _text + "</div>" ;

    $("#items_clone").append(_div) ;
  });

  $("#items").remove() ;
  $("#items_clone").show().attr("id", "items") ;
}) ;

#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
#items_clone{
  display:none;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
</div>
<div id="items_clone">

</div>


问:
How do I check the size of different variables in a function?
For a class I have to this simple problem in which I need to check the size of multiple types of variables while using pointers and display it all.
I want my code to look as clean as posible. So I wanted to know if there is something that does it cleaner. I have this code as of now.

```<code>void size (float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc){
    for(int i=1; i <=5; i++){
        cout << "Size of pointer " << i << " is:" << sizeof(p::i)<< endl;
    }

    cout << "Size of control pointer is:" << sizeof(pc)<< endl;
}
</code>```

Is there a way to do it somehow like this, or do I have to explicitely write line by line?

答:
if your goal is to automatically print the sizes of some function parameters, you may write something like

```<code>template< typename T, typename... V >
void print_size_of_args( T(*f)(V...) )
  {(( std::cout << "size of arg[" << typeid(V).name() << "] is " << sizeof(V) << std::endl ), ... );}

void fun(float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc)
{
  print_size_of_args(fun);
  // ...
}
</code>```

this is c++17 and, as it is, works for non overloaded, non member functions; can be made more general if necessary ...

Body:
For a class I have to this simple problem in which I need to check the size of multiple types of variables while using pointers and display it all.
I want my code to look as clean as posible. So I wanted to know if there is something that does it cleaner. I have this code as of now.

void size (float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc){
    for(int i=1; i <=5; i++){
        cout << "Size of pointer " << i << " is:" << sizeof(p::i)<< endl;
    }

    cout << "Size of control pointer is:" << sizeof(pc)<< endl;
}

Is there a way to do it somehow like this, or do I have to explicitely write line by line?

Body:
if your goal is to automatically print the sizes of some function parameters, you may write something like

template< typename T, typename... V >
void print_size_of_args( T(*f)(V...) )
  {(( std::cout << "size of arg[" << typeid(V).name() << "] is " << sizeof(V) << std::endl ), ... );}

void fun(float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc)
{
  print_size_of_args(fun);
  // ...
}

this is c++17 and, as it is, works for non overloaded, non member functions; can be made more general if necessary ...


问:
Check no of occurance of all digits in array using single for Loop or use Any Collection
```<code>Integer a[]={10,20,30,10,10,20,50,60,50,50};

for(int i=0;i<a.length;i++)
{

             int count=0;
            for(int j=0;j<a.length;j++)
            {

                if(a[i]==a[j])
                {
                    count++;

                }
            }
            System.out.println(a[i]+" occurs times ="+count);
            count=0;
}
</code>```

答:
```<code>Integer a[] = {10, 20, 30, 10, 10, 20, 50, 60, 50, 50};
Map<Integer, Integer> integerIntegerMap =
        Stream.of(a).collect(Collectors.groupingBy(o -> o))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, o -> o.getValue().size()));
System.out.println(integerIntegerMap);
</code>```

Output:

{50=3, 20=2, 10=3, 60=1, 30=1}

Body:
Integer a[] = {10, 20, 30, 10, 10, 20, 50, 60, 50, 50};
Map<Integer, Integer> integerIntegerMap =
        Stream.of(a).collect(Collectors.groupingBy(o -> o))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, o -> o.getValue().size()));
System.out.println(integerIntegerMap);

Output:

{50=3, 20=2, 10=3, 60=1, 30=1}


问:
iframe content reloads when there is a DOM manipulation Angular
I have an iframe that is loaded dynamically when a specific condition is met.

```<code>      <div *ngIf="iframeData">
        <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl(iframeData.iFrameUrl)" name="paymetricIFrame"></iframe>
      </div>
</code>```

The issue I have is that whenever anything in the page - outside of the frame -  changes (Input text, select values, etc), the iFrame content reloads, and I can see all the scripts contained being reloaded in the network tab, and therefore what the user has filled in the iframe disappears.

I am suspecting the ChangeDetectionStrategy since the stack trace of the initiator of the call that loads the files for the iframe goes back to viewRef._detectChanges as you can see from the screenshot:

I tried to add ChangeDetectionStrategy.OnPush but that created other issues on the page.

答: I solved the issue by creating a new component that contains only the iframe. I would still want to know why that solved the issue...</p>

Body:
I have an iframe that is loaded dynamically when a specific condition is met.

The issue I have is that whenever anything in the page - outside of the frame -  changes (Input text, select values, etc), the iFrame content reloads, and I can see all the scripts contained being reloaded in the network tab, and therefore what the user has filled in the iframe disappears.

I am suspecting the ChangeDetectionStrategy since the stack trace of the initiator of the call that loads the files for the iframe goes back to viewRef._detectChanges as you can see from the screenshot:

I tried to add ChangeDetectionStrategy.OnPush but that created other issues on the page.


问:
How to pass a string to a var without escape symbol in Kotlin?
I hope to pass the string {"name":"My Settings 1"} to a var aa

I have to write it using the code  var aa=" {\"name\":\"My Settings 1\"} "

Is there a simple way in Kotlin when I use Android Studio 3.0 ?

I know <![CDATA[...]]> is good for XML content

答:
Escaping special chars in regular Strings, like in your example, is what has to be done with Java and also Kotlin:

```<code>"{\"name\":\"My Settings 1\"}"
</code>```

Kotlin offers raw Strings to evade this. In these raw Strings there's no need to escape special chars, which shows the following:

```<code> """{"name":"My Settings 1"}"""
</code>```

Raw Strings are delimited by a triple quote (""").
Read the docs here.

Body:
Escaping special chars in regular Strings, like in your example, is what has to be done with Java and also Kotlin:

"{\"name\":\"My Settings 1\"}"

Kotlin offers raw Strings to evade this. In these raw Strings there's no need to escape special chars, which shows the following:

 """{"name":"My Settings 1"}"""

Raw Strings are delimited by a triple quote (""").
Read the docs here.


问:
Javascript local variable technique
I have a simple question related to one-line programming. First an example:

```<code>function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}
</code>```

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

```<code>function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
</code>```

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

```<code>function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}
</code>```

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

答:
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." – Brian W. Kernighan

I'm not knocking you, I'm just saying be careful not to get overzealous.

ContentLicense: CC BY-SA 4.0

Title: Javascript local variable technique

Body:
I have a simple question related to one-line programming. First an example:

function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).


问:
Generate random numbers from exponential distribution and model using python
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

```<code>from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')
</code>```

The result could look something like this.

And then I define a function to draw a line through my points:

```<code>def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()
</code>```

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

答:
I agree with the solution of @ImportanceOfBeingErnes, but I'd like to add a (well known?) general solution for distributions. If you have a distribution function f with integral F (i.e. f = dF / dx) then you get the required distribution by mapping random numbers with inv F i.e. the inverse function of the integral. In case of the exponential function, the integral is, again, an exponential and the inverse is the logarithm. So it can be done like this:

```<code>import matplotlib.pyplot as plt
import numpy as np
from random import random

def gen( a ):
    y=random()
    return( -np.log( y ) / a )

def dist_func( x, a ):
    return( a * np.exp( -a * x) )

data = [ gen(3.14) for x in range(20000) ]
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.hist(data, bins=80, normed=True, histtype="step")
ax.plot(np.linspace(0,5,150), dist_func( np.linspace(0,5,150), 3.14 ) )
plt.show()
</code>```

Body:
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')

The result could look something like this.

And then I define a function to draw a line through my points:

def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

Body:
I agree with the solution of @ImportanceOfBeingErnes, but I'd like to add a (well known?) general solution for distributions. If you have a distribution function f with integral F (i.e. f = dF / dx) then you get the required distribution by mapping random numbers with inv F i.e. the inverse function of the integral. In case of the exponential function, the integral is, again, an exponential and the inverse is the logarithm. So it can be done like this:

import matplotlib.pyplot as plt
import numpy as np
from random import random

def gen( a ):
    y=random()
    return( -np.log( y ) / a )

def dist_func( x, a ):
    return( a * np.exp( -a * x) )

data = [ gen(3.14) for x in range(20000) ]
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.hist(data, bins=80, normed=True, histtype="step")
ax.plot(np.linspace(0,5,150), dist_func( np.linspace(0,5,150), 3.14 ) )
plt.show()


问:
IBM Content Collector error calling external Web Service
In my current project using IBM Content Collector 4.0.1 SP5 with IBM Filenet P8 Content Engine 5.2.1 I need to collect files from file system and add them to a certain P8's object store.

After performing upload on the server or in case of error I inserted a WS Call Web Service Task in order to submit some data to be written to a database.

The configuration is the following:

The web service is REST conformant as requested in the WS Call Web Service task description page provided by IBM, follows a code excerpt:

```<code>@RequestMapping(value = "/filenet/notificaArchiviazione", method = { RequestMethod.GET,
                      RequestMethod.POST }, consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE,
                                     MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, produces = {
                                                    MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
       @ResponseBody
       String notificaArchiviazione(@RequestParam("fileName") String fileName, @RequestParam("esito") String esito) {
</code>```

When ICC tries to call the WS I get a HTTP/1.1 400 Bad Request error like this:

2017-10-20T13:47:10.394Z FINEST    [47] Prepared content to send to
  webservice:{"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.pdf":{"esito":"KO","fileName":"Prova"},"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.xml":{"esito":"KO","fileName":"Prova"}}

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask
  getInputHttpEntity] [CTMS-task-12dc 44] 2017-10-20T13:47:10.456Z
  FINEST     [48] Configuration:
  http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione
     fileName

  esito

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:10.830Z FINEST    [49] Invoking
  webservice
  URI:http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.763Z FINEST    [50] Invocation
  took time (ms): 2933

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.763Z SEVERE    [51] Failed to
  invoke webservice: HTTP/1.1 400 Bad Request

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.841Z FINEST    [52]
  [ctms-native] 2017-10-20T13:47:13Z    Trace2  0x12dc  Invocation
  successfull, task finished...

What am I doing wrong?

答:
Finally I managed to get it work eliminating the consumes parameter from the annotation; doing this will force the WS to accept every kind of possible message provided it is given through a GET or POST method.

In addition I received a hint by a IBM ICC and eDM L2 support who suggested:

It appears that your web server does not understand the request that
  is being sent from ICC.

This is the request being sent from ICC (from the log snippet you
  provided):

{"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.pdf":{"esito":"KO","fileName":"Prova"},"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.xml":{"esito":"KO","fileName":"Prova"}}

Check your code if it is able to parse the data above.

Body:
In my current project using IBM Content Collector 4.0.1 SP5 with IBM Filenet P8 Content Engine 5.2.1 I need to collect files from file system and add them to a certain P8's object store.

After performing upload on the server or in case of error I inserted a WS Call Web Service Task in order to submit some data to be written to a database.

The configuration is the following:

The web service is REST conformant as requested in the WS Call Web Service task description page provided by IBM, follows a code excerpt:

@RequestMapping(value = "/filenet/notificaArchiviazione", method = { RequestMethod.GET,
                      RequestMethod.POST }, consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE,
                                     MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, produces = {
                                                    MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
       @ResponseBody
       String notificaArchiviazione(@RequestParam("fileName") String fileName, @RequestParam("esito") String esito) {

When ICC tries to call the WS I get a HTTP/1.1 400 Bad Request error like this:

2017-10-20T13:47:10.394Z FINEST    [47] Prepared content to send to
  webservice:{"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.pdf":{"esito":"KO","fileName":"Prova"},"e:\report\amm_000001_00001\2017\10\201710_amm_000001_00001_qxn_report_00_errato.xml":{"esito":"KO","fileName":"Prova"}}

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask
  getInputHttpEntity] [CTMS-task-12dc 44] 2017-10-20T13:47:10.456Z
  FINEST     [48] Configuration:
  http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione
     fileName

  esito

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:10.830Z FINEST    [49] Invoking
  webservice
  URI:http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.763Z FINEST    [50] Invocation
  took time (ms): 2933

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.763Z SEVERE    [51] Failed to
  invoke webservice: HTTP/1.1 400 Bad Request

  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-12dc 44] 2017-10-20T13:47:13.841Z FINEST    [52]
  [ctms-native] 2017-10-20T13:47:13Z    Trace2  0x12dc  Invocation
  successfull, task finished...

What am I doing wrong?


问:
Fatal error when moving pimcore from a server to local
I moved all my pimcore files plus the database from a server to my localhost and made the necessary changes in website/var/config/system.xml.
Admin is working but the frond end is showing an error:

```<code>Fatal error: Call to a member function getFielddefinitions() on a non-object in /var/www/html/pimcore/pimcore/models/Object/Localizedfield/Resource.php on line 179
</code>```

This line of code produces the error:

```<code>$this->model->getClass()->getFielddefinition("localizedfields")->getFielddefinitions()
</code>```

The system requirements and file permissions are correct.

For testing purpose I installed a new pimcore project on my local system and it's working perfectly.

Can I make any changes in my Database?
How can I run my project successfully on local?

答:
Pimcore uses database views for storing objects data. When exporting database, in views definitions there will be also SECURITY DEFINER.

/*!50013 DEFINER=`prod-user`@`%` SQL SECURITY DEFINER */

OPTION: Vinot VT solution should work
You can acchive same with running command:

php pimcore/cli/console.php deployment:classes-rebuild

OPTION: Use same database username on your local env 'prod-user', which is  useful if you will import prod database a lot

OPTION: replace  DEFINER=prod-user@% with DEFINER=local-user@% before importing database

Body:
I moved all my pimcore files plus the database from a server to my localhost and made the necessary changes in website/var/config/system.xml.
Admin is working but the frond end is showing an error:

Fatal error: Call to a member function getFielddefinitions() on a non-object in /var/www/html/pimcore/pimcore/models/Object/Localizedfield/Resource.php on line 179

This line of code produces the error:

$this->model->getClass()->getFielddefinition("localizedfields")->getFielddefinitions()

The system requirements and file permissions are correct.

For testing purpose I installed a new pimcore project on my local system and it's working perfectly.

Can I make any changes in my Database?
How can I run my project successfully on local?


问:
Cyclically mapping flat arrays of different sizes and summing the values
I have an issue with two arrays that I need to combine, where the first array contains a list of campaign names ( page_data ) like

```<code>[
    "Campaign 1",
    "Campaign 2",
    "Campaign 3"
]
</code>```

and another array that contains number of leads for the campaigns. But this array will contain twice as many keys as the campaign array like this:

```<code>[
    222,
    342,
    71,
    33,
    43,
    665
]
</code>```

It contains twice as many keys, because it will take leads from two different forms, so the values for key 0 and key 3 will be for campaign 1 and key 2 and key 4 will be for campaign 2. It will always be this way. If there are 5 campaigns, leads array will have 10 keys and key 0 and key 5 will be for campaign one, key 1 an key 6 for campaign 2, etc.

And then I have this piece of code to combine ( push ):

```<code>foreach (json_decode($result) as $key) {
   foreach ($pages["page_data"] as $p => $pvalue) {
       array_push(
           $leadArray,
           array(
               "pageName" => $pvalue["form_name"],
               "pageLeads" => $key[$p]
           )
       );
    }
}
</code>```

That will incorrectly make an array that looks something like:

```<code>[
    "campaign 1" => 222,
    "campaign 2" => 342,
    "campaign 3" => 71
]
</code>```

But that will only take keys 0,1,2 and so key 3,4,5 will not be in the array.

What I want is key 0 and key 3, key 1 and key 4, etc. in the leads array to be combined so the the new leads array will be

```<code>[
    255,
    386,
    736
]
</code>```

which I can then combine with the campaigns array as the number of keys from the two arrays will now match which will give me an array that looks like

```<code>[
    "campaign 1" => 255,
    "campaign 2" => 386,
    "campaign 3" => 736
]
</code>```

答:
@aslawin approach may be realized a litle easy with some functions

```<code>$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [0 => 222, 1 => 342, 2 => 71, 3 => 33, 4 => 43, 5 => 665];

$res = array_combine($array1,
           array_map(function($i1, $i2) { return $i1+$i2; },
                 ...array_chunk($array2, count($array1))))
</code>```

reply to comment: it's not obvious that the OP needs more than twice the length of the second array, but the code can easily be rewritten for any length

```<code>$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [222, 342, 71, 33, 43, 665, -255, -385, -736];

$res = array_combine($array1,
           array_map(function(...$ar) { return array_sum($ar); },
                 ...array_chunk($array2, count($array1))));

print_r($res);
</code>```

output

```<code>[0, 0, 0]
</code>```

Body:
I have an issue with two arrays that I need to combine, where the first array contains a list of campaign names ( page_data ) like

[
    "Campaign 1",
    "Campaign 2",
    "Campaign 3"
]

and another array that contains number of leads for the campaigns. But this array will contain twice as many keys as the campaign array like this:

[
    222,
    342,
    71,
    33,
    43,
    665
]

It contains twice as many keys, because it will take leads from two different forms, so the values for key 0 and key 3 will be for campaign 1 and key 2 and key 4 will be for campaign 2. It will always be this way. If there are 5 campaigns, leads array will have 10 keys and key 0 and key 5 will be for campaign one, key 1 an key 6 for campaign 2, etc.

And then I have this piece of code to combine ( push ):

foreach (json_decode($result) as $key) {
   foreach ($pages["page_data"] as $p => $pvalue) {
       array_push(
           $leadArray,
           array(
               "pageName" => $pvalue["form_name"],
               "pageLeads" => $key[$p]
           )
       );
    }
}

That will incorrectly make an array that looks something like:

[
    "campaign 1" => 222,
    "campaign 2" => 342,
    "campaign 3" => 71
]

But that will only take keys 0,1,2 and so key 3,4,5 will not be in the array.

What I want is key 0 and key 3, key 1 and key 4, etc. in the leads array to be combined so the the new leads array will be

[
    255,
    386,
    736
]

which I can then combine with the campaigns array as the number of keys from the two arrays will now match which will give me an array that looks like

[
    "campaign 1" => 255,
    "campaign 2" => 386,
    "campaign 3" => 736
]

Body:
@aslawin approach may be realized a litle easy with some functions

$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [0 => 222, 1 => 342, 2 => 71, 3 => 33, 4 => 43, 5 => 665];

$res = array_combine($array1,
           array_map(function($i1, $i2) { return $i1+$i2; },
                 ...array_chunk($array2, count($array1))))

reply to comment: it's not obvious that the OP needs more than twice the length of the second array, but the code can easily be rewritten for any length

$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [222, 342, 71, 33, 43, 665, -255, -385, -736];

$res = array_combine($array1,
           array_map(function(...$ar) { return array_sum($ar); },
                 ...array_chunk($array2, count($array1))));

print_r($res);

output

[0, 0, 0]


问:
Putting the dir_id using boxr package in R
I am trying to setup the working directory-using the url-"https:\..."

Code:

```<code>box_setwd(url)

Error:-
Error in box_id(dir_id) :
box.com API ids must be (coercible to) 64-bit integers.
</code>```

I am exploring bit64 package meanwhile it will be great to have a workaround.
I hope the details are enough.

答: the dir and other ids pertaining to the boxr commands are the numeric extensions in  the url- it's available in the documentation</p>

Body:
I am trying to setup the working directory-using the url-"https:\..."

Code:

box_setwd(url)

Error:-
Error in box_id(dir_id) :
box.com API ids must be (coercible to) 64-bit integers.

I am exploring bit64 package meanwhile it will be great to have a workaround.
I hope the details are enough.


问:
Autostart JavaFX Application on RaspberryPi
I programmed a JavaFX application which runs on a "Raspberry Pi" (a small ARM based Linux Computer). The OS on the "Pi" is "Raspbian" (a Debian Linux for Raspberry Pi). I installed JDK8 on Raspbian to run graphic JavaFX Application without X-Server. This all works fine :) I can start the Application by entering the following command:

```<code>/opt/jdk1.8.0/bin/java -cp /home/pi/sqljdbc4.jar:/home/pi/Leitwarte.jar leitwarte.Leitwarte
</code>```

When the application starts it takes full control over mouse an keyboard, so there is no way back into console, but this doesent maters because it is just a monitoring system an i am able to shut the mashine down over ssh.

I now want to start the application directly after booting, so that there is no need for entering username ,passwort and starting the application.

The mashine does nothing else just running the app (of course there runs a ftp, ssh deamon for making updating the app posible)

Please tell me step by step, because i dont work with Linux for a long time.

Thank you very much.

答:
I solved this problem

When the application starts it takes full control over mouse an
  keyboard, so there is no way back into console

by adding quotes ("") and by giving -Djavafx.platform=gtk for DEFAULT_JVM_OPTS.
For example in my case I replaced this code:

```<code>DEFAULT_JVM_OPTS=-XX:+UseG1GC -Dmode=prod_w_updates
</code>```

to this:

```<code>DEFAULT_JVM_OPTS="-XX:+UseG1GC -Dmode=prod_w_updates -Djavafx.platform=gtk"
</code>```

Hope, it will help

Body:
I programmed a JavaFX application which runs on a "Raspberry Pi" (a small ARM based Linux Computer). The OS on the "Pi" is "Raspbian" (a Debian Linux for Raspberry Pi). I installed JDK8 on Raspbian to run graphic JavaFX Application without X-Server. This all works fine :) I can start the Application by entering the following command:

/opt/jdk1.8.0/bin/java -cp /home/pi/sqljdbc4.jar:/home/pi/Leitwarte.jar leitwarte.Leitwarte

When the application starts it takes full control over mouse an keyboard, so there is no way back into console, but this doesent maters because it is just a monitoring system an i am able to shut the mashine down over ssh.

I now want to start the application directly after booting, so that there is no need for entering username ,passwort and starting the application.

The mashine does nothing else just running the app (of course there runs a ftp, ssh deamon for making updating the app posible)

Please tell me step by step, because i dont work with Linux for a long time.

Thank you very much.

Body:
I solved this problem

When the application starts it takes full control over mouse an
  keyboard, so there is no way back into console

by adding quotes ("") and by giving -Djavafx.platform=gtk for DEFAULT_JVM_OPTS.
For example in my case I replaced this code:

DEFAULT_JVM_OPTS=-XX:+UseG1GC -Dmode=prod_w_updates

to this:

DEFAULT_JVM_OPTS="-XX:+UseG1GC -Dmode=prod_w_updates -Djavafx.platform=gtk"

Hope, it will help


问:
transform scipy sparse csr to pandas?
I have used the

```<code>sklearn.preprocessing.OneHotEncoder
</code>```

to transform some data the output is scipy.sparse.csr.csr_matrix
how can I merge it back into my original dataframe along with the other columns?

I tried to use pd.concat but I get

```<code>TypeError: cannot concatenate a non-NDFrame object
</code>```

Thanks

答:
You could also avoid getting back a sparse matrix in the first place by setting the parameter sparse to False when creating the Encoder.

The documentation of the OneHotEncoder states:

sparse : boolean, default=True

Will return sparse matrix if set True else will return an array.

Then you can again call the DataFrame constructor to transform the numpy array to a DataFrame.

Title: transform scipy sparse csr to pandas?

Body:
I have used the

sklearn.preprocessing.OneHotEncoder

to transform some data the output is scipy.sparse.csr.csr_matrix
how can I merge it back into my original dataframe along with the other columns?

I tried to use pd.concat but I get

TypeError: cannot concatenate a non-NDFrame object

Thanks