问:
save() doesn't update datetime fields in monoengine
I am new to mongoengine, but this doesn't make any sense to me, that when I call my my_update() function, the user's updated_at field doesnt get updated but other fields do.
here is my model:

```<code>class User(db.Document):
    username = db.StringField(required=True, unique=True, max_length=20)
    created_at = db.DateTimeField(default=datetime.datetime.utcnow())
    updated_at = db.DateTimeField()
    friend_list = ListField(StringField(max_length=100))
</code>```

when I do a save, it saves the new friend_list correctly but it keeps the old updated_at field, and that one will never get updated again.

```<code>def my_update(user_id):
    form = UserForm()
    user = User.objects.get_or_404(id=user_id)
    user.friend_list = insert_random_data()
    user.updated_at = datetime.datetime.utcnow()
    user.save()
    return users = User.objects.order_by('-updated_at', '-created_at')
</code>```

so if I run my_update a few times, it will update the friend_list each time, but the update_at field keeps staying the same !!! and I have no idea. I am really curious why is it behaving like this !

答:
To anyone who has same problem,
I figured out I had to use Atomic Update() instead of Save() because the save() wouldn't block till it is done and my view function will ask for the object before it was saved.

so bottom line is, Save is Evil (mostly). just use atomic update !

like this

User.objects(id=user.id).update(set__update_at=datetime.datetime.utcnow(), push__friend_list="ss")

Body:
I am new to mongoengine, but this doesn't make any sense to me, that when I call my my_update() function, the user's updated_at field doesnt get updated but other fields do.
here is my model:

class User(db.Document):
    username = db.StringField(required=True, unique=True, max_length=20)
    created_at = db.DateTimeField(default=datetime.datetime.utcnow())
    updated_at = db.DateTimeField()
    friend_list = ListField(StringField(max_length=100))

when I do a save, it saves the new friend_list correctly but it keeps the old updated_at field, and that one will never get updated again.

def my_update(user_id):
    form = UserForm()
    user = User.objects.get_or_404(id=user_id)
    user.friend_list = insert_random_data()
    user.updated_at = datetime.datetime.utcnow()
    user.save()
    return users = User.objects.order_by('-updated_at', '-created_at')

so if I run my_update a few times, it will update the friend_list each time, but the update_at field keeps staying the same !!! and I have no idea. I am really curious why is it behaving like this !


来源: stackexchange

问:
Changed position from day and month converting strings to date
I am working on following issue in PHP.
I have these variables:

$fecha = "01-07-2017";

$hora = "11:30";

Now I want to create a date variable with format Y-m-d H:i.

For that I am using following code:

```<code>$newDate = date("Y-m-d H:i", strtotime($fecha.' '.$hora));
</code>```

But I am getting the output:

```<code>echo $newDate = 2017-01-07 11:30
</code>```

I need it to be: 2017-07-01 11:30

What am I doing wrong?

答:
Change your code to:

```<code>$newDate = date("Y-d-m H:i", strtotime($fecha.' '.$hora));
</code>```

Notice that I just switched around 'h' & 'd' in the date function.

ContentLicense: CC BY-SA 3.0

Body:
I am working on following issue in PHP.
I have these variables:

$fecha = "01-07-2017";

$hora = "11:30";

Now I want to create a date variable with format Y-m-d H:i.

For that I am using following code:

$newDate = date("Y-m-d H:i", strtotime($fecha.' '.$hora));

But I am getting the output:

echo $newDate = 2017-01-07 11:30

I need it to be: 2017-07-01 11:30

What am I doing wrong?

Body:
Change your code to:

$newDate = date("Y-d-m H:i", strtotime($fecha.' '.$hora));

Notice that I just switched around 'h' & 'd' in the date function.


问:
python anti_vowel function error
Hi I'm doing the anti_vowel function, which basically takes out all of the vowels from the input. I'm confused about this code. Why doesn't it work? (For the last word "word")  The output for "Hey look words!" is:
Hy lk words!
If anyone can help, thank you so so much!

```<code>def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)

    for i in l:
        if i in "aeiouAEIOU":
            x = l.index(i)
            l.pop(x)
    print l
    print "".join(l)

anti_vowel("Hey look words!")
</code>```

The output is:
Hy lk Wrds!

答:
Since other answers have already provided you with an explanation of your problem, and showed how to fix your code, I'll show you how you can make your function much smaller and cleaner.

You can use a generator comprehension to filter out all of the vowels from your input, and use ''.join() to join each individual character back together:

```<code>>>> def anti_vowels(text):
    return ''.join(c for c in text if c.lower() not in 'aeiou')

>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hello, World!')
'Hll, Wrld!'
>>> anti_vowels('I love vowels!')
' lv vwls!'
>>> anti_vowels('Ronald Regan')
'Rnld Rgn'
>>> anti_vowels('Carts And BOxes')
'Crts nd Bxs'
>>>
</code>```

The important part of the comprehension is the the if part. It will only add the current character to the generator if it is not a vowel. I've also eliminated the extra uppercase vowels by using c.lower(). This force c to become lower case, so we can treat the character as if it were case insensitive.

You can also easily extend this to allow the user to specify the vowels they want to filter out (such as y):

```<code>>>> def anti_vowels(text, vowels='aeiou'):
    return ''.join(c for c in text if c.lower() not in vowels)

>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hey look words!', vowels='aeiouy')
'H lk wrds!'
>>>
</code>```

Title: python anti_vowel function error

Body:
Hi I'm doing the anti_vowel function, which basically takes out all of the vowels from the input. I'm confused about this code. Why doesn't it work? (For the last word "word")  The output for "Hey look words!" is:
Hy lk words!
If anyone can help, thank you so so much!

def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)

    for i in l:
        if i in "aeiouAEIOU":
            x = l.index(i)
            l.pop(x)
    print l
    print "".join(l)

anti_vowel("Hey look words!")

The output is:
Hy lk Wrds!

Body:
Since other answers have already provided you with an explanation of your problem, and showed how to fix your code, I'll show you how you can make your function much smaller and cleaner.

You can use a generator comprehension to filter out all of the vowels from your input, and use ''.join() to join each individual character back together:

>>> def anti_vowels(text):
    return ''.join(c for c in text if c.lower() not in 'aeiou')

>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hello, World!')
'Hll, Wrld!'
>>> anti_vowels('I love vowels!')
' lv vwls!'
>>> anti_vowels('Ronald Regan')
'Rnld Rgn'
>>> anti_vowels('Carts And BOxes')
'Crts nd Bxs'
>>>

The important part of the comprehension is the the if part. It will only add the current character to the generator if it is not a vowel. I've also eliminated the extra uppercase vowels by using c.lower(). This force c to become lower case, so we can treat the character as if it were case insensitive.

You can also easily extend this to allow the user to specify the vowels they want to filter out (such as y):

>>> def anti_vowels(text, vowels='aeiou'):
    return ''.join(c for c in text if c.lower() not in vowels)

>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hey look words!', vowels='aeiouy')
'H lk wrds!'
>>>


问:
Angular 2 - datepickers don't work
I need a datepicker to my application. First I tried to add bootstrap datepicker, but it didn't work. Therefore I tried to use ngBootstrap, but it still doesn't work. When I click to the icon I didn't get an calendar. Icon is not working.

my code:

```<code><form class="form-inline">
<div class="form-group">
    <div class="input-group">
    <input class="form-control" placeholder="yyyy-mm-dd"
            name="dp" [(ngModel)]="modelDate" ngbDatepicker #d="ngbDatepicker">
    <div class="input-group-addon" (click)="d.toggle()" >
        <img src="img/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
    </div>
    </div>
</div>
</code>```

```Model: {{ modelDate | json }}```

答:
Usually the problem is a result of not importing the ngBootstrap libraries correctly.

I'm assuming you've added it to your project dependencies:

```<code>npm install ng-bootstrap
</code>```

In your index.html file, you need to import the Bootstrap css files

```<code>  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/bootstrap-grid.min.css">
  <link rel="stylesheet" href="/css/bootstrap-reboot.min.css">
</code>```

You can get these here:

https://v4-alpha.getbootstrap.com

Download the package and copy the css files into your project root css directory (/css/would match the import statements above). You don't need the js files, as ng-bootstrap provides the required code.

In the component where you're using the nbgDatepicker, you need to import the library at the top

```<code>import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
</code>```

And then the date picker should work properly.

Title: Angular 2 - datepickers don't work

Body:
I need a datepicker to my application. First I tried to add bootstrap datepicker, but it didn't work. Therefore I tried to use ngBootstrap, but it still doesn't work. When I click to the icon I didn't get an calendar. Icon is not working.

my code:

<form class="form-inline">

    <input class="form-control" placeholder="yyyy-mm-dd"
            name="dp" [(ngModel)]="modelDate" ngbDatepicker #d="ngbDatepicker">

Model: {{ modelDate | json }}

Body:
Usually the problem is a result of not importing the ngBootstrap libraries correctly.

I'm assuming you've added it to your project dependencies:

npm install ng-bootstrap

In your index.html file, you need to import the Bootstrap css files

  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/bootstrap-grid.min.css">
  <link rel="stylesheet" href="/css/bootstrap-reboot.min.css">

You can get these here:

https://v4-alpha.getbootstrap.com

Download the package and copy the css files into your project root css directory (/css/would match the import statements above). You don't need the js files, as ng-bootstrap provides the required code.

In the component where you're using the nbgDatepicker, you need to import the library at the top

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

And then the date picker should work properly.


问:
c++ conversion operators no candidate is better
```<code>    #include <iostream>
#include <string>

using namespace std;

class test {
    private:
        std::string strValue;
        int value;

    public:
        test():value(0) { };
        test(int a):value(a) { };
        test(std::string a):strValue(a) { };
        ~test(){};

        operator int () { return value; }
        operator const char* () { return strValue.c_str(); }
};

int main() {
    test v1(100);
    cout << v1  << endl;
    return 0;
}
</code>```

When I run the above, with gcc I get an error saying no candidate is better for conversion.. Aren't they exclusive types?

答:
test v1(100);
cout << v1  << endl;

Since cout doesn't have operator << (ostream&, test) it tries conversions. You provided two, both types are defined with ostream, so you got ambiguity.

ContentLicense: CC BY-SA 2.5

Body:
    #include <iostream>
#include <string>

using namespace std;

class test {
    private:
        std::string strValue;
        int value;

    public:
        test():value(0) { };
        test(int a):value(a) { };
        test(std::string a):strValue(a) { };
        ~test(){};

        operator int () { return value; }
        operator const char* () { return strValue.c_str(); }
};

int main() {
    test v1(100);
    cout << v1  << endl;
    return 0;
}

When I run the above, with gcc I get an error saying no candidate is better for conversion.. Aren't they exclusive types?


问:
SQL Server Operating system error 5: "5(Access is denied.)"
I am starting to learn SQL and I have a book that provides a database to work on. These files below are in the directory but the problem is that when I run the query, it gives me this error:

Msg 5120, Level 16, State 101, Line 1 Unable to open the physical file
  "C:\Murach\SQL Server 2008\Databases\AP.mdf". Operating system error
  5: "5(Access is denied.)".

```<code>   CREATE DATABASE AP
      ON PRIMARY (FILENAME = 'C:\Murach\SQL Server 2008\Databases\AP.mdf')
      LOG ON (FILENAME =     'C:\Murach\SQL Server 2008\Databases\AP_log.ldf')
      FOR ATTACH
    GO
</code>```

In the book the author says it should work, but it is not working in my case. I searched but I do not know exactly what the problem is, so I posted this question.

答: I had this problem. Just run SQL Server as administrator

Body:
I am starting to learn SQL and I have a book that provides a database to work on. These files below are in the directory but the problem is that when I run the query, it gives me this error:

Msg 5120, Level 16, State 101, Line 1 Unable to open the physical file
  "C:\Murach\SQL Server 2008\Databases\AP.mdf". Operating system error
  5: "5(Access is denied.)".

   CREATE DATABASE AP
      ON PRIMARY (FILENAME = 'C:\Murach\SQL Server 2008\Databases\AP.mdf')
      LOG ON (FILENAME =     'C:\Murach\SQL Server 2008\Databases\AP_log.ldf')
      FOR ATTACH
    GO

In the book the author says it should work, but it is not working in my case. I searched but I do not know exactly what the problem is, so I posted this question.

ContentLicense: CC BY-SA 4.0


问:
How to add Web API controller to an existing ASP.NET Core MVC?
I created a project using the default ASP.NET Core MVC template. I would like to also create a RESTful API under /api/{Controller}. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found. I tried adding a route in Startup.cs but it doesn't do anything:

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});
</code>```

EDIT:

Like I said, it's all default templates. Here's the Web API Controller that I added:

```<code>[Route("api/[controller]")]
public class AdminController : Controller
{
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
</code>```

答:
Two things.

First, when using convention-based routing, more specific routes should come before more generic routes to avoid route conflicts.

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

Secondly, you are already using attribute routing on the controller so should have been able to route to the controller except for the fact that you do not have a routing template on the controller that would accept /api/{Controller}

That would require a default route.

```<code>[Route("api/[controller]")]
public class AdminController : Controller {

    [HttpGet("")] //Matches GET api/admin <-- Would also work with [HttpGet]
    public IActionResult Get() {
        return Ok();
    }

    [HttpGet("{id}")] //Matches GET api/admin/5
    public IActionResult Get(int id) {
        return Ok("value");
    }

    //...other code removed for brevity
}
</code>```

Body:
I created a project using the default ASP.NET Core MVC template. I would like to also create a RESTful API under /api/{Controller}. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found. I tried adding a route in Startup.cs but it doesn't do anything:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});

EDIT:

Like I said, it's all default templates. Here's the Web API Controller that I added:

[Route("api/[controller]")]
public class AdminController : Controller
{
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Body:
Two things.

First, when using convention-based routing, more specific routes should come before more generic routes to avoid route conflicts.

app.UseMvc(routes =>
{
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});

Secondly, you are already using attribute routing on the controller so should have been able to route to the controller except for the fact that you do not have a routing template on the controller that would accept /api/{Controller}

That would require a default route.

[Route("api/[controller]")]
public class AdminController : Controller {

    [HttpGet("")] //Matches GET api/admin <-- Would also work with [HttpGet]
    public IActionResult Get() {
        return Ok();
    }

    [HttpGet("{id}")] //Matches GET api/admin/5
    public IActionResult Get(int id) {
        return Ok("value");
    }

    //...other code removed for brevity
}


问:
Unable to check for changed rows in a dataset
I have a table within my program which stores information about messages and would like to detect when new information has been added to it. The reason I am doing this is beucause I would like to show the new data to the user only when there is new data instead of having to constantly get all the rows and display them.

The way I decided to do this was through the use of the dataSet.HasChanged() function which should essentially check the dataset for any new rows and a function called DataChanged returns dataSet.HasChanged() value.

However, the function I am using always returns false (even when there are changes)

Here is the function...

```<code>public bool DataChanged(string Table)
{
    //This is the variable that will be returned
    bool ChangesMade;

    //Create the  adapter
    OleDbDataAdapter adapter = new OleDbDataAdapter(Table, connector);
    //Clear the current data in the dataset
    dataSet.Clear();
    //Open the connection and fill the dataset
    connector.Open();
    adapter.Fill(dataSet, "TableData1");
    connector.Close();
    return ChangesMade = dataSet.HasChanges();
}
</code>```

Changes for some reason are never detected and therefore this function always returns false even after I add a new record to the dataset.

An alternative method that provides the functionality explained in paragraph one would be very helpful and the fixing of my current method ever more so.

答:
Here is an easy way to do this.

Make sure a Timestamp/Rowversion column exists for each table you wish to track changes to.

Return the current database Timestamp to your calling program as part of your data result set (DataSet in this case).  For example, add the following query to your result set.

```<code>SELECT @@DBTS;
</code>```

Use this returned value the next time you run your query with the following added to the existing WHERE clause(s) as appropriate.

```<code>...
AND (@LastRowversionValue IS NULL
    OR TableName.RowversionColumn > @LastRowversionValue)
...
</code>```

Pass NULL for the @LastRowversionValue the first time the query is ran to get the process started.

Any rows that are inserted/updated into the table(s) since the last time you retrieved data, will have an Rowversion greater than the one you stored from the last execution.

Body:
I have a table within my program which stores information about messages and would like to detect when new information has been added to it. The reason I am doing this is beucause I would like to show the new data to the user only when there is new data instead of having to constantly get all the rows and display them.

The way I decided to do this was through the use of the dataSet.HasChanged() function which should essentially check the dataset for any new rows and a function called DataChanged returns dataSet.HasChanged() value.

However, the function I am using always returns false (even when there are changes)

Here is the function...

public bool DataChanged(string Table)
{
    //This is the variable that will be returned
    bool ChangesMade;

    //Create the  adapter
    OleDbDataAdapter adapter = new OleDbDataAdapter(Table, connector);
    //Clear the current data in the dataset
    dataSet.Clear();
    //Open the connection and fill the dataset
    connector.Open();
    adapter.Fill(dataSet, "TableData1");
    connector.Close();
    return ChangesMade = dataSet.HasChanges();
}

Changes for some reason are never detected and therefore this function always returns false even after I add a new record to the dataset.

An alternative method that provides the functionality explained in paragraph one would be very helpful and the fixing of my current method ever more so.

Body:
Here is an easy way to do this.

Make sure a Timestamp/Rowversion column exists for each table you wish to track changes to.

Return the current database Timestamp to your calling program as part of your data result set (DataSet in this case).  For example, add the following query to your result set.

SELECT @@DBTS;

Use this returned value the next time you run your query with the following added to the existing WHERE clause(s) as appropriate.

...
AND (@LastRowversionValue IS NULL
    OR TableName.RowversionColumn > @LastRowversionValue)
...

Pass NULL for the @LastRowversionValue the first time the query is ran to get the process started.

Any rows that are inserted/updated into the table(s) since the last time you retrieved data, will have an Rowversion greater than the one you stored from the last execution.


问:
How to decide between scipy.integrate.simps or numpy.trapz?
I have a set of points, of which when I plot I get the graph below. I would like to find the area under the graph, however I am not sure whether scipy.integrate.simps or numpy.trapz is more suitable.

Could someone advice me on the mathematical background between the two functions and thus the conclusion on which function is more accurate?

答:
The trapezoidal rule is the simplest of numerical integration methods. In effect, it estimates the area under a curve by approximating the curve with straight line segments, which only requires two points for each segment. Simpson's rule uses quadratic curves to approximate the function segments instead, each of which requires three points, sampled from your function, to approximate a given segment.

So what is the error associated with using these numerical methods as approximations to an analytical integral?

The error associated with the trapezoidal rule, to leading order, is proportional to h^2[f'(a) - f'(b)]. h is the spacing between sampled points in your function; f'(a) and f'(b) are the first derivative of your function at the beginning and end of the sampling domain.

The error through Simpson's rule, on the other hand, is proportional to h^4[f'''(a) - f'''(b)]. f''' is the third-order derivative in your function.

h is typically small, so h^4 is typically much smaller than h^2!

TLDR: Simpson's rule typically gives far superior results for numerical integration, compared to the trapezoidal rule, with basically no additional computational cost.


问:
Quaternion assignment Failed in Eigen
I got Access violation error when I assign a quaterninon. I have checked that i is not out-of-bounds.The code is as blow:

```<code>using Quaternionr = Eigen::Quaternion<double>;
class A{
      std::vector<Quaternionr> m_lastQ;
public:
      EIGEN_MAKE_ALIGNED_OPERATOR_NEW
inline void setLastQuaternion(const unsigned int i, const Quaternionr &pos)
 {
      m_lastQ[i] = pos; // access violation happends
 }
 };
</code>```

The call back is as below:

```<code>POCosseratRods.exe!Eigen::internal::pload<__m128d>(const double * from) Line 307
POCosseratRods.exe!Eigen::internal::ploadt<__m128d,16>(const double * from) Line 463
POCosseratRods.exe!Eigen::internal::evaluator<Eigen::PlainObjectBase<Eigen::Matrix<double,4,1,0,4,1> > >::packet<16,__m128d>(int row, int col) Line 197
POCosseratRods.exe!Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>::assignPacket<16,16,__m128d>(int row, int col) Line 652
POCosseratRods.exe!Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>::assignPacketByOuterInner<16,16,__m128d>(int outer, int inner) Line 667
POCosseratRods.exe!Eigen::internal::copy_using_evaluator_innervec_CompleteUnrolling<Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>,0,4>::run(Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0> & kernel) Line 276
POCosseratRods.exe!Eigen::internal::dense_assignment_loop<Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>,2,2>::run(Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0> & kernel) Line 468
POCosseratRods.exe!Eigen::internal::call_dense_assignment_loop<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 741
POCosseratRods.exe!Eigen::internal::Assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double>,Eigen::internal::Dense2Dense,void>::run(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 879
POCosseratRods.exe!Eigen::internal::call_assignment_no_alias<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 836
POCosseratRods.exe!Eigen::internal::call_assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func, void * __formal) Line 804
POCosseratRods.exe!Eigen::internal::call_assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src) Line 782
POCosseratRods.exe!Eigen::PlainObjectBase<Eigen::Matrix<double,4,1,0,4,1> >::_set<Eigen::Matrix<double,4,1,0,4,1> >(const Eigen::DenseBase<Eigen::Matrix<double,4,1,0,4,1> > & other) Line 710
POCosseratRods.exe!Eigen::Matrix<double,4,1,0,4,1>::operator=(const Eigen::Matrix<double,4,1,0,4,1> & other) Line 209
POCosseratRods.exe!Eigen::QuaternionBase<Eigen::Quaternion<double,0> >::operator=(const Eigen::QuaternionBase<Eigen::Quaternion<double,0> > & other) Line 486
POCosseratRods.exe!OrientationData::setLastQuaternion(const unsigned int i, const Eigen::Quaternion<double,0> & pos) Line 407
POCosseratRods.exe!TimeStepController::step(SimulationModel & model) Line 43
POCosseratRods.exe!RodScene::update() Line 117
POCosseratRods.exe!idlefunc() Line 40
freeglutd.dll!0fd8dd9c()    Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for freeglutd.dll]
POCosseratRods.exe!main(int argc, char * * argv) Line 90
[External Code]
</code>```

This error happends accidently. Sometimes, it doesn't occur. I don't know if it has to do with alligenment.

I use Visual Studion 2013, Eigen 3.3.4 on Windows 10.

答:
It is the problem with STL container. Here is the explanation.

To use std::vector with Eigen, an aligned allocator is necessary.

```<code>std::vector<Quaternionr,Eigen::aligned_allocator<Quaternionr>> m_lastQ;
</code>```

Title: Quaternion assignment Failed in Eigen

Body:
I got Access violation error when I assign a quaterninon. I have checked that i is not out-of-bounds.The code is as blow:

using Quaternionr = Eigen::Quaternion<double>;
class A{
      std::vector<Quaternionr> m_lastQ;
public:
      EIGEN_MAKE_ALIGNED_OPERATOR_NEW
inline void setLastQuaternion(const unsigned int i, const Quaternionr &pos)
 {
      m_lastQ[i] = pos; // access violation happends
 }
 };

The call back is as below:

POCosseratRods.exe!Eigen::internal::pload<__m128d>(const double * from) Line 307
POCosseratRods.exe!Eigen::internal::ploadt<__m128d,16>(const double * from) Line 463
POCosseratRods.exe!Eigen::internal::evaluator<Eigen::PlainObjectBase<Eigen::Matrix<double,4,1,0,4,1> > >::packet<16,__m128d>(int row, int col) Line 197
POCosseratRods.exe!Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>::assignPacket<16,16,__m128d>(int row, int col) Line 652
POCosseratRods.exe!Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>::assignPacketByOuterInner<16,16,__m128d>(int outer, int inner) Line 667
POCosseratRods.exe!Eigen::internal::copy_using_evaluator_innervec_CompleteUnrolling<Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>,0,4>::run(Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0> & kernel) Line 276
POCosseratRods.exe!Eigen::internal::dense_assignment_loop<Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0>,2,2>::run(Eigen::internal::generic_dense_assignment_kernel<Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::evaluator<Eigen::Matrix<double,4,1,0,4,1> >,Eigen::internal::assign_op<double,double>,0> & kernel) Line 468
POCosseratRods.exe!Eigen::internal::call_dense_assignment_loop<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 741
POCosseratRods.exe!Eigen::internal::Assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double>,Eigen::internal::Dense2Dense,void>::run(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 879
POCosseratRods.exe!Eigen::internal::call_assignment_no_alias<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func) Line 836
POCosseratRods.exe!Eigen::internal::call_assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1>,Eigen::internal::assign_op<double,double> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src, const Eigen::internal::assign_op<double,double> & func, void * __formal) Line 804
POCosseratRods.exe!Eigen::internal::call_assignment<Eigen::Matrix<double,4,1,0,4,1>,Eigen::Matrix<double,4,1,0,4,1> >(Eigen::Matrix<double,4,1,0,4,1> & dst, const Eigen::Matrix<double,4,1,0,4,1> & src) Line 782
POCosseratRods.exe!Eigen::PlainObjectBase<Eigen::Matrix<double,4,1,0,4,1> >::_set<Eigen::Matrix<double,4,1,0,4,1> >(const Eigen::DenseBase<Eigen::Matrix<double,4,1,0,4,1> > & other) Line 710
POCosseratRods.exe!Eigen::Matrix<double,4,1,0,4,1>::operator=(const Eigen::Matrix<double,4,1,0,4,1> & other) Line 209
POCosseratRods.exe!Eigen::QuaternionBase<Eigen::Quaternion<double,0> >::operator=(const Eigen::QuaternionBase<Eigen::Quaternion<double,0> > & other) Line 486
POCosseratRods.exe!OrientationData::setLastQuaternion(const unsigned int i, const Eigen::Quaternion<double,0> & pos) Line 407
POCosseratRods.exe!TimeStepController::step(SimulationModel & model) Line 43
POCosseratRods.exe!RodScene::update() Line 117
POCosseratRods.exe!idlefunc() Line 40
freeglutd.dll!0fd8dd9c()    Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for freeglutd.dll]
POCosseratRods.exe!main(int argc, char * * argv) Line 90
[External Code]

This error happends accidently. Sometimes, it doesn't occur. I don't know if it has to do with alligenment.

I use Visual Studion 2013, Eigen 3.3.4 on Windows 10.

Body:
It is the problem with STL container. Here is the explanation.

To use std::vector with Eigen, an aligned allocator is necessary.

std::vector<Quaternionr,Eigen::aligned_allocator<Quaternionr>> m_lastQ;


问:
Using PHP to split a URL
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.

When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"

i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?

please le me know how this is accomplished or if you have more questions.

答:
A regular expression should do the trick, something like the below would work. This is what Django uses in their URL dispatcher</p>

```<code>r'^export/$'
</code>```

Title: Using PHP to split a URL

Body:
A regular expression should do the trick, something like the below would work. This is what Django uses in their URL dispatcher

r'^export/$'


问:
Function that returns a multiplication table fails with negative numbers
Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns

10.2 = 20

10.3 = 30

10.4 = 40

This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate

10.-4 = -40

10.-3 = -30

10.-2 = -20

10.-1 = -10

but it doesn't return anything. This is my code:

```<code>function tabmul(a,b,c){ \\function that generates the multiplication table
    var myarray = new Array();
    var x
    for(x=b; x<=c; x++){
        myarray[x - b] = a*x;
        document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
  tabmul(a,b,c);

} else {
    alert("The starting point is bigger than the ending point");
}
</code>```

答:
You are comparing strings. This is because prompt returns strings. you need to convert a,b,c to numbers. Also you are using wrong symbols for comments, you need to correct those.

function tabmul(a,b,c){ //function that generates the multiplication table
    a = Number(a);
    b = Number(b);
    c = Number(c);
    var myarray = new Array();
    var x
    for(x=b;x<=c;x++){
        myarray[x-b] = a*x;
        document.write(a+"."+x+"="+myarray[x-b]+"
")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
    alert("The starting point is bigger than the ending point");
}```

Body:
Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns

10.2 = 20

10.3 = 30

10.4 = 40

This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate

10.-4 = -40

10.-3 = -30

10.-2 = -20

10.-1 = -10

but it doesn't return anything. This is my code:

function tabmul(a,b,c){ \\function that generates the multiplication table
    var myarray = new Array();
    var x
    for(x=b; x<=c; x++){
        myarray[x - b] = a*x;
        document.write(a + "." + x + "=" + myarray[x - b] + "
")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
  tabmul(a,b,c);

} else {
    alert("The starting point is bigger than the ending point");
}

Body:
You are comparing strings. This is because prompt returns strings. you need to convert a,b,c to numbers. Also you are using wrong symbols for comments, you need to correct those.

function tabmul(a,b,c){ //function that generates the multiplication table
    a = Number(a);
    b = Number(b);
    c = Number(c);
    var myarray = new Array();
    var x
    for(x=b;x<=c;x++){
        myarray[x-b] = a*x;
        document.write(a+"."+x+"="+myarray[x-b]+"<br/>")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
    alert("The starting point is bigger than the ending point");
}


答:
You should also convert your input to a number using Number or parseInt to make sure it is numeric.

After that you can run into problems referring to an array by index using a negative number.

```<code>myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.
</code>```

For example take the following:

```<code>var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"
</code>```

You could convert it to a string:

```<code>myarray['"' + (x-b) + '"'] = a*x;
</code>```

Or you could just use push() and your indexes will start with zero.:

```<code> for(x=b;x<=c;x++){
    myarray.push(a*x);
    document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}
</code>```

Title: Function that returns a multiplication table fails with negative numbers

Body:
You should also convert your input to a number using Number or parseInt to make sure it is numeric.

After that you can run into problems referring to an array by index using a negative number.

myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.

For example take the following:

var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"

You could convert it to a string:

myarray['"' + (x-b) + '"'] = a*x;

Or you could just use push() and your indexes will start with zero.:

 for(x=b;x<=c;x++){
    myarray.push(a*x);
    document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}


问:
Method call asks for method as parameter
I'm pretty new to swift so this might be a really simple question, but I am trying to create a method that returns a list upon completion but when I try to call the method, it says I am missing the escaping parameter which I do not know how to satisfy.

Here is the method:

```<code>func fillFromFile(completionBlock: @escaping ([Asset_Content]) -> ()) {
    let url = "URL STRING"

    LoadJSONFile(from: url) { (result) in
        // The code inside this block would be called when LoadJSONFile is completed. this could happen very quickly, or could take a long time

        //.map is an easier way to transform/iterate over an array
        var newContentArray = [Asset_Content]()
        for json in result{
            let category = json["BIGCATEGORY"] as? String
            let diagnosis = json["DIAGNOSIS"] as? String
            let perspective = json["PERSPECTIVE"] as? String
            let name = json["NAME"] as? String
            let title = json["Title"] as? String
            let UnparsedTags = json["TAGS"] as? String
            let filename = json["FILENAME"] as? String

            let tagArray = UnparsedTags?.characters.split(separator: ",")
            for tag in tagArray!{
                if(!self.ListOfTags.contains(String(tag))){
                    self.ListOfTags.append(String(tag))
                }
            }

            let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
            // This is a return to the map closure. We are still in the LoadJSONFile completion block
            newContentArray.append(asset)

        }
        print("return count ", newContentArray.count)
        // This is the point at which the passed completion block is called.
        completionBlock(newContentArray)
    }
}
</code>```

here is the method call:

```<code>self.ListOfFiles = fillFromFile()
</code>```

and the error is "Missing argument for parameter 'completionblock' in call"

答:
Notice that the fillFromFile function doesn't return anything. It's an asynchronous function. This means that it does its work independently of the main control flow of the thread it was called from. It'll return (nothing) almost immediately, and perform its work some unknown time thereafter.

To obtain the result of this function, you're expected to given a completion handler. This is a closure that will be called by the code when it eventually completes its work. As a parameter to this closure, it will pass in the result of the work (an Array<Asset_Content>).

Here's simple example of how to satisfy this method signature:

```<code>fillFromFile { (response) in
    print(response)
}
</code>```

I suggest you read the language guide, especially its section on closures.

Body:
I'm pretty new to swift so this might be a really simple question, but I am trying to create a method that returns a list upon completion but when I try to call the method, it says I am missing the escaping parameter which I do not know how to satisfy.

Here is the method:

func fillFromFile(completionBlock: @escaping ([Asset_Content]) -> ()) {
    let url = "URL STRING"

    LoadJSONFile(from: url) { (result) in
        // The code inside this block would be called when LoadJSONFile is completed. this could happen very quickly, or could take a long time

        //.map is an easier way to transform/iterate over an array
        var newContentArray = [Asset_Content]()
        for json in result{
            let category = json["BIGCATEGORY"] as? String
            let diagnosis = json["DIAGNOSIS"] as? String
            let perspective = json["PERSPECTIVE"] as? String
            let name = json["NAME"] as? String
            let title = json["Title"] as? String
            let UnparsedTags = json["TAGS"] as? String
            let filename = json["FILENAME"] as? String

            let tagArray = UnparsedTags?.characters.split(separator: ",")
            for tag in tagArray!{
                if(!self.ListOfTags.contains(String(tag))){
                    self.ListOfTags.append(String(tag))
                }
            }

            let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
            // This is a return to the map closure. We are still in the LoadJSONFile completion block
            newContentArray.append(asset)

        }
        print("return count ", newContentArray.count)
        // This is the point at which the passed completion block is called.
        completionBlock(newContentArray)
    }
}

here is the method call:

self.ListOfFiles = fillFromFile()

and the error is "Missing argument for parameter 'completionblock' in call"

Body:
Notice that the fillFromFile function doesn't return anything. It's an asynchronous function. This means that it does its work independently of the main control flow of the thread it was called from. It'll return (nothing) almost immediately, and perform its work some unknown time thereafter.

To obtain the result of this function, you're expected to given a completion handler. This is a closure that will be called by the code when it eventually completes its work. As a parameter to this closure, it will pass in the result of the work (an Array<Asset_Content>).

Here's simple example of how to satisfy this method signature:

fillFromFile { (response) in
    print(response)
}

I suggest you read the language guide, especially its section on closures.


答:
Use the DateTime API to parse your string(s) initially

```<code>$dt = DateTime::createFromFormat('d-m-Y H:i', $fecha.' '.$hora);
$newDt = $dt->format('Y-m-d H:i');
</code>```

Demo ~ https://eval.in/827662

Title: Changed position from day and month converting strings to date

Body:
I am working on following issue in PHP.
I have these variables:

$fecha = "01-07-2017";

$hora = "11:30";

Now I want to create a date variable with format Y-m-d H:i.

For that I am using following code:

$newDate = date("Y-m-d H:i", strtotime($fecha.' '.$hora));

But I am getting the output:

echo $newDate = 2017-01-07 11:30

I need it to be: 2017-07-01 11:30

What am I doing wrong?

Body:
Use the DateTime API to parse your string(s) initially

$dt = DateTime::createFromFormat('d-m-Y H:i', $fecha.' '.$hora);
$newDt = $dt->format('Y-m-d H:i');

Demo ~ https://eval.in/827662


问:
Issue with Arduino code running Motors with H Bridge and Arduino according to the written code
So i have an issue in which when I run my code with my ultrasonic sensors, and h bridge with motors one motor spins at all times and the other spins every 6 seconds for 2 seconds but i don't know why. Any help?

Here is the code:

```<code>int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
int in5 = 6;
int in6 = 7;
int trig = 8;
int echol = 9;
int echor = 12;
int echof = 11;
long df, tf, dr, tr, dl, tl;
 void setup() {

  Serial.begin(9600);
    }

void loop() {

 pinMode (in1, OUTPUT);
 pinMode (in2, OUTPUT);
 pinMode (in3, OUTPUT);
 pinMode (in4, OUTPUT);
 pinMode (in5, OUTPUT);
 pinMode (in6, OUTPUT);
 pinMode (trig, OUTPUT);
 pinMode (echol, INPUT);
 pinMode (echor, INPUT);
 pinMode (echof, INPUT);

forward();

  digitalWrite (trig, HIGH);
  delay (0.01);
  tf = pulseIn (echof, HIGH);
  digitalWrite (trig, LOW);
  df = tf * 0.03156;

  if (df < 1.5){
  digitalWrite (trig, HIGH);
  delay (0.01);
  tr = pulseIn (echor, HIGH);
  tl = pulseIn (echol, HIGH);
  digitalWrite (trig, LOW);
  dr = tr * 0.03156;
  dl = tl * 0.03156;

   if (dr > dl) {

    right();
    delay (5000);
    forward();

  }
  else {

    left();
    delay (5000);
    forward();

  }

}

}

void forward(){
 digitalWrite (in1, HIGH);
 digitalWrite (in2, LOW);
 digitalWrite (in3, HIGH);
 digitalWrite (in4, LOW);
 digitalWrite (in5, HIGH);
 digitalWrite (in6, LOW);
}

void backward(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, HIGH);
  digitalWrite (in3, LOW);
  digitalWrite (in4, HIGH);
  digitalWrite (in5, LOW);
  digitalWrite (in6, HIGH);
}

void left(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, LOW);
  digitalWrite (in3, HIGH);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}

void right(){
  digitalWrite (in1, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in3, LOW);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}
</code>```

答:
First of all, you should move your pin setup in Setup(), there is no need to reinitialize pin i/o setup on every loop.

```<code>void Setup()
{
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
  pinMode (in5, OUTPUT);
  pinMode (in6, OUTPUT);
  pinMode (trig, OUTPUT);
  pinMode (echol, INPUT);
  pinMode (echor, INPUT);
  pinMode (echof, INPUT);
}
</code>```

From what I know about the H-Bridge module, they usually have 3 inputs per motor, of which only ONE should be on at a time.  I could not find any correlation to that effect ion your code....  This is a constraint, so you should organize your code around it.  It would make it easier to read and debug.  There is no debugger on the Arduino, so organizing code does help a lot.  And if you need more help, it will sure be a lot easier for others to understand what you code does.

```<code>void MotorA(int dir)
{
  // dir = 0 = STOP, +1 = Forward, -1 = Reverse
  digitalWrite(in1, dir > 0);
  digitalWrite(in2, dir == 0);      // You gave no details on the module
  digitalWrite(in3, dir < 0);       // you have. the actual logic may differ...
}

void MotorB(int dir)
{
  // dir = 0 = STOP, +1 = Forward, -1 = Reverse
  digitalWrite(in4, dir > 0);
  digitalWrite(in5, dir == 0);
  digitalWrite(in6, dir < 0);
}

void Stop()
{
  MotorA(0);
  MotorB(0);
}

void Forward()
{
  MotorA(+1);
  MotorB(+1);
}

void Reverse()
{
  MotorA(-1);
  MotorB(-1);
}

void Left()
{
  MotorA(+1);
  MotorB(-1);
}

void Right()
{
  MotorA(-1);
  MotorB(+1);
}
</code>```

May I also suggest you start with a simpler loop to start with, until you have the motors running?  Add one feature at a time.  This will help you get your project up and ready much faster in the end.

```<code>void Loop()
{
  Forward()
  delay(5000);
  Stop()
  delay(1000);
  Reverse();
  delay(1000);
 // ---
}
</code>```

Body:
So i have an issue in which when I run my code with my ultrasonic sensors, and h bridge with motors one motor spins at all times and the other spins every 6 seconds for 2 seconds but i don't know why. Any help?

Here is the code:

int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
int in5 = 6;
int in6 = 7;
int trig = 8;
int echol = 9;
int echor = 12;
int echof = 11;
long df, tf, dr, tr, dl, tl;
 void setup() {

  Serial.begin(9600);
    }

void loop() {

 pinMode (in1, OUTPUT);
 pinMode (in2, OUTPUT);
 pinMode (in3, OUTPUT);
 pinMode (in4, OUTPUT);
 pinMode (in5, OUTPUT);
 pinMode (in6, OUTPUT);
 pinMode (trig, OUTPUT);
 pinMode (echol, INPUT);
 pinMode (echor, INPUT);
 pinMode (echof, INPUT);

forward();

  digitalWrite (trig, HIGH);
  delay (0.01);
  tf = pulseIn (echof, HIGH);
  digitalWrite (trig, LOW);
  df = tf * 0.03156;

  if (df < 1.5){
  digitalWrite (trig, HIGH);
  delay (0.01);
  tr = pulseIn (echor, HIGH);
  tl = pulseIn (echol, HIGH);
  digitalWrite (trig, LOW);
  dr = tr * 0.03156;
  dl = tl * 0.03156;

   if (dr > dl) {

    right();
    delay (5000);
    forward();

  }
  else {

    left();
    delay (5000);
    forward();

  }

}

}

void forward(){
 digitalWrite (in1, HIGH);
 digitalWrite (in2, LOW);
 digitalWrite (in3, HIGH);
 digitalWrite (in4, LOW);
 digitalWrite (in5, HIGH);
 digitalWrite (in6, LOW);
}

void backward(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, HIGH);
  digitalWrite (in3, LOW);
  digitalWrite (in4, HIGH);
  digitalWrite (in5, LOW);
  digitalWrite (in6, HIGH);
}

void left(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, LOW);
  digitalWrite (in3, HIGH);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}

void right(){
  digitalWrite (in1, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in3, LOW);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}

Body:
First of all, you should move your pin setup in Setup(), there is no need to reinitialize pin i/o setup on every loop.

void Setup()
{
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
  pinMode (in5, OUTPUT);
  pinMode (in6, OUTPUT);
  pinMode (trig, OUTPUT);
  pinMode (echol, INPUT);
  pinMode (echor, INPUT);
  pinMode (echof, INPUT);
}

From what I know about the H-Bridge module, they usually have 3 inputs per motor, of which only ONE should be on at a time.  I could not find any correlation to that effect ion your code....  This is a constraint, so you should organize your code around it.  It would make it easier to read and debug.  There is no debugger on the Arduino, so organizing code does help a lot.  And if you need more help, it will sure be a lot easier for others to understand what you code does.

void MotorA(int dir)
{
  // dir = 0 = STOP, +1 = Forward, -1 = Reverse
  digitalWrite(in1, dir > 0);
  digitalWrite(in2, dir == 0);      // You gave no details on the module
  digitalWrite(in3, dir < 0);       // you have. the actual logic may differ...
}

void MotorB(int dir)
{
  // dir = 0 = STOP, +1 = Forward, -1 = Reverse
  digitalWrite(in4, dir > 0);
  digitalWrite(in5, dir == 0);
  digitalWrite(in6, dir < 0);
}

void Stop()
{
  MotorA(0);
  MotorB(0);
}

void Forward()
{
  MotorA(+1);
  MotorB(+1);
}

void Reverse()
{
  MotorA(-1);
  MotorB(-1);
}

void Left()
{
  MotorA(+1);
  MotorB(-1);
}

void Right()
{
  MotorA(-1);
  MotorB(+1);
}

May I also suggest you start with a simpler loop to start with, until you have the motors running?  Add one feature at a time.  This will help you get your project up and ready much faster in the end.

void Loop()
{
  Forward()
  delay(5000);
  Stop()
  delay(1000);
  Reverse();
  delay(1000);
 // ---
}


问:
Getting Inconsistent data from multi-node memcached cluster AWS
I am using Moodle 2.7.2 for our application on load balanced environment. I am using AWS elastic cache memcached cluster with multiple node.

Whenever i am doing any confrontational changes or database update, on front-end some times new changes reflects but some time old data are displayed.

I researched about this issue and found that i should set

memcached.sess_consistent_hash=On

I changes this and restarted the server but still i am getting inconsistent data.

答:
I guess the problem you have to solve is the cache and permanent storage updates when you have dirty data.

The consistenthash parameter is for how the data should be distributed in cluster.

For your problem, there are various strategies for this like write-back, write-through, write-around. Typically if consistency and durability are important, one will choose write-through. Also, for lots of read and less write operations - write-through is a good fit.

Hope it helps!


问:
Loading Facebook pixel async
I'm loading the Facebook pixel and getting an error because the script isn't loaded when the call is made. This is what it looks like:

```<code>function Load3rdPartyScripts() {

    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); //problem here
    fbq('track', 'PageView');

}
</code>```

Problem is that fbq isn't initiated when the code runs. Now I know I could wrap the problem code inside a setInterval and keep checking until the external script is fully loaded but I'm wondering if there's a better way to do it.

答:
I tried to reproduce this problem but in vain. Your code works perfectly.
fbq is appended syncronously (So no need to timeout) to window and will be called normally. Check yourself:

(function Load3rdPartyScripts() {

    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); // No problem here!
    fbq('track', 'PageView');

})();```
</div>
</div>
</p>

<h2><strong>But</strong></h2>

<p>There are some potential reasons that may produce your error:</p>

<ol>
<li><p>Running the script outside the browser, An env that ruined the window variable.</p></li>
<li><p>Running code on browser but with a freezed <code>window</code> (<code>Object.freeze(window)</code>) causes that <code>fbq</code> will be <code>undefined</code></p></li>
<li><p>So also <code>Object.seal(window)</code> like <code>freeze()</code>. It will prevent new properties from being added to <code>window</code></p></li>
<li><p>Creating a <strong>local</strong> scope <strong>named</strong> <code>window</code> variable will cause <code>fbq</code> to be <code>undefined</code></p>

```function Load3rdPartyScripts() {
    let window = {};  // Notice!
    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); //problem here
    fbq('track', 'PageView');

}
Load3rdPartyScripts();
```

Title: Loading Facebook pixel async

Body:
I'm loading the Facebook pixel and getting an error because the script isn't loaded when the call is made. This is what it looks like:

function Load3rdPartyScripts() {

    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); //problem here
    fbq('track', 'PageView');

}

Problem is that fbq isn't initiated when the code runs. Now I know I could wrap the problem code inside a setInterval and keep checking until the external script is fully loaded but I'm wondering if there's a better way to do it.

Body:
I tried to reproduce this problem but in vain. Your code works perfectly.
fbq is appended syncronously (So no need to timeout) to window and will be called normally. Check yourself:

(function Load3rdPartyScripts() {

    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); // No problem here!
    fbq('track', 'PageView');

})();

But

There are some potential reasons that may produce your error:

Running the script outside the browser, An env that ruined the window variable.

Running code on browser but with a freezed window (Object.freeze(window)) causes that fbq will be undefined

So also Object.seal(window) like freeze(). It will prevent new properties from being added to window

Creating a local scope named window variable will cause fbq to be undefined

function Load3rdPartyScripts() {
    let window = {};  // Notice!
    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js', undefined, undefined, undefined);

    fbq('init', 'XXXXXXXXXXXXX'); //problem here
    fbq('track', 'PageView');

}
Load3rdPartyScripts();


问:
was ruby sdk: how to find instances without missing name tag
To list ec2 instances without a name tag, I tried

```<code># resource interface
ec2 = Aws::EC2::Resource.new
ec2.instances(filters:[{name:'tag:Name', values:[]}]).each do |instance|
   # ...
end
</code>```

Any idea how to do this?

[1] https://forums.aws.amazon.com/thread.jspa?messageID=740190

答: Try iterating over all instances the API returns, with an unless to catch instances that don't have the tag you're seeking. Operate within that conditional.

Body:
To list ec2 instances without a name tag, I tried

# resource interface
ec2 = Aws::EC2::Resource.new
ec2.instances(filters:[{name:'tag:Name', values:[]}]).each do |instance|
   # ...
end

Any idea how to do this?

[1] https://forums.aws.amazon.com/thread.jspa?messageID=740190


问:
How to get actual HTML elements in Chrome extension, not original source code
I am making a Chrome extension,

In Chrome's Inspect Elements panel, at the bottom will show all elements of the HTML page.

How can I get all those elements in JavaScript?

The page's original source code not include all of the elements.

How can I get all elements shown in Inspect Elements in my Chrome extension?

See these pictures: this one is the elements I want, and this one is the original source code.

答:
Any elements that you see in the JavaScript inspector, but not in the HTML source code, are either (a) automatically added by the browser to normalize the any missing elements (i.e. no  tag) or correcting invalid structure (i.e. unclosed
 tag) to make the document valid, or (b) added by JavaScript.

Any technique you use to inspect the document from your Chrome extension will automatically see the document as you see it in the document inspector. You don't need to do anything specific. All of the elements that have been created by the browser or by JavaScript will be there. For example, you could use document.querySelectorAll('*') to get an array-like object containing all of them, or document.body.outerHTML to get the HTML code.

The harder task would actually be if you wanted to get the original, uncorrected source code.

Body:
Any elements that you see in the JavaScript inspector, but not in the HTML source code, are either (a) automatically added by the browser to normalize the any missing elements (i.e. no <body> tag) or correcting invalid structure (i.e. unclosed <p> tag) to make the document valid, or (b) added by JavaScript.

Any technique you use to inspect the document from your Chrome extension will automatically see the document as you see it in the document inspector. You don't need to do anything specific. All of the elements that have been created by the browser or by JavaScript will be there. For example, you could use document.querySelectorAll('*') to get an array-like object containing all of them, or document.body.outerHTML to get the HTML code.

The harder task would actually be if you wanted to get the original, uncorrected source code.


问:
fade in and fade out div onclick with jQuery
I have a div on left and right of the page. Currently the div on the right is being hidden.

I'm trying to use jQuery to fadeout the div that is currently being displayed and replace it by fading in the hidden div.

What am I doing wrong? I followed the example on this similar question.

It should happen when you click the About link in the code snippet:

$("a").on('click', function() {
  $("#feed-show").fadeIn();
  $(".feed").fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: rgba(255, 80, 70, 1) !important;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255, 80, 70, 1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float: left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255, 80, 70, 1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float: left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top: 2.5%;
}

.feed-show {
  position: absolute !important;
  top: -9999px !important;
  left: -9999px !important;
  background: red;
}</code>```

    About

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.

      Find out more about Creatives of Colour..

        Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.

        Find out more about Creatives of Colour..

```

Here is a codepen

Many thanks!

答:
I have maded some modifications to your code:

I have changed position:absolute to keep hidden #feed-show with display:none

I have changed inside click function fadeIn to be executed when fadeOut is finish to avoid strange moving effect

$(document).ready(function(){
  $("#feed-show").fadeOut(0);
  $("a").on('click', function() {

     $(".feed").fadeOut(1000,function(){
        $("#feed-show").fadeIn(1000);
     });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    a {
    color: rgba(255,80,70,1) !important ;
    text-decoration: none;
}

.nav a {
    font-size: 13px;
    color: rgba(255,80,70,1);
    text-decoration: none;
    font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
    position: fixed;
    float:left;
    width: 96%;
    left: 2%;
    margin-left: -2px;
    border-bottom: 2px solid rgba(255,80,70,1);
    padding-bottom: 18px;
    background: white;
    z-index: 999;
    top: 0px;
    padding-top: 18px;
}

.c1 {
    max-width: 24%;
}

.column {
    position: relative;
    float:left;
    padding-right: 1%;
    width: 585px;
}

/* feed */
.feed {
    width: 96%;
    left: 2%;
    margin-top: 75px;
    padding-left: 2px;
}

.c2 {
    max-width: 49%;
}

.feed-item {
    position: relative;
    width: 100%;
    height: auto;
    padding-bottom: 25px;
    padding-top:2.5%;
}
#feed-show{
  display:none;
}
#feed-show p{

   background:red;
}</code>```

                About

                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.

                    Find out more about Creatives of Colour..

       OCULT TEXT
                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK.

                    Find out more about Creatives of Colour..

```

Body:
I have a div on left and right of the page. Currently the div on the right is being hidden.

I'm trying to use jQuery to fadeout the div that is currently being displayed and replace it by fading in the hidden div.

What am I doing wrong? I followed the example on this similar question.

It should happen when you click the About link in the code snippet:

$("a").on('click', function() {
  $("#feed-show").fadeIn();
  $(".feed").fadeOut();
});

a {
  color: rgba(255, 80, 70, 1) !important;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255, 80, 70, 1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float: left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255, 80, 70, 1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float: left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top: 2.5%;
}

.feed-show {
  position: absolute !important;
  top: -9999px !important;
  left: -9999px !important;
  background: red;
}

    About

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.

      Find out more about Creatives of Colour..

        Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.

        Find out more about Creatives of Colour..

Here is a codepen

Many thanks!

Body:
I have maded some modifications to your code:

I have changed position:absolute to keep hidden #feed-show with display:none

I have changed inside click function fadeIn to be executed when fadeOut is finish to avoid strange moving effect

$(document).ready(function(){
  $("#feed-show").fadeOut(0);
  $("a").on('click', function() {

     $(".feed").fadeOut(1000,function(){
        $("#feed-show").fadeIn(1000);
     });
  });
});

    a {
    color: rgba(255,80,70,1) !important ;
    text-decoration: none;
}

.nav a {
    font-size: 13px;
    color: rgba(255,80,70,1);
    text-decoration: none;
    font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
    position: fixed;
    float:left;
    width: 96%;
    left: 2%;
    margin-left: -2px;
    border-bottom: 2px solid rgba(255,80,70,1);
    padding-bottom: 18px;
    background: white;
    z-index: 999;
    top: 0px;
    padding-top: 18px;
}

.c1 {
    max-width: 24%;
}

.column {
    position: relative;
    float:left;
    padding-right: 1%;
    width: 585px;
}

/* feed */
.feed {
    width: 96%;
    left: 2%;
    margin-top: 75px;
    padding-left: 2px;
}

.c2 {
    max-width: 49%;
}

.feed-item {
    position: relative;
    width: 100%;
    height: auto;
    padding-bottom: 25px;
    padding-top:2.5%;
}
#feed-show{
  display:none;
}
#feed-show p{

   background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
            <div class="column c1">
                <a href="#" rel="click">About</a>
            </div>

        </div>
<div id="container">
        <div id="feed" class="feed" style="margin-top: 54px;">

            <div class="column c2">
                <p>
                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.
                </p>
                <p>
                    <a href="#">Find out more about Creatives of Colour..</a>
                </p>
            </div>
   </div>
    <!-- Show on click -->

    <div id="feed-show" class="feed-show" style="margin-top: 54px;">

            <div class="column c2">
                <p>
       OCULT TEXT
                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK.
                </p>
                <p>
                    <a href="#">Find out more about Creatives of Colour..</a>
                </p>
            </div>

        </div>
 </div>


问:
"Safe" TO_NUMBER()
```<code>SELECT TO_NUMBER('*') FROM DUAL
</code>```

This obviously gives me an exception:

ORA-01722: invalid number

Is there a way to "skip" it and get 0 or NULL instead?

The whole issue: I have NVARCHAR2 field, which contains numbers and not almost ;-) (like *) and I need to select the biggest number from the column.

Yes, I know it is a terrible design, but this is what I need now... :-S

UPD:

For myself I've solved this issue with

```<code>COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+')), 0)
</code>```

答:
It's probably a bit messy rolling your own regexp to test for a number, but the code below might work. I think the other solution by Gabe involving a user defined function is more robust since you are using the built in Oracle functionality (and my regexp is probably not 100% correct) but it might be worth a go:

```<code>with my_sample_data as (
  select '12345' as mynum from dual union all
  select '54-3' as mynum from dual union all
  select '123.4567' as mynum from dual union all
  select '.34567' as mynum from dual union all
  select '-0.3462' as mynum from dual union all
  select '0.34.62' as mynum from dual union all
  select '1243.64' as mynum from dual
)
select
  mynum,
  case when regexp_like(mynum, '^-?\d+(\.\d+)?$')
    then to_number(mynum) end as is_num
from my_sample_data
</code>```

This will then give the following output:

```<code>MYNUM   IS_NUM
-------- ----------
12345   12345
54-3
123.4567    123.4567
.34567
-0.3462 -0.3462
0.34.62
1243.64 1243.64
</code>```

Title: "Safe" TO_NUMBER()

Body:
SELECT TO_NUMBER('*') FROM DUAL

This obviously gives me an exception:

ORA-01722: invalid number

Is there a way to "skip" it and get 0 or NULL instead?

The whole issue: I have NVARCHAR2 field, which contains numbers and not almost ;-) (like *) and I need to select the biggest number from the column.

Yes, I know it is a terrible design, but this is what I need now... :-S

UPD:

For myself I've solved this issue with

COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+')), 0)

Body:
It's probably a bit messy rolling your own regexp to test for a number, but the code below might work. I think the other solution by Gabe involving a user defined function is more robust since you are using the built in Oracle functionality (and my regexp is probably not 100% correct) but it might be worth a go:

with my_sample_data as (
  select '12345' as mynum from dual union all
  select '54-3' as mynum from dual union all
  select '123.4567' as mynum from dual union all
  select '.34567' as mynum from dual union all
  select '-0.3462' as mynum from dual union all
  select '0.34.62' as mynum from dual union all
  select '1243.64' as mynum from dual
)
select
  mynum,
  case when regexp_like(mynum, '^-?\d+(\.\d+)?$')
    then to_number(mynum) end as is_num
from my_sample_data

This will then give the following output:

MYNUM   IS_NUM
-------- ----------
12345   12345
54-3
123.4567    123.4567
.34567
-0.3462 -0.3462
0.34.62
1243.64 1243.64


问:
The request signature we calculated does not match the signature you provided. S3 Bucket Http Post
I am trying to upload an image to an s3 bucket using HTTP post method following the tutorial http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html. But I am getting the following error every time

```<code> Error
 <Code>SignatureDoesNotMatch</Code>
 <Message>
 The request signature we calculated does not match the signature you
 provided. Check your key and signing method.
  </Message>
</code>```

To make the request I've got the following form:

```<code> <form action="http://mynewdulibucket.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
Key to upload:
<input type="input"  name="key" value="user/user1/${filename}" /><br />
<input type="hidden" name="acl" value="public-read" />
<input type="hidden" name="success_action_redirect" value="http://mynewdulibucket.s3.amazonaws.com/successful_upload.html" />
Content-Type:
<input type="input"  name="Content-Type" value="image/jpeg" /><br />
<input type="hidden" name="x-amz-meta-uuid" value="14365123651274" />
<input type="hidden" name="x-amz-server-side-encryption" value="AES256" />
<input type="text"   name="X-Amz-Credential" value="XXXXXXXXXXXXX/20151229/us-east-1/s3/aws4_request" />
<input type="text"   name="X-Amz-Algorithm" value="AWS4-HMAC-SHA256" />
<input type="text"   name="X-Amz-Date" value="20151229T000000Z" />

Tags for File:
<input type="input"  name="x-amz-meta-tag" value="" /> <br />
<input type="hidden" name="Policy" value="XXXXXXXXXXXXXXX"/>
<input type="hidden" name="X-Amz-Signature" value="XXXXXXXXXXXXX" />
File:
<input type="file"   name="file" /> <br />
<!-- The elements after this will be ignored -->
<input type="submit" name="submit" value="Upload to Amazon S3" />
</code>```

The policy is the following:

```<code>{ "expiration": "2018-12-30T12:00:00.000Z",
 "conditions": [
{"bucket": "mynewdulibucket"},
["starts-with", "$key", "user/user1/MyPhoto.jpg"],
{"acl": "public-read"},
{"success_action_redirect": "http://mynewdulibucket.s3.amazonaws.com/successful_upload.html"},
["starts-with", "$Content-Type", "image/"],
{"x-amz-meta-uuid": "14365123651274"},
{"x-amz-server-side-encryption": "AES256"},
["starts-with", "$x-amz-meta-tag", ""],
{"x-amz-credential": "XXXXXXXXX/20151229/us-east-1/s3/aws4_request"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": "20151229T000000Z" }
]
  }
</code>```

And the code to generate the policy and signature which I then paste into the relevant form fields is:

```<code>public class Main {

public static void main(String[] args) throws Exception
{
    String policy_document = "{\"expiration\":\"2018-12-30T12:00:00.000Z\",\"conditions\":[{\"bucket\":\"mynewdulibucket\"},[\"starts-with\",\"$key\",\"user/user1/MyPhoto.jpg\"],{\"acl\":\"public-read\"},{\"success_action_redirect\":\"http://mynewdulibucket.s3.amazonaws.com/successful_upload.html\"},[\"starts-with\",\"$Content-Type\",\"image/\"],{\"x-amz-meta-uuid\":\"14365123651274\"},{\"x-amz-server-side-encryption\":\"AES256\"},[\"starts-with\",\"$x-amz-meta-tag\",\"\"],{\"x-amz-credential\":\"AKIAJQHQNWQ7FCTGNKQQ/20151229/us-east-1/s3/aws4_request\"},{\"x-amz-algorithm\":\"AWS4-HMAC-SHA256\"},{\"x-amz-date\":\"20151229T000000Z\"}]}";
    String encodedPolicy = new String(Base64.getEncoder().encode(policy_document.getBytes("UTF-8"))).replaceAll("\n", "").replaceAll("\r", "");
    String secretKey = "XXXXXXXXXXXXXXXX";

    String signature = getSigning(secretKey, "20151229T000000Z", "us-east-1", "s3",encodedPolicy);

    //the following values get pasted into the form fields Policy and X-Amz-Signature respectively (see above XXXXX)
    System.out.println("base64 " + encodedPolicy);

    System.out.println("signature " + signature);

}

static byte[] HmacSHA256(String data, byte[] key) throws Exception
{
    String algorithm="HmacSHA256";
    Mac mac = Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key, algorithm));
    return mac.doFinal(data.getBytes("UTF8"));
}

static String getSigning(String key, String dateStamp, String regionName, String serviceName,String base64signature) throws Exception {
    byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
    byte[] kDate = HmacSHA256(dateStamp, kSecret);
    byte[] kRegion = HmacSHA256(regionName, kDate);
    byte[] kService = HmacSHA256(serviceName, kRegion);
    //
    byte[] kSigning = HmacSHA256("aws4_request", kService);

    byte[] signature = HmacSHA256(base64signature, kSigning);

    return new String(Base64.getEncoder().encode(signature));
}
</code>```

答:
This misleading error shows up when you haven’t authenticated properly.

Validate that either:

your ~/.aws/config is correct.

you’re providing API keys properly at invocation time.

your environment variables are passing your credentials properly.

the instance you’re running this from has the proper permissions assigned to its IAM role.

Body:
I am trying to upload an image to an s3 bucket using HTTP post method following the tutorial http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html. But I am getting the following error every time

 Error
 SignatureDoesNotMatch
 <Message>
 The request signature we calculated does not match the signature you
 provided. Check your key and signing method.
  </Message>

To make the request I've got the following form:

 <form action="http://mynewdulibucket.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
Key to upload:
<input type="input"  name="key" value="user/user1/${filename}" />

<input type="hidden" name="acl" value="public-read" />
<input type="hidden" name="success_action_redirect" value="http://mynewdulibucket.s3.amazonaws.com/successful_upload.html" />
Content-Type:
<input type="input"  name="Content-Type" value="image/jpeg" />

<input type="hidden" name="x-amz-meta-uuid" value="14365123651274" />
<input type="hidden" name="x-amz-server-side-encryption" value="AES256" />
<input type="text"   name="X-Amz-Credential" value="XXXXXXXXXXXXX/20151229/us-east-1/s3/aws4_request" />
<input type="text"   name="X-Amz-Algorithm" value="AWS4-HMAC-SHA256" />
<input type="text"   name="X-Amz-Date" value="20151229T000000Z" />

Tags for File:
<input type="input"  name="x-amz-meta-tag" value="" />

<input type="hidden" name="Policy" value="XXXXXXXXXXXXXXX"/>
<input type="hidden" name="X-Amz-Signature" value="XXXXXXXXXXXXX" />
File:
<input type="file"   name="file" />

<input type="submit" name="submit" value="Upload to Amazon S3" />

The policy is the following:

{ "expiration": "2018-12-30T12:00:00.000Z",
 "conditions": [
{"bucket": "mynewdulibucket"},
["starts-with", "$key", "user/user1/MyPhoto.jpg"],
{"acl": "public-read"},
{"success_action_redirect": "http://mynewdulibucket.s3.amazonaws.com/successful_upload.html"},
["starts-with", "$Content-Type", "image/"],
{"x-amz-meta-uuid": "14365123651274"},
{"x-amz-server-side-encryption": "AES256"},
["starts-with", "$x-amz-meta-tag", ""],
{"x-amz-credential": "XXXXXXXXX/20151229/us-east-1/s3/aws4_request"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": "20151229T000000Z" }
]
  }

And the code to generate the policy and signature which I then paste into the relevant form fields is:

public class Main {

public static void main(String[] args) throws Exception
{
    String policy_document = "{\"expiration\":\"2018-12-30T12:00:00.000Z\",\"conditions\":[{\"bucket\":\"mynewdulibucket\"},[\"starts-with\",\"$key\",\"user/user1/MyPhoto.jpg\"],{\"acl\":\"public-read\"},{\"success_action_redirect\":\"http://mynewdulibucket.s3.amazonaws.com/successful_upload.html\"},[\"starts-with\",\"$Content-Type\",\"image/\"],{\"x-amz-meta-uuid\":\"14365123651274\"},{\"x-amz-server-side-encryption\":\"AES256\"},[\"starts-with\",\"$x-amz-meta-tag\",\"\"],{\"x-amz-credential\":\"AKIAJQHQNWQ7FCTGNKQQ/20151229/us-east-1/s3/aws4_request\"},{\"x-amz-algorithm\":\"AWS4-HMAC-SHA256\"},{\"x-amz-date\":\"20151229T000000Z\"}]}";
    String encodedPolicy = new String(Base64.getEncoder().encode(policy_document.getBytes("UTF-8"))).replaceAll("\n", "").replaceAll("\r", "");
    String secretKey = "XXXXXXXXXXXXXXXX";

    String signature = getSigning(secretKey, "20151229T000000Z", "us-east-1", "s3",encodedPolicy);

    //the following values get pasted into the form fields Policy and X-Amz-Signature respectively (see above XXXXX)
    System.out.println("base64 " + encodedPolicy);

    System.out.println("signature " + signature);

}

static byte[] HmacSHA256(String data, byte[] key) throws Exception
{
    String algorithm="HmacSHA256";
    Mac mac = Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key, algorithm));
    return mac.doFinal(data.getBytes("UTF8"));
}

static String getSigning(String key, String dateStamp, String regionName, String serviceName,String base64signature) throws Exception {
    byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
    byte[] kDate = HmacSHA256(dateStamp, kSecret);
    byte[] kRegion = HmacSHA256(regionName, kDate);
    byte[] kService = HmacSHA256(serviceName, kRegion);
    //
    byte[] kSigning = HmacSHA256("aws4_request", kService);

    byte[] signature = HmacSHA256(base64signature, kSigning);

    return new String(Base64.getEncoder().encode(signature));
}


问:
Django REST Framework Filter Queryset Based On URL
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

```<code>class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)
</code>```

Here's my serializer:

```<code>class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')
</code>```

And here's the CompanyProductField

```<code>class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)
</code>```

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

答:
For now, I'm going to use this somewhat "hacky" way of doing this.

In my serializers.py file I added a global variable:

```<code>from rest_framework import serializers
from .models import *
from django.db.models import Q

global_company_id = 0
</code>```

Then in the init method for my serializer I set the global_company_id:

```<code>class InquirySerializer(serializers.ModelSerializer):
def __init__(self, *args, company_id=None, **kwargs):
    super(InquirySerializer, self).__init__(*args, **kwargs)
    company_set = Company.objects.filter(pk=company_id)
    self.fields['company'].queryset = company_set
    global global_company_id
    global_company_id = company_id

company = serializers.HyperlinkedRelatedField(many=False,
                                              view_name='company-detail',
                                              queryset=Company.objects.all())
inquirer = UserPKField(many=False)
is_anonymous = serializers.BooleanField
product_rows = CompanyProductField(many=True)
</code>```

And in the CompanyProductField I accessed the global_company_id:

```<code>class CompanyProductField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
    product_query = Q(company__pk=global_company_id)
    return Product.objects.filter(product_query)
</code>```

Body:
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)

Here's my serializer:

class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')

And here's the CompanyProductField

class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

Body:
For now, I'm going to use this somewhat "hacky" way of doing this.

In my serializers.py file I added a global variable:

from rest_framework import serializers
from .models import *
from django.db.models import Q

global_company_id = 0

Then in the init method for my serializer I set the global_company_id:

class InquirySerializer(serializers.ModelSerializer):
def __init__(self, *args, company_id=None, **kwargs):
    super(InquirySerializer, self).__init__(*args, **kwargs)
    company_set = Company.objects.filter(pk=company_id)
    self.fields['company'].queryset = company_set
    global global_company_id
    global_company_id = company_id

company = serializers.HyperlinkedRelatedField(many=False,
                                              view_name='company-detail',
                                              queryset=Company.objects.all())
inquirer = UserPKField(many=False)
is_anonymous = serializers.BooleanField
product_rows = CompanyProductField(many=True)

And in the CompanyProductField I accessed the global_company_id:

class CompanyProductField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
    product_query = Q(company__pk=global_company_id)
    return Product.objects.filter(product_query)


问:
php error with correct syntax: Warning: Cannot modify header information - headers already sent by
It gives me this error

Full Header

Full Settings.php

```<code>Warning: Cannot modify header information - headers already sent by (output started at /media/maksim/LENOVO/github/server/pages/settings.php:34) in /media/maksim/LENOVO/github/server/pages/header.php on line 211
</code>```

Here is that line of code and I know it has to be that one because it works when I remove it.

```<code><option value="0" <?php if ($nightthemeis == 0) {echo "selected";} ?> >Off</option>
</code>```

答:
You have got to be using the echo statement before :

```<code>header(), session_start(), setcookie()
</code>```

when it should be afterward,

Body:
It gives me this error

Full Header

Full Settings.php

Warning: Cannot modify header information - headers already sent by (output started at /media/maksim/LENOVO/github/server/pages/settings.php:34) in /media/maksim/LENOVO/github/server/pages/header.php on line 211

Here is that line of code and I know it has to be that one because it works when I remove it.

<option value="0" <?php if ($nightthemeis == 0) {echo "selected";} ?> >Off</option>

Body:
You have got to be using the echo statement before :

header(), session_start(), setcookie()

when it should be afterward,


问:
Is there syntax just like #region #endregion in Kotlin?
I know I can use #region #endregion to surround a code snippets in C#, is there a similar syntax in Kotlin? Thanks!</p>

```<code>   #region MyRegion
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    #endregion
</code>```

答:
In IntelliJ IDEA (or Android Studio): yes, you can. You can do it by using //region and //endregion comments or by using //<editor-fold desc="..."> and //</editor-fold>.

Example:

```<code>//region name

fun someCode() { ... }
fun someMoreCode() { ... }

//endregion

// or

//<editor-fold desc="name">

fun someCode() { ... }
fun someMoreCode() { ... }

//</editor-fold>
</code>```

Body:
I know I can use #region #endregion to surround a code snippets in C#, is there a similar syntax in Kotlin? Thanks!

   #region MyRegion
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    #endregion

Body:
In IntelliJ IDEA (or Android Studio): yes, you can. You can do it by using //region and //endregion comments or by using //<editor-fold desc="..."> and //</editor-fold>.

Example:

//region name

fun someCode() { ... }
fun someMoreCode() { ... }

//endregion

// or

//<editor-fold desc="name">

fun someCode() { ... }
fun someMoreCode() { ... }

//</editor-fold>