问:
ArrayMap put method pushes elements in strange order
I am using ArrayMap for first time in my project and I thought it works just like an array. I expected when I use .put method it inserts it at next index.
But in my case this is not true - after I added all elements one by one the first element I added ended up at index 4 which is kind of strange.

Here are the first three steps which I add elements:

1 - Salads:

2 - Soups:

3 - Appetizers:

So somehow on second step "Soup" element was inserted in index 0 instead of 1 as I was expecting, but strangely on third step "Appetizers" was inserted as expected after "Soup".

This is the code I am using to push key and value pair:

```<code>function ArrayMap<String, DMType> addElement(String typeKey, DMType type) {
    ArrayMap<String, DMType> types = new ArrayMap<>();
    types.put(typeKey, type);

    return types;
}
</code>```

Am I missing something about the behavior of ArrayMap?

答:
ArrayMap does NOT work like an Array, instead, it works like a HashMap with performance optimizations.

The internal sequence of the key-value pair is not guaranteed as it is NOT part of the contract.

In your case, what you really want to use is probably an ArrayList<Element>, where the Element class is defined like this:

```<code>public class Element{
    private final String typeKey;
    private final DMType type;
    public Element(String typeKey, DMType type){
           this.typeKey = typeKey;
           this.type = type;
    }
}
</code>```

If you don't want a new Class just to store the result, and you want to keep the sequence, you can use a LinkedHashMap<String, DMType>. As the document specifies:

Class LinkedHashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Body:
I am using ArrayMap for first time in my project and I thought it works just like an array. I expected when I use .put method it inserts it at next index.
But in my case this is not true - after I added all elements one by one the first element I added ended up at index 4 which is kind of strange.

Here are the first three steps which I add elements:

1 - Salads:

2 - Soups:

3 - Appetizers:

So somehow on second step "Soup" element was inserted in index 0 instead of 1 as I was expecting, but strangely on third step "Appetizers" was inserted as expected after "Soup".

This is the code I am using to push key and value pair:

function ArrayMap<String, DMType> addElement(String typeKey, DMType type) {
    ArrayMap<String, DMType> types = new ArrayMap<>();
    types.put(typeKey, type);

    return types;
}

Am I missing something about the behavior of ArrayMap?

Body:
ArrayMap does NOT work like an Array, instead, it works like a HashMap with performance optimizations.

The internal sequence of the key-value pair is not guaranteed as it is NOT part of the contract.

In your case, what you really want to use is probably an ArrayList<Element>, where the Element class is defined like this:

public class Element{
    private final String typeKey;
    private final DMType type;
    public Element(String typeKey, DMType type){
           this.typeKey = typeKey;
           this.type = type;
    }
}

If you don't want a new Class just to store the result, and you want to keep the sequence, you can use a LinkedHashMap<String, DMType>. As the document specifies:

Class LinkedHashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)


来源: stackexchange

问:
how to find specific class through all child elements and if available then hide that child element?
I have one scenario, where I have to go through all the child elements and check if there is a specific class is available or not. If it's available, then hide that specific element. This is my html code:

```<code><div id="toolbar">
    <ul class="nav navbar-nav">
        <li class="topnav"></li>
        <li class="topnav"></li>
        <li class="topnav"></li>
        <li class="topnav all"></li>
    </ul>
</div>
</code>```

Now, I am able to check if any child elements has class all or not, using this code:

```<code>$('#toolbar ul').find('li').hasClass('all')
</code>```

And I am getting true. Now, I want to hide that specific element, which has all class. I have tried with this code:

```<code>if($('#toolbar ul').find('li').hasClass('all')) $(this).hide();
</code>```

But, didn't get success. So, kindly guide me here, on how to do this. Thanks.

答:
You're very close with the following code
$('#toolbar ul').find('li').hasClass('all')

Just change that one line into this
$('#toolbar ul').find('.all').hide()

That will hide all descendants inside the ul with the classname .all

.find(): Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

ContentLicense: CC BY-SA 3.0

Body:
I have one scenario, where I have to go through all the child elements and check if there is a specific class is available or not. If it's available, then hide that specific element. This is my html code:

Now, I am able to check if any child elements has class all or not, using this code:

$('#toolbar ul').find('li').hasClass('all')

And I am getting true. Now, I want to hide that specific element, which has all class. I have tried with this code:

if($('#toolbar ul').find('li').hasClass('all')) $(this).hide();

But, didn't get success. So, kindly guide me here, on how to do this. Thanks.


问:
What does onDelete('cascade') mean?

Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
```

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?

答:
The short answer is: in your case if you deleted a user, all posts related to him will be deleted too.

onDelete('cascade'); simply adds the ON DELETE CASCADE rule to your database which specifies that the child data gets deleted when the parent data is deleted.

Note: take care of the typo (double semicolon)

```<code>$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
</code>```

Also, the Laravel function uses delete cascade

```<code>`$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
</code>```

ContentLicense: CC BY-SA 4.0

Title: What does onDelete('cascade') mean?

Body:
Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?

Body:
The short answer is: in your case if you deleted a user, all posts related to him will be deleted too.

onDelete('cascade'); simply adds the ON DELETE CASCADE rule to your database which specifies that the child data gets deleted when the parent data is deleted.

Note: take care of the typo (double semicolon)

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Also, the Laravel function uses delete cascade

`$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();


问:
Shortcut for calling all the setter methods on an object in Eclipse?
I want to create an object of a class in and then set all the properties in it using setter methods. There are more than 150 setter methods and I do want to type each one of them or even type in the object instance name Object instance type in dot . and then hit the spacebar for Eclipse to give me suggestions and then go and select the setter method. I do not want to do that 150 times.

Thus, I was looking for some sort of shortcut in Eclipse that allows you to call all the setters on the method. So like you type in the instance name and Eclipse calls all the setter methods e.g.

instanceName.setterOne("valOne");

instanceName.setterTwo("valOne");

instanceName.setterThree("valOne");

I cannot create another constructor in the the class, I am not allowed to do so

答:
Here are some tips I used -

Ctrl+Shift+A - > eclipse block selection (this is the magic tool 01)

Ctrl + F -> eclipse find/ find and replace ( magic tool 02)

Ctrl +Shift + X -> to upper case (tool 03)

Here how I did

block selection -> select all field names (tool 01)
Ex : user

select all first letters and make the first letter uppercase (tool 01/03)

Ex : User

select all and put the word set (tool 01)
 Ex: setUser

Align all fields nicely in line. So you can use the block selector straight

select all and set "();"
Ex:  setUser();

now you have all the setters ready

When you want to insert a value inside parentheses you can use magic tool 02. Find and replace ( think a little and you will see an option )

Finally, save your time of boredom from getters/setters settings.

cheers !


问:
Media query (max-width) not work properly in firefox
I have an issue with max-width media query. In this if i am use that media query:

```<code>@media only screen and (min-width: 320px) and (max-width: 480px) {
}
</code>```

Then its not work on 480px resolution. But if i am use that media query:

```<code>@media only screen and (min-width: 320px) and (max-width: 640px) {
}
</code>```

its work with on 480px resolution but not work on 640px. Its work fine with Chrome.

I see this below link also. But not successfull.

Media queries not work in firefox

mediaqueries max-width not working in firefox

Media queries not working on firefox

My meta tag is:

```<code><meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
</code>```

Please help.

答:
Using

```<code>@media only screen and (min-width: 320px) and (max-width: 480px) {

}
</code>```

Means that changes would occur when screen width gets to 480px and revert back to normal when screen width gets to 320px

Don't really know what you want but the explanation above should help you out

Body:
I have an issue with max-width media query. In this if i am use that media query:

@media only screen and (min-width: 320px) and (max-width: 480px) {
}

Then its not work on 480px resolution. But if i am use that media query:

@media only screen and (min-width: 320px) and (max-width: 640px) {
}

its work with on 480px resolution but not work on 640px. Its work fine with Chrome.

I see this below link also. But not successfull.

Media queries not work in firefox

mediaqueries max-width not working in firefox

Media queries not working on firefox

My meta tag is:

<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />

Please help.

Body:
Using

@media only screen and (min-width: 320px) and (max-width: 480px) {

}

Means that changes would occur when screen width gets to 480px and revert back to normal when screen width gets to 320px

Don't really know what you want but the explanation above should help you out


问:
Return a promise from service
I have this service where I do like this

```<code>userRes.getCurrentUser = () => {
    return userRes.get({
        user: 1
    });
};
</code>```

Which I use in my controller like this

```<code>console.log(currUserService.getCurrentUser());
</code>```

and it works fine, I get back a promise and the object when it is resolved

BUT

I want to create a class after I get the data, so I do like this

```<code>userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};
</code>```

But then I get undefined

How can I make it return the class?

Thank you

Edit

```<code>let userRes = $resource('url', {}, {});
</code>```

答:
In your controller script,  currUserService.getCurrentUser() will run through the function without handling the promise. In fact it will return nothing.

```<code> console.log(currUserService.getCurrentUser());
</code>```

to properly use the $promise, you can return the $promise, as in

```<code>return userRes.getCurrentUser = () => {
    userRes.get({
    user: 1
}).$promise.then(data => {
    return new User(data);
});  // end of this chain is another $promise
</code>```

};

now in your controller you can do this

```<code>currUserService.getCurrentUser().then( user =>{
    console.log(user);
});
</code>```

Title: Return a promise from service

Body:
I have this service where I do like this

userRes.getCurrentUser = () => {
    return userRes.get({
        user: 1
    });
};

Which I use in my controller like this

console.log(currUserService.getCurrentUser());

and it works fine, I get back a promise and the object when it is resolved

BUT

I want to create a class after I get the data, so I do like this

userRes.getCurrentUser = () => {
    userRes.get({
        user: 1
    }).$promise.then(data => {
        return new User(data);
    });
};

But then I get undefined

How can I make it return the class?

Thank you

Edit

let userRes = $resource('url', {}, {});

Body:
In your controller script,  currUserService.getCurrentUser() will run through the function without handling the promise. In fact it will return nothing.

 console.log(currUserService.getCurrentUser());

to properly use the $promise, you can return the $promise, as in

return userRes.getCurrentUser = () => {
    userRes.get({
    user: 1
}).$promise.then(data => {
    return new User(data);
});  // end of this chain is another $promise

};

now in your controller you can do this

currUserService.getCurrentUser().then( user =>{
    console.log(user);
});


问:
PowerShell fails to call a simple function from an ASP.NET DLL
I'm trying to call this really simple .NET 4 function with PowerShell v2. Its definition look like:

Public Shared Function
  currentSchoolYear() As String
       Member of NM4.SiteAdmin.Logic.Subscription

Let's add the path to the DLL file containing that function. It's an ASP.NET MVC web application DLL file.

PS > Add-Type -Path C:\xxx\bin\xxxWebApp.dll

Let's try it (FAIL!):

PS >

  [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear()

  Exception calling "currentSchoolYear"

  with "0" argument(s): "The type

  initializer for

  'NM4.SiteAdmin.Logic.Subscription'

  threw an exception." At line:1 char:54

  + [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear

  <<<< ()

      + CategoryInfo          : NotSpecified: (:) [],

  MethodInvocationException

      + FullyQualifiedErrorId : DotNetMethodException

Let's observe the class from PowerShell:

PS >

  [NM4.SiteAdmin.Logic.Subscription]

  IsPublic IsSerial Name

  BaseType

  -------- -------- ---- --------  True     False    Subscription

  System.Object

Let's observe the function from PowerShell

PS >

  [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear

  MemberType          : Method

  OverloadDefinitions : {static string

  currentSchoolYear()} TypeNameOfValue

  :

  System.Management.Automation.PSMethod

  Value               : static string

  currentSchoolYear() Name

  : currentSchoolYear IsInstance

  : True

Why oh why? It seems like the doc to me.

答: It sounds like an exception in the static constructor OR a type on which NM4.SiteAdmin.Logic.Subscription depends could not be loaded. I'm assuming "C:\xxx\bin\xxxWebApp.dll" and friends aren't in GAC and you're not running from "C:\xxx\bin\" so therefore powershell can't resolve the dependencies. Try running this from "C:\xxx\bin\".

ContentLicense: CC BY-SA 2.5


问:
Accessing Federal Data via SOAP Webservice using SUDS in Python
I am trying to access the Webservice of the Business Register of the Swiss Federal Government (https://www.bfs.admin.ch/bfs/de/home/register/unternehmensregister/unternehmens-identifikationsnummer/uid-register/uid-schnittstellen.assetdetail.1760903.html)

However their documentation is so complex and weird that I have no clue on how to build the request that it works.

I am rather familiar with REST APIs but SOAP is new to me.

Using SoapUI I managed to build a working request:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"    xmlns:uid="http://www.uid.admin.ch/xmlns/uid-wse" xmlns:ns="http://www.ech.ch/xmlns/eCH-0108-f/3" xmlns:ns1="http://www.ech.ch/xmlns/eCH-0098-f/3" xmlns:ns2="http://www.ech.ch/xmlns/eCH-0097-f/2" xmlns:ns3="http://www.ech.ch/xmlns/eCH-0046-f/3" xmlns:ns4="http://www.ech.ch/xmlns/eCH-0044-f/4" xmlns:ns5="http://www.ech.ch/xmlns/eCH-0010-f/6" xmlns:ns6="http://www.ech.ch/xmlns/eCH-0007-f/6">
<soapenv:Header/>
  <soapenv:Body>
    <uid:Search>
      <uid:searchParameters>
        <ns:organisation>
          <ns1:organisationIdentification>
              <ns2:organisationName>Beekeeper</ns2:organisationName>
           </ns1:organisationIdentification>
        </ns:organisation>
     </uid:searchParameters>
  </uid:Search>
</soapenv:Body>
</soapenv:Envelope>
</code>```

But I am failing to implement this request in Python. Whatever tutorials I look up i find things such as

```<code> request_data = client.factory.create('s1:CityWeatherRequest')
 request_data.City = "Stockholm"
</code>```

What would the methods be to build the request as above?

How do I create nested requests to SOAP?

答:
You should have a look at pyxb

When you have built up Python bindings based on wsdl schema or xsd files, you can execute the code below to make the request. The wsld shows what your actions will be.

from pyxb.utils.six.moves.urllib import request as urllib_request
import pyxb.bundles.wssplat.soap11 as soapenv

# Create a SOAP envelope from XML
myenv = soapenv.Envelope(soapenv.Body(myxmlreq))

# Create URL, headers and body for the HTTP request
url="http://www.test.com"
headers = {'Content-Type': 'text/xml;charset=UTF-8',
           'Accept-Encoding': 'gzip,deflate',
           'SOAPAction': "http://test.com/API/Action", # See documentation to learn about the actions
           'Connection':'close'} # set what your server accepts
body = myenv.toxml("utf-8")

# Create the request, send it and receive the response as XML
uri = urllib_request.Request(url,data=body,headers=headers)
rxml = urllib_request.urlopen(uri).read() # This is the response XML
```

Body:
I am trying to access the Webservice of the Business Register of the Swiss Federal Government (https://www.bfs.admin.ch/bfs/de/home/register/unternehmensregister/unternehmens-identifikationsnummer/uid-register/uid-schnittstellen.assetdetail.1760903.html)

However their documentation is so complex and weird that I have no clue on how to build the request that it works.

I am rather familiar with REST APIs but SOAP is new to me.

Using SoapUI I managed to build a working request:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"    xmlns:uid="http://www.uid.admin.ch/xmlns/uid-wse" xmlns:ns="http://www.ech.ch/xmlns/eCH-0108-f/3" xmlns:ns1="http://www.ech.ch/xmlns/eCH-0098-f/3" xmlns:ns2="http://www.ech.ch/xmlns/eCH-0097-f/2" xmlns:ns3="http://www.ech.ch/xmlns/eCH-0046-f/3" xmlns:ns4="http://www.ech.ch/xmlns/eCH-0044-f/4" xmlns:ns5="http://www.ech.ch/xmlns/eCH-0010-f/6" xmlns:ns6="http://www.ech.ch/xmlns/eCH-0007-f/6">
<soapenv:Header/>
  <soapenv:Body>
    <uid:Search>
      <uid:searchParameters>
        <ns:organisation>
          <ns1:organisationIdentification>
              <ns2:organisationName>Beekeeper</ns2:organisationName>
           </ns1:organisationIdentification>
        </ns:organisation>
     </uid:searchParameters>
  </uid:Search>
</soapenv:Body>
</soapenv:Envelope>

But I am failing to implement this request in Python. Whatever tutorials I look up i find things such as

 request_data = client.factory.create('s1:CityWeatherRequest')
 request_data.City = "Stockholm"

What would the methods be to build the request as above?

How do I create nested requests to SOAP?


问:
Unable to load controller-specific javascript file in Rails (5+)
I have tried as many potential solutions as I can find and, so far, nothing has worked. The code in the .js file is not being executed nor does it appear to be present anywhere in the client browser.

application.html.erb loads this partial in the head:

```<code><%= csrf_meta_tags %>
<%= stylesheet_link_tag "application", params[:controller], media: "all" %>
<%= javascript_include_tag "application", params[:controller] %>
</code>```

config/initializers/assets.rb

```<code>%w(  articles password_resets sessions static_pages users ).each do |controller|
  Rails.application.config.assets.precompile += ["#{controller}.js.coffee", "#{controller}.css"]
end
</code>```

[controller-name-here].js

```<code>$(document).ready(function() {
    alert('My controller');
});
</code>```

In the browser, when everything above is as it is, there will be an asset called ‘[controller-name].self.longstringhere.js?body=1’. It will have this code in it:

```<code>(function() {

}).call(this);
</code>```

… which does not exist anywhere in my project. If I remove the controller from the assets.rb, when trying to load a page from that controller, it throws an error [as expected]. When getting rid of the entry in the application layout, the ‘[controller].self.js’ file is missing from the browser’s assets [as expected]. However, whether or not any of the controllers’ js files are missing or not doesn’t cause any errors and does not preclude the browser’s assets from including the ‘[controller].self.js’. It is like the files in app/assets/javascripts are totally ignored and “stubbed out”.

NOTE: I specifically do not have '//= require_tree .' and '*= require_tree .' in the application.js/.css files as I am specifically following the instructions here. This is intentional.

I have also removed all references that I can find (gem’s, assets, etc.) of turbolinks as I have been reading that this can cause evil things to happen that may relate to this issue.

I have also restarted the server, precompiled the assets, and have done this and several other ritualistic things many times - all to no avail.

For the record, I also changed the "#{controller}.js.coffee" in the assets.rb to just ‘.js’ to no avail. But I read that this isn’t necessary anyway.

This problem is with all controller’s – not just one in particular.

Thanks for your help!

[EDIT] I created a new rails project using scaffolding and followed the same procedure (but ensuring that the precompiled asset (posts.js) was called out specifically by name in assets.rb) and have the same problem as described above including the same javascript "stub" code in the browser's posts.blahblah.js file.

答:
Seems like your file name is [controller-name-here].js and you are using js not coffee.

But you are adding coffee file in your config/initializers/assets.rb file. that's why it's not able to compile file properly.
Try change your config/initializers/assets.rb file like below:

```<code>%w(  articles password_resets sessions static_pages users ).each do |controller|
  Rails.application.config.assets.precompile += ["#{controller}.js", "#{controller}.css"]
end
</code>```

Everything else seems fine.

Body:
I have tried as many potential solutions as I can find and, so far, nothing has worked. The code in the .js file is not being executed nor does it appear to be present anywhere in the client browser.

application.html.erb loads this partial in the head:

<%= csrf_meta_tags %>
<%= stylesheet_link_tag "application", params[:controller], media: "all" %>
<%= javascript_include_tag "application", params[:controller] %>

config/initializers/assets.rb

%w(  articles password_resets sessions static_pages users ).each do |controller|
  Rails.application.config.assets.precompile += ["#{controller}.js.coffee", "#{controller}.css"]
end

[controller-name-here].js

$(document).ready(function() {
    alert('My controller');
});

In the browser, when everything above is as it is, there will be an asset called ‘[controller-name].self.longstringhere.js?body=1’. It will have this code in it:

(function() {

}).call(this);

… which does not exist anywhere in my project. If I remove the controller from the assets.rb, when trying to load a page from that controller, it throws an error [as expected]. When getting rid of the entry in the application layout, the ‘[controller].self.js’ file is missing from the browser’s assets [as expected]. However, whether or not any of the controllers’ js files are missing or not doesn’t cause any errors and does not preclude the browser’s assets from including the ‘[controller].self.js’. It is like the files in app/assets/javascripts are totally ignored and “stubbed out”.

NOTE: I specifically do not have '//= require_tree .' and '*= require_tree .' in the application.js/.css files as I am specifically following the instructions here. This is intentional.

I have also removed all references that I can find (gem’s, assets, etc.) of turbolinks as I have been reading that this can cause evil things to happen that may relate to this issue.

I have also restarted the server, precompiled the assets, and have done this and several other ritualistic things many times - all to no avail.

For the record, I also changed the "#{controller}.js.coffee" in the assets.rb to just ‘.js’ to no avail. But I read that this isn’t necessary anyway.

This problem is with all controller’s – not just one in particular.

Thanks for your help!

[EDIT] I created a new rails project using scaffolding and followed the same procedure (but ensuring that the precompiled asset (posts.js) was called out specifically by name in assets.rb) and have the same problem as described above including the same javascript "stub" code in the browser's posts.blahblah.js file.

Body:
Seems like your file name is [controller-name-here].js and you are using js not coffee.

But you are adding coffee file in your config/initializers/assets.rb file. that's why it's not able to compile file properly.
Try change your config/initializers/assets.rb file like below:

%w(  articles password_resets sessions static_pages users ).each do |controller|
  Rails.application.config.assets.precompile += ["#{controller}.js", "#{controller}.css"]
end

Everything else seems fine.


问:
How to insert array fields data in Laravel5
How can I insert multiple text fields data with Laravel.
I have two fields.

```<code><input type="text" name="title[]" />
<input type="text" name="email[]" />
</code>```

Now in controller I can get these values as below.

```<code>$name =  $request->title;
$description =  $request->email;
</code>```

Here what i get when i print these values.

```<code>Array
(
    [0] => title1
    [1] => title2
)
Array
(
    [0] => desc1
    [1] => desc2
)
</code>```

How can I add this with eloquent.

答:
Method 1 :

```<code>$name =  $request->title;
    $description =  $request->email;

    if(count($name) > count($description))
        $count = count($description);
    else $count = count($name);

for($i = 0; $i < $count; $i++){
    $objModel = new ModelName();
    $objModel->name = $name[$i];
    $objModel->description = $description[$i];
    $objModel->save();
}
</code>```

Method 2 :

```<code>$name =  $request->title;
    $description =  $request->email;

    if(count($name) > count($description))
        $count = count($description);
    else $count = count($name);

    for($i = 0; $i < $count; $i++){
        $data = array(
            'name' => $name[$i],
            'description' => $description[$i]
        );

        $insertData[] = $data;
    }

    ModelName::insert($insertData);
</code>```

Body:
How can I insert multiple text fields data with Laravel.
I have two fields.

<input type="text" name="title[]" />
<input type="text" name="email[]" />

Now in controller I can get these values as below.

$name =  $request->title;
$description =  $request->email;

Here what i get when i print these values.

Array
(
    [0] => title1
    [1] => title2
)
Array
(
    [0] => desc1
    [1] => desc2
)

How can I add this with eloquent.

Body:
Method 1 :

$name =  $request->title;
    $description =  $request->email;

    if(count($name) > count($description))
        $count = count($description);
    else $count = count($name);

for($i = 0; $i < $count; $i++){
    $objModel = new ModelName();
    $objModel->name = $name[$i];
    $objModel->description = $description[$i];
    $objModel->save();
}

Method 2 :

$name =  $request->title;
    $description =  $request->email;

    if(count($name) > count($description))
        $count = count($description);
    else $count = count($name);

    for($i = 0; $i < $count; $i++){
        $data = array(
            'name' => $name[$i],
            'description' => $description[$i]
        );

        $insertData[] = $data;
    }

    ModelName::insert($insertData);


问:
How can I programatically select a drop down option using Ember?
This is my sample drop down

```<code><select name="newType" class="parts-select full-width-combo" onchange={{action "loadFilter" value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}">{{item.description}}</option>
            {{/each}}
 </select>
</code>```

from the relevant template action I wanted to set this selected item dynamically.

As an example it default selected by "Select" and then based on some button click on that page and need to set my selected option to other selected option to be selected.
I am not using any plugin and I can't do it here.

答:
You can use ember-truth-helpers' eq helper to set which option is selected. I believe I have coded what you are asking at this twiddle. See my-component.hbs about how I used eq helper to set selected attributes of each option.

By the way I suggest using ember-power-select for select box instead of trying to write your own select with options.

Body:
This is my sample drop down

<select name="newType" class="parts-select full-width-combo" onchange={{action "loadFilter" value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}">{{item.description}}</option>
            {{/each}}
 </select>

from the relevant template action I wanted to set this selected item dynamically.

As an example it default selected by "Select" and then based on some button click on that page and need to set my selected option to other selected option to be selected.
I am not using any plugin and I can't do it here.


问:
React: Using ES6 component in TS component: TS2605: JSX element type 'xxx' is not a constructor function for JSX elements
I want to use an ES6 React component in another Typescript component.

The ES6 component:

```<code>class ModelViewer extends Component {
  constructor(props, context) {
    super(props, context);
    //...
  }
// ...
}
export default ModelViewer;
</code>```

My consuming TS component:

```<code>import * as ReactDOM from "react-dom";
import * as React from "react";
import ModelViewer from "./model_viewer/ModelViewer";

export class Viewer extends React.Component<any, any> {
    render() {
        return (
                <div>
                    <ModelViewer />
                </div>
        );
    }
}
</code>```

Options for the TSC are:

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true
    }
}
</code>```

Now I'm receiving the error TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements.

Do I need to provide typings despite having set "allowJS": true? I've tried different ways to import, but no difference.

答:
As a kind of brute force method I satisfied the Typescript compiler using a custom typings file.

```<code>// typings/custom.d.ts
declare module "*";
</code>```

And tell the compiler in my tsconfig.json to read my custom typings:

```<code>// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "typeRoots": [
             "./typings",
             "node_modules/@types"
         ]
    }
}
</code>```

Body:
I want to use an ES6 React component in another Typescript component.

The ES6 component:

class ModelViewer extends Component {
  constructor(props, context) {
    super(props, context);
    //...
  }
// ...
}
export default ModelViewer;

My consuming TS component:

import * as ReactDOM from "react-dom";
import * as React from "react";
import ModelViewer from "./model_viewer/ModelViewer";

export class Viewer extends React.Component<any, any> {
    render() {
        return (

                    <ModelViewer />

        );
    }
}

Options for the TSC are:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true
    }
}

Now I'm receiving the error TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements.

Do I need to provide typings despite having set "allowJS": true? I've tried different ways to import, but no difference.

Body:
As a kind of brute force method I satisfied the Typescript compiler using a custom typings file.

// typings/custom.d.ts
declare module "*";

And tell the compiler in my tsconfig.json to read my custom typings:

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "typeRoots": [
             "./typings",
             "node_modules/@types"
         ]
    }
}


答:
I thought it works just like an array

No, it works like a map, because it is a map. It is similar to a HashMap, but more memory efficient for smaller data sets.

It's order shouldn't and doesn't matter. Under the hood, it is implemented using
an array which has an order since arrays do. This inherently gives the ArrayMap an order, but that is not part of it's API anyway. Just like which memory slot your Java objects are in, you shouldn't care about the order here either.

Title: ArrayMap put method pushes elements in strange order

Body:
I am using ArrayMap for first time in my project and I thought it works just like an array. I expected when I use .put method it inserts it at next index.
But in my case this is not true - after I added all elements one by one the first element I added ended up at index 4 which is kind of strange.

Here are the first three steps which I add elements:

1 - Salads:

2 - Soups:

3 - Appetizers:

So somehow on second step "Soup" element was inserted in index 0 instead of 1 as I was expecting, but strangely on third step "Appetizers" was inserted as expected after "Soup".

This is the code I am using to push key and value pair:

function ArrayMap<String, DMType> addElement(String typeKey, DMType type) {
    ArrayMap<String, DMType> types = new ArrayMap<>();
    types.put(typeKey, type);

    return types;
}

Am I missing something about the behavior of ArrayMap?


问:
Application Loader Error: Launch Path Not Accessible
I'm trying to submit an application to Apple but am coming up with an error in Application Launcher.

Once I choose the zip file I hit Send and it comes up with the error:

Exception while validating: launch path not accessible

No idea what to do here, can't find much info on it at all on the net.

I have tried reapplying my provisioning / distribution profiles with no luck.  Have re-opened XCode many times in case it was confused.

I submitted the same app a week and a bit ago and it went through fine, it got rejected so I made a few small changes and now this error comes up - no big changes were made.

The only thing I can think of is that I needed to update XCode and the SDK - from xcode_3.2.4_and_ios_sdk_4.1 to xcode_3.2.5_and_ios_sdk_4.2_final as the iPad I am using was updated to 4.2.

Any ideas on where to go from here would be greatly appreciated.

答: i had same problem, closed App Loader, restarted App Loader, problem solved.</p>


问:
How can i store object in MySql Database?
can i store some object in MySql Database? Because I am making a online or offline support system by MySql. So it is important to store all data as Object. Do you have better Idea except Object?

This is Damo example about object

```<code>$data = array(
                'user_id' => 1, //$userId,
                'payment_id' => $payment_id,
                'hash' => $hash,
                'conversation' => $object,
                'amount' => $paypal->getTransactions()[0]->getAmount()->getTotal(),
                'description' => $paypal->getTransactions()[0]->getDescription()
            );
$this->db->insert($this->table, $data);
</code>```

答:
You have to transform your object in a string to save your full object.
For that, use serialize in PHP:

http://php.net/manual/en/language.oop5.serialization.php

Then you will be able to unserialize and get back your object.

Body:
can i store some object in MySql Database? Because I am making a online or offline support system by MySql. So it is important to store all data as Object. Do you have better Idea except Object?

This is Damo example about object

$data = array(
                'user_id' => 1, //$userId,
                'payment_id' => $payment_id,
                'hash' => $hash,
                'conversation' => $object,
                'amount' => $paypal->getTransactions()[0]->getAmount()->getTotal(),
                'description' => $paypal->getTransactions()[0]->getDescription()
            );
$this->db->insert($this->table, $data);


问:
how to stretch listviewitem in listview
developers.

I try to stretch listview item in horizontal orientation.
I do reset ItemContainerStyle ,and the horizentalalignment is strech.
Here is all code in the MainPage.xaml.

```<code><Grid x:Name="rootGrid"
      HorizontalAlignment="Stretch"
      MinWidth="320"
      MaxWidth="480"
      Width="Auto">
    <ListView x:Name="infoFlowListView"
              MinWidth="320"
              MaxWidth="480"
              Width="Auto"
              HorizontalAlignment="Stretch">
        <ListView.ItemTemplate>
            <DataTemplate>
                <local:MyUserControl1 MinWidth="300" HorizontalAlignment="Stretch"></local:MyUserControl1>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>
</Grid>
</code>```

Here is all code in MainPage.xaml.cs

```<code>public MainPage()
    {
        var items = new List<MyUserControl1>();
        for (int i = 0; i < 50; i++)
        {
            items.Add(new MyUserControl1());
        }
        this.InitializeComponent();
        infoFlowListView.ItemsSource = items;
    }
</code>```

Here is all code in MyUserControl.xaml

```<code><Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="8"></RowDefinition>
</Grid.RowDefinitions>

<Ellipse Width="60" Height="60"
         Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="Uniform">
    <Ellipse.Fill>
        <ImageBrush ImageSource="Assets/1.png"></ImageBrush>
    </Ellipse.Fill>
</Ellipse>

<RelativePanel x:Name="topRelativePanel"
               Grid.Column="1" Grid.Row="0"
               HorizontalAlignment="Stretch">
    <TextBlock Text="TestName"
               VerticalAlignment="Bottom"
               RelativePanel.AlignLeftWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"></TextBlock>
    <TextBlock Text="Author"
               VerticalAlignment="Bottom"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"
               Margin="0,0,8,0"></TextBlock>
</RelativePanel>

<TextBlock x:Name="nameTextBlock"
           Grid.Column="1" Grid.Row="1"
           Text="Name"
           TextTrimming="WordEllipsis"
           VerticalAlignment="Stretch"
           HorizontalAlignment="Stretch"
           FontSize="18" >
</TextBlock>

<Grid x:Name="bottomGrid"
      Grid.Column="1" Grid.Row="2"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="3*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0"
               HorizontalAlignment="Stretch"
               Text="90"></TextBlock>
    <TextBlock Grid.Column="1"
               HorizontalAlignment="Stretch"
               Text="48"></TextBlock>
    <TextBlock Grid.Column="2"
               HorizontalAlignment="Stretch"
               Text="20170330 08:33"
               Margin="0,0,0,0"></TextBlock>
</Grid>

<Border Background="LightGray"
        VerticalAlignment="Stretch"
        HorizontalAlignment="Stretch"
        Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"></Border>
</code>```

I test these code on 6inch emulator, and I add a screenshot of this example.

And the mobile emulators don't have the same result.
Here are different emulator screenshots.
4inch
screen shot of example
The right side of these screenshots are different.

答: I think, this is because the ListView.ItemTemplate control have the MaxWidth="400" property. </p>

Title: how to stretch listviewitem in listview

Body:
developers.

I try to stretch listview item in horizontal orientation.
I do reset ItemContainerStyle ,and the horizentalalignment is strech.
Here is all code in the MainPage.xaml.

<Grid x:Name="rootGrid"
      HorizontalAlignment="Stretch"
      MinWidth="320"
      MaxWidth="480"
      Width="Auto">
    <ListView x:Name="infoFlowListView"
              MinWidth="320"
              MaxWidth="480"
              Width="Auto"
              HorizontalAlignment="Stretch">
        <ListView.ItemTemplate>
            <DataTemplate>
                <local:MyUserControl1 MinWidth="300" HorizontalAlignment="Stretch"></local:MyUserControl1>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemContainerStyle>

        </ListView.ItemContainerStyle>
    </ListView>
</Grid>

Here is all code in MainPage.xaml.cs

public MainPage()
    {
        var items = new List<MyUserControl1>();
        for (int i = 0; i < 50; i++)
        {
            items.Add(new MyUserControl1());
        }
        this.InitializeComponent();
        infoFlowListView.ItemsSource = items;
    }

Here is all code in MyUserControl.xaml

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="8"></RowDefinition>
</Grid.RowDefinitions>

<Ellipse Width="60" Height="60"
         Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="Uniform">
    <Ellipse.Fill>
        <ImageBrush ImageSource="Assets/1.png"></ImageBrush>
    </Ellipse.Fill>
</Ellipse>

<RelativePanel x:Name="topRelativePanel"
               Grid.Column="1" Grid.Row="0"
               HorizontalAlignment="Stretch">
    <TextBlock Text="TestName"
               VerticalAlignment="Bottom"
               RelativePanel.AlignLeftWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"></TextBlock>
    <TextBlock Text="Author"
               VerticalAlignment="Bottom"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"
               Margin="0,0,8,0"></TextBlock>
</RelativePanel>

<TextBlock x:Name="nameTextBlock"
           Grid.Column="1" Grid.Row="1"
           Text="Name"
           TextTrimming="WordEllipsis"
           VerticalAlignment="Stretch"
           HorizontalAlignment="Stretch"
           FontSize="18" >
</TextBlock>

<Grid x:Name="bottomGrid"
      Grid.Column="1" Grid.Row="2"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="3*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0"
               HorizontalAlignment="Stretch"
               Text="90"></TextBlock>
    <TextBlock Grid.Column="1"
               HorizontalAlignment="Stretch"
               Text="48"></TextBlock>
    <TextBlock Grid.Column="2"
               HorizontalAlignment="Stretch"
               Text="20170330 08:33"
               Margin="0,0,0,0"></TextBlock>
</Grid>

<Border Background="LightGray"
        VerticalAlignment="Stretch"
        HorizontalAlignment="Stretch"
        Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"></Border>

I test these code on 6inch emulator, and I add a screenshot of this example.

And the mobile emulators don't have the same result.
Here are different emulator screenshots.
4inch
screen shot of example
The right side of these screenshots are different.


问:
Find if a JSONObject contains a particular JSONARray
I am working on a spring MVC application. I am using org.json jar to deal with jsonObjects. I am trying to find if a JSONObject contains a JSON array. Can any one please help me in this:

Say i have a JSON Object:

```<code>{"Object":{
   "array":["",""]
}
}
</code>```

So i want to know if array exists in that json object as some times the JSONObject will be :

```<code>{"Object":{
   "array11":["",""]
}
}
</code>```

Please help me.

答:
Per the javadocs for the org.json JSON library, JSONObject has an optJSONArray() method that does not throw an exception if the key you are targeting does not exist or the value at that key is not a JSON array. For a JSONObject "foo":

```<code>JSONArray array = foo.optJSONArray("array");
if (array != null) {
    // do stuff with the array
}
</code>```

Body:
I am working on a spring MVC application. I am using org.json jar to deal with jsonObjects. I am trying to find if a JSONObject contains a JSON array. Can any one please help me in this:

Say i have a JSON Object:

{"Object":{
   "array":["",""]
}
}

So i want to know if array exists in that json object as some times the JSONObject will be :

{"Object":{
   "array11":["",""]
}
}

Please help me.

Body:
Per the javadocs for the org.json JSON library, JSONObject has an optJSONArray() method that does not throw an exception if the key you are targeting does not exist or the value at that key is not a JSON array. For a JSONObject "foo":

JSONArray array = foo.optJSONArray("array");
if (array != null) {
    // do stuff with the array
}


问:
Docraptor PDF: How to avoid displaying header in 2nd Page
Im generating PDFs using docraptor API and my pdfs can have multiple pages. I have set the header image for the pdf but it appears on all pages. I need the header in the first page only.

TIA

答:
Lecstor's answer will definitely work in this case, but it's possible to have vary headers on different pages.

Full documentation is available on Prince (DocRaptor's PDF renderer) Named Pages section, but it should look roughly like this:

```<code><style type="text/css">
@page has-header {
  @top {
    content: "This is header of text";
  }
}

.first-page {
  page: has-header;
  /* all content within .first-page will use the above @page styling */
}
</style>

<div class="first-page">
  Put first page content here
</div>

<p>Rest of content will not have a header.</p>
</code>```

That pattern can be repeated. Different named pages can have different headers, different margins, different landscape/portrait modes, sizes, etc..

Body:
Lecstor's answer will definitely work in this case, but it's possible to have vary headers on different pages.

Full documentation is available on Prince (DocRaptor's PDF renderer) Named Pages section, but it should look roughly like this:

<style type="text/css">
@page has-header {
  @top {
    content: "This is header of text";
  }
}

.first-page {
  page: has-header;
  /* all content within .first-page will use the above @page styling */
}
</style>

<div class="first-page">
  Put first page content here
</div>

<p>Rest of content will not have a header.</p>

That pattern can be repeated. Different named pages can have different headers, different margins, different landscape/portrait modes, sizes, etc..


问:
Is it possible to force a mapping, server side, on a specific index?
I send to Elasticsearch data to a index mydata. This index may or may not exist when the data reaches Elasticsearch and is automatically created.

The mapping guessed from my data was correct up to now, when I added a new field of geo_point type. This type, as far as I understand, must be explicitly provided with a mapping.

My understanding is that mapping is handled

either dynamicall, like my case

or when creating an index "manually"

or via the Put Mapping API

None of these solutions work for me, the index is deleted / recreated rarely (but unpredictibly) and adding the mapping to each document sent to the server would be too much.

Is there a way to store, on the server, an information of the type "if you create  index mydata, the field position must be of type geo_ip"?

答:
Index templates will do exactly what you need. Simply create a template (with mappings and settings) whose name matches your index name and as soon as a new document comes in for an index that doesn't exist yet, the latter will be automatically create with the proper mappings and settings.

To answer your second question, yes, your mapping may only contain the definition of a few fields (the geo_point you mentioned, etc) and you can let ES map the other ones dynamically.


问:
Fetching JSON and iterating through the values in react-native
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

```<code>import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);
</code>```

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

```<code>renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
</code>```

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

```<code>{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}
</code>```

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

```<code>fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }
</code>```

console.log(responseData) shows:

```<code>03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }
</code>```

console.log(this.state.results.movies);

```<code>03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]
</code>```

答:
I see a couple of things you need to change.

Firstly, you need to bind fetchData method when you are using ES6 doing this this.fetchData = this.fetchData.bind(this); in the constructor (look for other ways to do this).

Secondly, map should be applied to this.state.results.movies due this is the array (following your post). this.state.results is not an array, is an object containing an array.

```<code>import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);

    this.state = {
      //Lets initialize results with the same struct we expect to receive from the api
      results: {
        title: '',
        description: '',
        movies: []
      }
    };
    //Using ES6 we need to bind methods to access 'this'
    this.fetchData = this.fetchData.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results: responseData
        });
      })
      .done();
  }

  render() {
    //this.state.results.movies is the array you have to iterate
    contents = this.state.results.movies.map((item) => {
      //We need to return the corresponding mapping for each item too.
      return (
          <View key={item.title} style={ styles.container }>
            <Text style={styles.title}>
              {item.title}
            </Text>
          </View>
        );
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);
</code>```

Let me know if its works, I havent tested yet but I will soon.

Body:
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }

console.log(responseData) shows:

03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }

console.log(this.state.results.movies);

03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]

Body:
I see a couple of things you need to change.

Firstly, you need to bind fetchData method when you are using ES6 doing this this.fetchData = this.fetchData.bind(this); in the constructor (look for other ways to do this).

Secondly, map should be applied to this.state.results.movies due this is the array (following your post). this.state.results is not an array, is an object containing an array.

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);

    this.state = {
      //Lets initialize results with the same struct we expect to receive from the api
      results: {
        title: '',
        description: '',
        movies: []
      }
    };
    //Using ES6 we need to bind methods to access 'this'
    this.fetchData = this.fetchData.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results: responseData
        });
      })
      .done();
  }

  render() {
    //this.state.results.movies is the array you have to iterate
    contents = this.state.results.movies.map((item) => {
      //We need to return the corresponding mapping for each item too.
      return (
          <View key={item.title} style={ styles.container }>
            <Text style={styles.title}>
              {item.title}
            </Text>
          </View>
        );
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

Let me know if its works, I havent tested yet but I will soon.


问:
C# - Prevent animation of a showing form
Is there any way of stopping the default opening animation of a form from Windows? I mean stopping it just for one form, not all of them. I need the showing of a form to be instantly, without that growing effect.

I tried to document about WinApi, but I couldn't find anything. Thank you!

答:
I had to set the location property after showing the form. It works!</p>

```<code>this.Hide();
this.Size = this.Size;
this.Location = this.Location;
this.Show();
</code>```

Body:
I had to set the location property after showing the form. It works!

this.Hide();
this.Size = this.Size;
this.Location = this.Location;
this.Show();


问:
How to write query in database to make search case insenstive and display multiple records based on search
My SQL query

```<code>PreparedStatement ps = con.prepareStatement("select * from Application where name like '"+ name+"%'");
</code>```

Could you please suggest me how to make it case insensitive and based on search it should display multiple records which starts with search keyword since I have used 'like'.

Suppose when I search by 'C' in search button. When submit it should display Car, cat etc. (in my database) in the jsp page, but it is returning only one record.

答:
On databases that support it, you can use ilike in place of like for a case-insensitive search.

```<code>PreparedStatement ps = con.prepareStatement("select * from Application where name ilike '"+ name+"%'");
</code>```

Body:
My SQL query

PreparedStatement ps = con.prepareStatement("select * from Application where name like '"+ name+"%'");

Could you please suggest me how to make it case insensitive and based on search it should display multiple records which starts with search keyword since I have used 'like'.

Suppose when I search by 'C' in search button. When submit it should display Car, cat etc. (in my database) in the jsp page, but it is returning only one record.

Body:
On databases that support it, you can use ilike in place of like for a case-insensitive search.

PreparedStatement ps = con.prepareStatement("select * from Application where name ilike '"+ name+"%'");


问:
permanently delete only one gmail message from a thread using a google script
I want to permanently delete a Gmail message inside a thread already in the trash.

I merged a few scripts around there, so I can delay and track emails. It works by saving a draft, then the script copy the draft into a new email, send it at the specified time and send the original draft to trash. The problem is that once in a while, the drafts that are in the trash are sent again (i haven't been able to figure out why yet)...

As a workaround, I was using the following code that that was originally posted here: delete forever emails 1:

```<code>function cleanUp() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);
  for (var i = 0; i < threads.length; i++) {
    Logger.log(threads[i].getId());
    Gmail.Users.Message.remove('me',threads[i].getId());
  }
}
</code>```

This was working fine, until a while ago. If the draft was inside a thread with more than 1 message, only the draft was deleted... I got now an error on line 6 that says: "Cannot call method "remove" of undefined".

In this post: delete forever emails 2, it is suggested to replace line 6 by

```<code>Gmail.Users.Threads.remove('me',threads[i].getId());
</code>```

This dosn't get any errors, but if the draft is in a thread with more than one message, the whole thread is deleted instead of only the draft...

So, is there a way to get only the draft erased?

I tried calling the message id of the draft inside the thread and use the original line 6:

```<code>function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);
    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        Gmail.Users.Message.remove('me',messages[j].getId());
      }
    }
  }
}
</code>```

But I got the same error, now on line 10...

I also tried using this function:

```<code>function deleteMessage(userId, messageId) {
  var request = gapi.client.gmail.users.messages.delete({
    'userId': userId,
    'id': messageId
  });
  request.execute(
    function(resp) { });
}
</code>```

That you can find in the developers page of google: here. In the "try this API" section it works, but in my implementation i got an error on line 2 that says (translated from Spanish so i don't know if it will be exact): "a name (?) is missing behind (after?) operator "."" And if i copy the function in a separated tab, i can save it and the same error is showed...

Any help will be appreciated...

Regards,

答:
i finally made it trough an http request:</p>

```<code>function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'xxxxx@gmail.com';
  var options = {
   'method' : 'delete',
   'muteHttpExceptions': true
 };

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        var url = 'https://www.googleapis.com/gmail/v1/users/' + userId + '/messages/' + messages[j].getId();
        var response = UrlFetchApp.fetch(url,options);
        Logger.log(response);
      }
    }
  }
}
</code>```

Body:
I want to permanently delete a Gmail message inside a thread already in the trash.

I merged a few scripts around there, so I can delay and track emails. It works by saving a draft, then the script copy the draft into a new email, send it at the specified time and send the original draft to trash. The problem is that once in a while, the drafts that are in the trash are sent again (i haven't been able to figure out why yet)...

As a workaround, I was using the following code that that was originally posted here: delete forever emails 1:

function cleanUp() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);
  for (var i = 0; i < threads.length; i++) {
    Logger.log(threads[i].getId());
    Gmail.Users.Message.remove('me',threads[i].getId());
  }
}

This was working fine, until a while ago. If the draft was inside a thread with more than 1 message, only the draft was deleted... I got now an error on line 6 that says: "Cannot call method "remove" of undefined".

In this post: delete forever emails 2, it is suggested to replace line 6 by

Gmail.Users.Threads.remove('me',threads[i].getId());

This dosn't get any errors, but if the draft is in a thread with more than one message, the whole thread is deleted instead of only the draft...

So, is there a way to get only the draft erased?

I tried calling the message id of the draft inside the thread and use the original line 6:

function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);
    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        Gmail.Users.Message.remove('me',messages[j].getId());
      }
    }
  }
}

But I got the same error, now on line 10...

I also tried using this function:

function deleteMessage(userId, messageId) {
  var request = gapi.client.gmail.users.messages.delete({
    'userId': userId,
    'id': messageId
  });
  request.execute(
    function(resp) { });
}

That you can find in the developers page of google: here. In the "try this API" section it works, but in my implementation i got an error on line 2 that says (translated from Spanish so i don't know if it will be exact): "a name (?) is missing behind (after?) operator "."" And if i copy the function in a separated tab, i can save it and the same error is showed...

Any help will be appreciated...

Regards,

Body:
i finally made it trough an http request:

function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'xxxxx@gmail.com';
  var options = {
   'method' : 'delete',
   'muteHttpExceptions': true
 };

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        var url = 'https://www.googleapis.com/gmail/v1/users/' + userId + '/messages/' + messages[j].getId();
        var response = UrlFetchApp.fetch(url,options);
        Logger.log(response);
      }
    }
  }
}


问:
C++ and Xlib - center window
I have started to study GUI applications programming based on XLib directly and I am trying to create a centered window on the screen. I don't know the usual technique used to achieve this. My code (which doesn't work) is this (I use CodeBlocks)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <GL/glew.h>
#include <GL/freeglut.h>

int screen;
Display *display;
XSetWindowAttributes window_attributes;
Window mainwindow;
XEvent events;

int main(int argc, char** argv) {
    display = XOpenDisplay(NULL);screen = DefaultScreen(display);
    window_attributes.background_pixel = XWhitePixel(display, screen);
    window_attributes.border_pixel = XBlackPixel(display, screen);
    window_attributes.win_gravity = SouthWestGravity;

    mainwindow = XCreateWindow(display,
                             RootWindow(display, screen),
                             1, 1,
                             600, 400,
                             0,
                             CopyFromParent,
                             InputOutput,
                             CopyFromParent,
                             CWBackPixel|CWBorderPixel,
                             &window_attributes
                            );
    XMapWindow(display, mainwindow);
    XFlush(display);
    XSelectInput(display, mainwindow, ExposureMask|KeyPressMask|ButtonPressMask);
    while (1)  {
        XNextEvent(display, &events);
        switch  (events.type) {
            case Expose:
                // Lots of code that doesn't matter for my problem
            break;
        }
    }
    return 0;
}
</code>```

So, I thought that window_attributes.win_gravity would do the trick but it seems like I'm doing something wrong or it must be an OS related issue.

Thanks for your help!

UPDATE

I have changed X (left position) by 100 and y (top position) by 100 but the window's position doesn't change. So, my problem is that the window's position can't be changed, no matter what it is.

答:
In your function where you create window you should calculate the starting x,y coordinates of your window in the screen:

```<code>XDisplayWidth(dpy, sreen); XDisplayHeight(dpy, sreen);
</code>```

After that you should make your calculation (like  .../2 + win.size.x ....) to center your window.

Title: C++ and Xlib - center window

Body:
I have started to study GUI applications programming based on XLib directly and I am trying to create a centered window on the screen. I don't know the usual technique used to achieve this. My code (which doesn't work) is this (I use CodeBlocks)

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <GL/glew.h>
#include <GL/freeglut.h>

int screen;
Display *display;
XSetWindowAttributes window_attributes;
Window mainwindow;
XEvent events;

int main(int argc, char** argv) {
    display = XOpenDisplay(NULL);screen = DefaultScreen(display);
    window_attributes.background_pixel = XWhitePixel(display, screen);
    window_attributes.border_pixel = XBlackPixel(display, screen);
    window_attributes.win_gravity = SouthWestGravity;

    mainwindow = XCreateWindow(display,
                             RootWindow(display, screen),
                             1, 1,
                             600, 400,
                             0,
                             CopyFromParent,
                             InputOutput,
                             CopyFromParent,
                             CWBackPixel|CWBorderPixel,
                             &window_attributes
                            );
    XMapWindow(display, mainwindow);
    XFlush(display);
    XSelectInput(display, mainwindow, ExposureMask|KeyPressMask|ButtonPressMask);
    while (1)  {
        XNextEvent(display, &events);
        switch  (events.type) {
            case Expose:
                // Lots of code that doesn't matter for my problem
            break;
        }
    }
    return 0;
}

So, I thought that window_attributes.win_gravity would do the trick but it seems like I'm doing something wrong or it must be an OS related issue.

Thanks for your help!

UPDATE

I have changed X (left position) by 100 and y (top position) by 100 but the window's position doesn't change. So, my problem is that the window's position can't be changed, no matter what it is.

Body:
In your function where you create window you should calculate the starting x,y coordinates of your window in the screen:

XDisplayWidth(dpy, sreen); XDisplayHeight(dpy, sreen);

After that you should make your calculation (like  .../2 + win.size.x ....) to center your window.


问:
MySQL and UNIQUE columns: how to avoid duplicates?
I have a table with the following column:

```<code>(id, col_1, col_2)
</code>```

where "id" is the primary key (auto-inc).

I would like to make col_1 and col_2 a "unique combo".

For example, if I insert the data...

```<code>(.., col_1, col_2 ) = (.., 'A', 'B')
</code>```

...Next, I shouldn't be allowed to insert the following:

```<code>(.., col_1, col_2 ) = (.., 'A', 'B')
(.., col_1, col_2 ) = (.., 'B', 'A') #because it already exists, in another order:('A','B')
</code>```

I successfully blocked the first case with the use of UNIQUE(col_1, col_2)...

But it seems that the "reverse combo" (.., 'B', 'A') is permitted.

How can I stop this?

答:
After trying it out it really isn't as easy as creating another unique index.

This seems to be an odd flaw in MySQL. A workaround though can be to always store the lesser value in col_1 and the greater value in col_2 (when you don't like triggers, that is):

```<code>INSERT INTO your_table (col_1, col_2) VALUES (LEAST('A', 'B'), GREATEST('A', 'B'));
</code>```

You can find the documentation to these functions here.

Body:
I have a table with the following column:

(id, col_1, col_2)

where "id" is the primary key (auto-inc).

I would like to make col_1 and col_2 a "unique combo".

For example, if I insert the data...

(.., col_1, col_2 ) = (.., 'A', 'B')

...Next, I shouldn't be allowed to insert the following:

(.., col_1, col_2 ) = (.., 'A', 'B')
(.., col_1, col_2 ) = (.., 'B', 'A') #because it already exists, in another order:('A','B')

I successfully blocked the first case with the use of UNIQUE(col_1, col_2)...

But it seems that the "reverse combo" (.., 'B', 'A') is permitted.

How can I stop this?

Body:
After trying it out it really isn't as easy as creating another unique index.

This seems to be an odd flaw in MySQL. A workaround though can be to always store the lesser value in col_1 and the greater value in col_2 (when you don't like triggers, that is):

INSERT INTO your_table (col_1, col_2) VALUES (LEAST('A', 'B'), GREATEST('A', 'B'));

You can find the documentation to these functions here.


问:
Input/Output on a file
I wrote a short program for one of my class and there is something that I just cannot figure out. So I am supposed to write 100 random integers on a file, read back the data and print the integers in increasing order. Everything works fine, but I don't see my final sorted list on the output file, anyone can see why?

Here is my code:

```<code>private final static int NUMBEROFRANDOM = 100;

public static void main(String[] args) throws IOException {

    // Creating my file
    java.io.File file = new java.io.File("Question1.txt");

    // If it already exists, print a message and terminate program
    if (file.exists()) {
        System.out.println("File already exists.");
        System.exit(0);
    }

    // Creating my PrintWriter object
    PrintWriter output = new PrintWriter(file);

    // Creating 100 random numbers between 0 and 100 and printing them on the file
    for (int i = 0; i < NUMBEROFRANDOM; i++) {
        int number = (int) (Math.random() * 101);
        output.print(number + " ");
    }

    // Creating my Scanner object
    Scanner input = new Scanner(file);

    // Creating my array list to store the sorted list of 100 elements
    ArrayList<Integer> sortedList = new ArrayList<Integer>();

    // Reading the elements from the file and adding them into my array list
    while (input.hasNext()) {
        sortedList.add(input.nextInt());
    }

    //Sorting elements from array list
    Collections.sort(sortedList);

    // Printing the elements in increasing order
    for (int i = 0; i < sortedList.size(); i++) {
        //System.out.println(sortedList.get(i));
        output.print(sortedList.get(i));
    }

    // Closing my objects
    input.close();
    output.close();

}
</code>```

Thank you very much, any help is very appreciated!

答:
Your file is empty when you are reading it using Scanner input = new Scanner(file);

Use output.flush() to save your data after printing the values.

output.close() - will close your stream and you won't be able to store your sorted values.

```<code>// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
    int number = (int) (Math.random() * 101);
    output.print(number + " ");
}

output.flush();
</code>```

Title: Input/Output on a file

Body:
I wrote a short program for one of my class and there is something that I just cannot figure out. So I am supposed to write 100 random integers on a file, read back the data and print the integers in increasing order. Everything works fine, but I don't see my final sorted list on the output file, anyone can see why?

Here is my code:

private final static int NUMBEROFRANDOM = 100;

public static void main(String[] args) throws IOException {

    // Creating my file
    java.io.File file = new java.io.File("Question1.txt");

    // If it already exists, print a message and terminate program
    if (file.exists()) {
        System.out.println("File already exists.");
        System.exit(0);
    }

    // Creating my PrintWriter object
    PrintWriter output = new PrintWriter(file);

    // Creating 100 random numbers between 0 and 100 and printing them on the file
    for (int i = 0; i < NUMBEROFRANDOM; i++) {
        int number = (int) (Math.random() * 101);
        output.print(number + " ");
    }

    // Creating my Scanner object
    Scanner input = new Scanner(file);

    // Creating my array list to store the sorted list of 100 elements
    ArrayList<Integer> sortedList = new ArrayList<Integer>();

    // Reading the elements from the file and adding them into my array list
    while (input.hasNext()) {
        sortedList.add(input.nextInt());
    }

    //Sorting elements from array list
    Collections.sort(sortedList);

    // Printing the elements in increasing order
    for (int i = 0; i < sortedList.size(); i++) {
        //System.out.println(sortedList.get(i));
        output.print(sortedList.get(i));
    }

    // Closing my objects
    input.close();
    output.close();

}

Thank you very much, any help is very appreciated!

Body:
Your file is empty when you are reading it using Scanner input = new Scanner(file);

Use output.flush() to save your data after printing the values.

output.close() - will close your stream and you won't be able to store your sorted values.

// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
    int number = (int) (Math.random() * 101);
    output.print(number + " ");
}

output.flush();


问:
pg:pull, pg:backups no longer available in heroku cli
Just strange, I am doing back database maintenance, I tried to to a heroku pg:pull <DB_URL> local_db --app <appname> and it says:

pg:pull is not a heroku command.

I tried to create a backup with heroku pg:backups:capture <DB_URL> and i get this:

pg:backups:capture is not a heroku command.

Just trying heroku pg:backups shows:

pg:backups is not a heroku command.

Its strange because even in the --help section, looks like all the useful commands are gone:

```<code>heroku pg --help
Usage: heroku pg [DATABASE]

 -a, --app APP       # app to run command against
 -r, --remote REMOTE # git remote of app to run command against

Commands for pg, type "heroku help pg:COMMAND" for more details:

 heroku pg [DATABASE]                  #
 heroku pg:info [DATABASE]             #
 heroku pg:wait [DATABASE]             #
</code>```

I looked around online and didn't see anything about these pg command deprications.  I checked my heroku CLI version: heroku-cli/5.3.0-5329fb8 (darwin-amd64) go1.6.2

Strange becuase I've been using these commands on this same computer many times recently and suddenly they're gone.

Have these pg been depricated (I doubt)?  If not does anyone know what I am doing wrong?  If so, anyone know how to do push/pull/capture in the new framework?

答:
The answer was that my CLI version was out-of-date.  I followed these instructions on my Mac:

```<code>rm -rf /usr/local/heroku
rm -rf ~/.local/share/heroku ~/.config/heroku ~/.cache/heroku
</code>```

And then re-installed using homebrew:

```<code>brew update
brew install heroku
</code>```

Apparently the new version of the CLI is supposed to keep itself up-to-date.

Body:
Just strange, I am doing back database maintenance, I tried to to a heroku pg:pull <DB_URL> local_db --app <appname> and it says:

pg:pull is not a heroku command.

I tried to create a backup with heroku pg:backups:capture <DB_URL> and i get this:

pg:backups:capture is not a heroku command.

Just trying heroku pg:backups shows:

pg:backups is not a heroku command.

Its strange because even in the --help section, looks like all the useful commands are gone:

heroku pg --help
Usage: heroku pg [DATABASE]

 -a, --app APP       # app to run command against
 -r, --remote REMOTE # git remote of app to run command against

Commands for pg, type "heroku help pg:COMMAND" for more details:

 heroku pg [DATABASE]                  #
 heroku pg:info [DATABASE]             #
 heroku pg:wait [DATABASE]             #

I looked around online and didn't see anything about these pg command deprications.  I checked my heroku CLI version: heroku-cli/5.3.0-5329fb8 (darwin-amd64) go1.6.2

Strange becuase I've been using these commands on this same computer many times recently and suddenly they're gone.

Have these pg been depricated (I doubt)?  If not does anyone know what I am doing wrong?  If so, anyone know how to do push/pull/capture in the new framework?

Body:
The answer was that my CLI version was out-of-date.  I followed these instructions on my Mac:

rm -rf /usr/local/heroku
rm -rf ~/.local/share/heroku ~/.config/heroku ~/.cache/heroku

And then re-installed using homebrew:

brew update
brew install heroku

Apparently the new version of the CLI is supposed to keep itself up-to-date.


问:
django error returned non-zero exit status 1
I'm uploading a file from Django web-site to my WordPress.

```<code>from subprocess import check_call
    try:
        check_call(['scp', filename, upload_filename])
         ....
    except (CalledProcessError, OSError):
        report['error_messages'].append("4 %s" % exc_info()[1])
        return report
</code>```

This gives error:

Command '['scp', '/uploads/test-01.txt',
  'mysite.com:/home/wp-content/uploads/test-01.txt']' returned non-zero
  exit status 1

Now,
If I do it manually from the console:

```<code>scp /uploads/test-01.txt mysite.com:/home/wp-content/uploads/test-01.txt
</code>```

it's working:

```<code>test-01.txt  100% 0  0.0KB/s 00:00
</code>```

(It's an empty file so 0 KB)

I don't understand why the scp fails from the Django. The error is not clear. What can I do?

答:
If you temporarily change your code to use check_output instead of check_call, then you can capture the standard error.

```<code>from subprocess import check_output, CalledProcessError, STDOUT

try:
    check_output(['scp', filename, upload_filename], stderr=STDOUT)
except CalledProcessError as e:
    print(e.output)  # output from STDERR should show what is going wrong
</code>```

This should give you a hint what is going wrong. It could be permissions, if the Django website is running as a different user than you when you tested the command in the console.

Body:
I'm uploading a file from Django web-site to my WordPress.

from subprocess import check_call
    try:
        check_call(['scp', filename, upload_filename])
         ....
    except (CalledProcessError, OSError):
        report['error_messages'].append("4 %s" % exc_info()[1])
        return report

This gives error:

Command '['scp', '/uploads/test-01.txt',
  'mysite.com:/home/wp-content/uploads/test-01.txt']' returned non-zero
  exit status 1

Now,
If I do it manually from the console:

scp /uploads/test-01.txt mysite.com:/home/wp-content/uploads/test-01.txt

it's working:

test-01.txt  100% 0  0.0KB/s 00:00

(It's an empty file so 0 KB)

I don't understand why the scp fails from the Django. The error is not clear. What can I do?

Body:
If you temporarily change your code to use check_output instead of check_call, then you can capture the standard error.

from subprocess import check_output, CalledProcessError, STDOUT

try:
    check_output(['scp', filename, upload_filename], stderr=STDOUT)
except CalledProcessError as e:
    print(e.output)  # output from STDERR should show what is going wrong

This should give you a hint what is going wrong. It could be permissions, if the Django website is running as a different user than you when you tested the command in the console.