问:
Pretty URL Conditional Rewrite
Our site allows for a pretty url 'etest.me/1234' where '1234' is a client id. As you can see below it redirects to our route.php file where we do our redirect. The problem is when a client uses 'etest.me' without the '/1234' they get the apache 'The requested URL /go/ was not found on this server.' message. I would like the url to go to another page when the '/1234' is missing.

Note that we have the domain and path forwarded to the non-existing '/go' directory so the rules below will catch it. The following is in our .htaccess file in the root directory.

```<code>RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1
</code>```

答:
You can add a new rule to handle this situation:</p>

```<code>RewriteRule ^go/$ ./another_script\.php
</code>```

Title: Pretty URL Conditional Rewrite

Body:
Our site allows for a pretty url 'etest.me/1234' where '1234' is a client id. As you can see below it redirects to our route.php file where we do our redirect. The problem is when a client uses 'etest.me' without the '/1234' they get the apache 'The requested URL /go/ was not found on this server.' message. I would like the url to go to another page when the '/1234' is missing.

Note that we have the domain and path forwarded to the non-existing '/go' directory so the rules below will catch it. The following is in our .htaccess file in the root directory.

RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1

Body:
You can add a new rule to handle this situation:

RewriteRule ^go/$ ./another_script\.php


来源: stackexchange

答:
Working perfectly fine for me. Hope this will work for you as well.</p>

```<code>RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9]+)$ /route.php?go=$1 //when client id exist
RewriteRule ^([a-zA-Z0-9]+)$ /index.php // when no client id
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pretty URL Conditional Rewrite

Body:
Working perfectly fine for me. Hope this will work for you as well.

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9]+)$ /route.php?go=$1 //when client id exist
RewriteRule ^([a-zA-Z0-9]+)$ /index.php // when no client id


问:
CSS selector for a checked radio button's label
Is it possible to apply a css(3) style to a label of a checked radio button?

I have the following markup:

```<code><input type="radio" id="rad" name="radio"/>
<label for="rad">A Label</label>
</code>```

What I was hoping is that

```<code>label:checked { font-weight: bold; }
</code>```

would do something, but alas it does not (as I expected).

Is there a selector that can achieve this sort of functionality?  You may surround with divs etc if that helps, but the best solution would be one that uses the label ''for'' attribute.

It should be noted that I am able to specify browsers for my application, so best of class css3 etc please.

答:
I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for= attribute set. So, let's check out a sample on SO:

* {
  padding: 0;
  margin: 0;
  background-color: #262626;
  color: white;
}

.radio-button {
  display: none;
}

#filter {
  display: flex;
  justify-content: center;
}

.filter-label {
  display: inline-block;
  border: 4px solid green;
  padding: 10px 20px;
  font-size: 1.4em;
  text-align: center;
  cursor: pointer;
}

main {
  clear: left;
}

.content {
  padding: 3% 10%;
  display: none;
}

h1 {
  font-size: 2em;
}

.date {
  padding: 5px 30px;
  font-style: italic;
}

.filter-label:hover {
  background-color: #505050;
}

#featured-radio:checked~#filter .featured,
#personal-radio:checked~#filter .personal,
#tech-radio:checked~#filter .tech {
  background-color: green;
}

#featured-radio:checked~main .featured {
  display: block;
}

#personal-radio:checked~main .personal {
  display: block;
}

#tech-radio:checked~main .tech {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">

<header id="filter">
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>
</header>

<main>
  <article class="content featured tech">
    <header>
      <h1>Cool Stuff</h1>
      <h3 class="date">Today</h3>
    </header>

    <p>
      I'm showing cool stuff in this article!
    </p>
  </article>

  <article class="content personal">
    <header>
      <h1>Not As Cool</h1>
      <h3 class="date">Tuesday</h3>
    </header>

    <p>
      This stuff isn't nearly as cool for some reason :(;
    </p>
  </article>

  <article class="content tech">
    <header>
      <h1>Cool Tech Article</h1>
      <h3 class="date">Last Monday</h3>
    </header>

    <p>
      This article has awesome stuff all over it!
    </p>
  </article>

  <article class="content featured personal">
    <header>
      <h1>Cool Personal Article</h1>
      <h3 class="date">Two Fridays Ago</h3>
    </header>

    <p>
      This article talks about how I got a job at a cool startup because I rock!
    </p>
  </article>
</main></code>```

Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input tags a child to only what they need to be (in this case - only the body element).

Since the label element doesn't actually utilize the :checked pseudo selector, it doesn't matter that the labels are stored in the header. It does have the added benefit that since the header is a sibling element we can use the ~ generic sibling selector to move from the input[type=radio]:checked DOM element to the header container and then use descendant/child selectors to access the labels themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.

Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the inputs. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!

Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to apply a css(3) style to a label of a checked radio button?

I have the following markup:

<input type="radio" id="rad" name="radio"/>
A Label

What I was hoping is that

label:checked { font-weight: bold; }

would do something, but alas it does not (as I expected).

Is there a selector that can achieve this sort of functionality?  You may surround with divs etc if that helps, but the best solution would be one that uses the label ''for'' attribute.

It should be noted that I am able to specify browsers for my application, so best of class css3 etc please.

Body:
I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for= attribute set. So, let's check out a sample on SO:

* {
  padding: 0;
  margin: 0;
  background-color: #262626;
  color: white;
}

.radio-button {
  display: none;
}

#filter {
  display: flex;
  justify-content: center;
}

.filter-label {
  display: inline-block;
  border: 4px solid green;
  padding: 10px 20px;
  font-size: 1.4em;
  text-align: center;
  cursor: pointer;
}

main {
  clear: left;
}

.content {
  padding: 3% 10%;
  display: none;
}

h1 {
  font-size: 2em;
}

.date {
  padding: 5px 30px;
  font-style: italic;
}

.filter-label:hover {
  background-color: #505050;
}

#featured-radio:checked~#filter .featured,
#personal-radio:checked~#filter .personal,
#tech-radio:checked~#filter .tech {
  background-color: green;
}

#featured-radio:checked~main .featured {
  display: block;
}

#personal-radio:checked~main .personal {
  display: block;
}

#tech-radio:checked~main .tech {
  display: block;
}

<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">

<header id="filter">
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>
</header>

<main>
  <article class="content featured tech">
    <header>
      <h1>Cool Stuff</h1>
      <h3 class="date">Today</h3>
    </header>

    <p>
      I'm showing cool stuff in this article!
    </p>
  </article>

  <article class="content personal">
    <header>
      <h1>Not As Cool</h1>
      <h3 class="date">Tuesday</h3>
    </header>

    <p>
      This stuff isn't nearly as cool for some reason :(;
    </p>
  </article>

  <article class="content tech">
    <header>
      <h1>Cool Tech Article</h1>
      <h3 class="date">Last Monday</h3>
    </header>

    <p>
      This article has awesome stuff all over it!
    </p>
  </article>

  <article class="content featured personal">
    <header>
      <h1>Cool Personal Article</h1>
      <h3 class="date">Two Fridays Ago</h3>
    </header>

    <p>
      This article talks about how I got a job at a cool startup because I rock!
    </p>
  </article>
</main>

Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input tags a child to only what they need to be (in this case - only the body element).

Since the label element doesn't actually utilize the :checked pseudo selector, it doesn't matter that the labels are stored in the header. It does have the added benefit that since the header is a sibling element we can use the ~ generic sibling selector to move from the input[type=radio]:checked DOM element to the header container and then use descendant/child selectors to access the labels themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.

Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the inputs. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!

Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.


问:
How to Run Shell Script at start in VM Virtualbox Ubuntu 16.04
I am trying to run a shell script which runs at system login. To try, I used an example script, which has two lines
   #!/bin/bash
   echo “Hello World”

I Followed all the instructions mentioned on this website http://www.cyberciti.biz/tips/linux-how-to-run-a-command-when-boots-up.html

Even I did some steps such as editing /etc/rc.local, but still when I login, I do not see Hello world output running on terminal.

Can anyone please explain what is wrong here or may be I am missing something?

答:
Add the line in /etc/profile under echo command as follows

```<code>echo “Hello World”
</code>```

Then execute the following command

```<code>source /etc/profile
</code>```

Body:
Add the line in /etc/profile under echo command as follows

echo “Hello World”

Then execute the following command

source /etc/profile


问:
Storing MP4 Files in Cassandra?
I am currently considering whether I should be storing media in an apache cassandra database. The use case is that the site will be taking uploads from users for insurance claims and will need to store the files so that they cannot be accessed outside the correct permissions and at the same time they need to be able to be streamed. If I store them on a file system, I have to deal with redundancy backups and so on using file system based old tech. I am not really interested in dealing with a CDN because many of them are expensive but also I the permissions to the whether you can view the content depends on information in the app such as which adjuster is assigned to the case and so on. In addition I want to stream the files rather than require download and view which would be the default mode with requests against a CDN. If I put them in cassandra it will handle the replication, storage and I can stream the binary data out of the database to the user with integrated permissions. What I am concerned about is if I will run into problems with cassandra rows having huge HD video files that are sometimes 1 to 2 hours long (testimony).

I am interested in the recommendations of Cassandra users concerning this issue. How would to solve the problem. Any lessons you have learned that I can benefit from. Would you suggest anything specific about the video tables if I go with cassandra storage? Is there any CDN that will stream, not require download, allow me to plug in permissions and at the same time be open source?

Thanks a bunch.

答:
Cassandra is definitely not designed and should not be used as an object store. I've worked on plenty of use cases where Cassandra was used as the metadata store alongside the object store/CDN and can complement them quite nicely.

Check out KillrVideo for inspiration: https://killrvideo.github.io/

Title: Storing MP4 Files in Cassandra?


问:
How to access specific values along with single key from Javascript associate array using for in loop
here is the associative array with multiple values for single key

```<code>var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};
</code>```

I want to display key who have one of its value ==3
that is, 250:[" Web Development","Build web applications",3]};

using for in loop.
Thanks

答:
```<code>var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};

for (key in course) { // repeat for each key
    if (~course[key].indexOf(3)) { // check if 3 is in array
        console.log(key);
    }
}
</code>```

Body:
here is the associative array with multiple values for single key

var course ={170:["Introduction to Programming"," Develop algorithms forcomputers",5],
250:[" Web Development","Build web applications",3]};

I want to display key who have one of its value ==3
that is, 250:[" Web Development","Build web applications",3]};

using for in loop.
Thanks


问:
Bad location accuracy with Google Maps API in Android
I have an app that uses a MapsActivity, the problem that I'm having is that when I got the realese key from the Android Developer site, the accuracy got a lot worse than with the debug key. When I was using the debug key, its accuracy was almost 100% good. Now my realese app with the realese key shows the location with a minimal error of 15 meters. Moreover, a friend of mine who used the app, told me that it actually showed his location 15 km far from his current position.

Is there any way to improve the Google Maps API's accuracy? Or is there any getLocation method improving it?

Thanks

答:
You can set the accuracy of the locationClient, using the locationRequest. E.g.

```<code>  mLocationRequest = LocationRequest.create();
  mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  mLocationClient.requestLocationUpdates(mLocationRequest, (LocationListener) this);
</code>```

You can also set the frequency of updates. If you need something highly precise, take a bunch of readings over a few seconds. Then look at the "accuracy" number on each reading. Toss out any readings whose accuracy is significantly less accurate than the others. Then average the rest

If you use lower accuracy, it's going to average gps data with wifi and cellular results. GPS consumes more battery, so it uses it less often on this setting. Wifi uses a physical address lookup, since its always moving me towards the public road near my house, even when I'm in the middle of it.

Body:
You can set the accuracy of the locationClient, using the locationRequest. E.g.

  mLocationRequest = LocationRequest.create();
  mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  mLocationClient.requestLocationUpdates(mLocationRequest, (LocationListener) this);

You can also set the frequency of updates. If you need something highly precise, take a bunch of readings over a few seconds. Then look at the "accuracy" number on each reading. Toss out any readings whose accuracy is significantly less accurate than the others. Then average the rest

If you use lower accuracy, it's going to average gps data with wifi and cellular results. GPS consumes more battery, so it uses it less often on this setting. Wifi uses a physical address lookup, since its always moving me towards the public road near my house, even when I'm in the middle of it.


问:
Serialport: Changing DatareceivedHandler
When opening the port I add the handler and it works.

What I need is, at some point, to change the handler to another subroutine..

What I did was:

```<code>AddHandler serport.DataReceived, AddressOf handler1
</code>```

And the first handler worked as expected...

after some time in code I do:

```<code>RemoveHandler serport.DataReceived, AddressOf handler1
AddHandler serport.DataReceived, AddressOf handler2
</code>```

But the second handler doesn't work. it never gets called.

What can I do?

I also have coded this routine to open a port :

```<code>Public Function OpenSerial(ByRef serialport As String, ByVal receivehandler As SerialDataReceivedEventHandler) As SerialPort
    Dim ser As SerialPort
    ser = New System.IO.Ports.SerialPort(serialport, 115200, Parity.None, 8, StopBits.One)
    With ser
        .Handshake = Handshake.None
        .ReadBufferSize = 10000
        .ReadTimeout = 500
        .WriteBufferSize = 10000
        .WriteTimeout = 500
        .RtsEnable = True
        .DtrEnable = True
        AddHandler .DataReceived, receivehandler
        AddHandler .ErrorReceived, AddressOf sErrorHandler
        .Encoding = System.Text.Encoding.Default
        .Open()
        .DiscardOutBuffer()
    End With
    OpenSerial = ser
End Function
</code>```

So I thought I could use it in this way:

```<code>Dim comSerial As SerialPort
comSerial = OpenSerial("COM1", AddressOf Handler1)
</code>```

Anyhow, however I do it I get the same result: the first time, the first handler works,   when redefined, even if the port is closed and reopened, the second handler never gets

called :(

答:
This question was bogus.

The program works fine. I was not receiving any data for another reason.

Body:
When opening the port I add the handler and it works.

What I need is, at some point, to change the handler to another subroutine..

What I did was:

AddHandler serport.DataReceived, AddressOf handler1

And the first handler worked as expected...

after some time in code I do:

RemoveHandler serport.DataReceived, AddressOf handler1
AddHandler serport.DataReceived, AddressOf handler2

But the second handler doesn't work. it never gets called.

What can I do?

I also have coded this routine to open a port :

Public Function OpenSerial(ByRef serialport As String, ByVal receivehandler As SerialDataReceivedEventHandler) As SerialPort
    Dim ser As SerialPort
    ser = New System.IO.Ports.SerialPort(serialport, 115200, Parity.None, 8, StopBits.One)
    With ser
        .Handshake = Handshake.None
        .ReadBufferSize = 10000
        .ReadTimeout = 500
        .WriteBufferSize = 10000
        .WriteTimeout = 500
        .RtsEnable = True
        .DtrEnable = True
        AddHandler .DataReceived, receivehandler
        AddHandler .ErrorReceived, AddressOf sErrorHandler
        .Encoding = System.Text.Encoding.Default
        .Open()
        .DiscardOutBuffer()
    End With
    OpenSerial = ser
End Function

So I thought I could use it in this way:

Dim comSerial As SerialPort
comSerial = OpenSerial("COM1", AddressOf Handler1)

Anyhow, however I do it I get the same result: the first time, the first handler works,   when redefined, even if the port is closed and reopened, the second handler never gets

called :(


问:
SQL Server : cannot connect to a named instance
I get the following error when trying to log in to a named SQL Server 2016 instance:

2017-03-31 09:25:19.12 Logon

  Error: 18456, Severity: 14, State: 5.

  2017-03-31 09:25:19.12 Logon

  Login failed for user 'domain\user'.  Reason: Could not find a login matching the name provided. [CLIENT: some-ip-address

SQL Server 2016 is a named instance on this box as it also has SQL Server 2012 instance and was installed using virtual accounts as outlined here

https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-windows-service-accounts-and-permissions

This named instance is running under port 1500.

Any ideas on how to connect to this server using SQL Server Management Studio ?

答:
A virtual account is used to run the SQL Server Service but you wouldn't be able to login using that account as there is no way to know the password.  In addition it's a local account only so domain\user is not going to work.

You should have had to grant SOME user access to the server, I think by default it grants the user who is installing the SQL Server so if you know that account you could try logging in with that.  Also if you know the sa password that should work too.

Past that you are probably looking at putting the server in single user mode and adding a login just to get in.  See here


问:
Get rid of SSL verification in Cordova in app browser
I am building a web and hybrid mobile app. The apps communicate with third party service using  ssl self-sign cert in staging env. Desktop browsers allow to accept invalid cert with risk warning but in iOS app I got this error

Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be "xxx" which could put your confidential information at risk.```

I understand the risk but as my third party provider can not provide valid ssl cert for the service in staging server so I have no choice.

Is there any configs/possibilities to allow invalid ssl cert in iOS and android inappbrowser plugin.

Really appreciate your help.

答:
iOS will always complain about invalid certificates, either in debug or release mode. To avoid this you should place the following code at the end of the AppDelegate.m file.

```<code>@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}
@end
</code>```

For Cordova users this file is placed in

```<code>project/platforms/ios/Project/Classes/AppDelegate.m
</code>```

Android (Cordova specific)

In Android the history is different. It will allow you to make requests to services with invalid certificates, but only if the app is compiled in build mode. On the other hand, when you would build the app in release mode (ie: to send the APK to a co-worker or stuff like that), the Cordova Web View, which is where the HTML + CSS + JS you wrote runs, will not allow you to make “insecure” requests. Once again, to avoid this you should modify a platform file. In this case the file will be CordovaWebViewClient.java

You would need to modify a method in the mentioned filed, like this:

```<code>public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  final String packageName = this.cordova.getActivity().getPackageName();
  final PackageManager pm = this.cordova.getActivity().getPackageManager();

  ApplicationInfo appInfo;
  try {
    appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
    if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
      // debug = true
      handler.proceed();
      return;
    } else {
      // debug = false
      // THIS IS WHAT YOU NEED TO CHANGE:
      // 1. COMMENT THIS LINE
      // super.onReceivedSslError(view, handler, error);
      // 2. ADD THESE TWO LINES
      // ---->
      handler.proceed();
      return;
      // <----
    }
  } catch (NameNotFoundException e) {
    // When it doubt, lock it out!
    super.onReceivedSslError(view, handler, error);
  }
}
</code>```

This file is placed in (Cordova v4 and below)

```<code>project/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewClient.java
</code>```

In newer versions of Cordova (v5 and later) the file is now placed in

```<code>project/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
</code>```

and

You should not use these solutions for production apps. This is just to test them or share them with co-workers.

Reference: Ignoring invalid SSL certificates on Cordova for Android and iOS

ContentLicense: CC BY-SA 4.0

Body:
I am building a web and hybrid mobile app. The apps communicate with third party service using  ssl self-sign cert in staging env. Desktop browsers allow to accept invalid cert with risk warning but in iOS app I got this error

Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be "xxx" which could put your confidential information at risk.

I understand the risk but as my third party provider can not provide valid ssl cert for the service in staging server so I have no choice.

Is there any configs/possibilities to allow invalid ssl cert in iOS and android inappbrowser plugin.

Really appreciate your help.

Body:
iOS will always complain about invalid certificates, either in debug or release mode. To avoid this you should place the following code at the end of the AppDelegate.m file.

@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}
@end

For Cordova users this file is placed in

project/platforms/ios/Project/Classes/AppDelegate.m

Android (Cordova specific)

In Android the history is different. It will allow you to make requests to services with invalid certificates, but only if the app is compiled in build mode. On the other hand, when you would build the app in release mode (ie: to send the APK to a co-worker or stuff like that), the Cordova Web View, which is where the HTML + CSS + JS you wrote runs, will not allow you to make “insecure” requests. Once again, to avoid this you should modify a platform file. In this case the file will be CordovaWebViewClient.java

You would need to modify a method in the mentioned filed, like this:

public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  final String packageName = this.cordova.getActivity().getPackageName();
  final PackageManager pm = this.cordova.getActivity().getPackageManager();

  ApplicationInfo appInfo;
  try {
    appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
    if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
      // debug = true
      handler.proceed();
      return;
    } else {
      // debug = false
      // THIS IS WHAT YOU NEED TO CHANGE:
      // 1. COMMENT THIS LINE
      // super.onReceivedSslError(view, handler, error);
      // 2. ADD THESE TWO LINES
      // ---->
      handler.proceed();
      return;
      // <----
    }
  } catch (NameNotFoundException e) {
    // When it doubt, lock it out!
    super.onReceivedSslError(view, handler, error);
  }
}

This file is placed in (Cordova v4 and below)

project/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewClient.java

In newer versions of Cordova (v5 and later) the file is now placed in

project/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java

and

You should not use these solutions for production apps. This is just to test them or share them with co-workers.

Reference: Ignoring invalid SSL certificates on Cordova for Android and iOS


问:
How to find max int in an array, while ignoring all numbers greater than first value?
Having trouble with this problem on an assignment I'm working on. I believe the problem is that the method will never return a negative value, but I'm not sure why that is or how to fix it. (Also, this has to be done using recursion, even though that is probably the worst way to accomplish it.

```<code>private static int findMaxOfLessThanFirst(int[] numList, int startIndex, int endIndex, int firstNum) {
    if(startIndex>-1&&startIndex<100){
        if(startIndex==endIndex){
            if(numList[startIndex]<=firstNum){
                return numList[startIndex];
            } else {
                return 222; //number used for testing
            }
        }
        if(numList[startIndex]>=
        findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum) &&
        numList[startIndex]<=firstNum){
            return numList[startIndex];
        } else {
            return findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum);
        }
    } return 333; //number used for testing
}
</code>```

The goal is to return the integer in the array that is largest while ignoring all of the numbers that are larger than numList[0].

答:
```<code>private static int findMaxOfLessThanFirst(int[] numList, int currentIndex, int len, int currentMax) {
    // when you reach the end of the array, return the currentMax
    if (currentIndex == len - 1) {
        return currentMax;
    }
    int firstElement = numList[0];
    // if the current element we are looking at in this stage of the recursion is greater
    // than the first element, ignore it and recurse on the next element
    if (numList[currentIndex] >= firstElement) {
        return findMaxOfLessThanFirst(numList, currentIndex + 1, len, currentMax);
    }
    int newMax;
    // if none of the previous conditions were true, and this current value is greater than
    // the currentMax, update the currentMax
    if (numList[currentIndex] > currentMax) {
        newMax = numList[currentIndex];
    }
    return findMaxOfLessThanFirst(numList, currentIndex + 1, len, newMax);
}
</code>```

<p>When you call this function, set your currentMax to something like the minimum integer value. This way you can check the return value at the end to see if you did, in fact, have an element less than the first element. </p>

Body:
Having trouble with this problem on an assignment I'm working on. I believe the problem is that the method will never return a negative value, but I'm not sure why that is or how to fix it. (Also, this has to be done using recursion, even though that is probably the worst way to accomplish it.

private static int findMaxOfLessThanFirst(int[] numList, int startIndex, int endIndex, int firstNum) {
    if(startIndex>-1&&startIndex<100){
        if(startIndex==endIndex){
            if(numList[startIndex]<=firstNum){
                return numList[startIndex];
            } else {
                return 222; //number used for testing
            }
        }
        if(numList[startIndex]>=
        findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum) &&
        numList[startIndex]<=firstNum){
            return numList[startIndex];
        } else {
            return findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum);
        }
    } return 333; //number used for testing
}

The goal is to return the integer in the array that is largest while ignoring all of the numbers that are larger than numList[0].

Body:
private static int findMaxOfLessThanFirst(int[] numList, int currentIndex, int len, int currentMax) {
    // when you reach the end of the array, return the currentMax
    if (currentIndex == len - 1) {
        return currentMax;
    }
    int firstElement = numList[0];
    // if the current element we are looking at in this stage of the recursion is greater
    // than the first element, ignore it and recurse on the next element
    if (numList[currentIndex] >= firstElement) {
        return findMaxOfLessThanFirst(numList, currentIndex + 1, len, currentMax);
    }
    int newMax;
    // if none of the previous conditions were true, and this current value is greater than
    // the currentMax, update the currentMax
    if (numList[currentIndex] > currentMax) {
        newMax = numList[currentIndex];
    }
    return findMaxOfLessThanFirst(numList, currentIndex + 1, len, newMax);
}

When you call this function, set your currentMax to something like the minimum integer value. This way you can check the return value at the end to see if you did, in fact, have an element less than the first element.


问:
How to add days to a date in mysql
kindly give your valuable suggestion to sort following mysql query.

days give the no of days available for the project eg: 6

Received_date shows the starting date of the project in this format   eg: 2017-03-27

So I just need to get the value of the Expired_date using MYSQL

```<code>Expired_date (Received_date + days ) = 2017-04-03
</code>```

kindly tell me what should i include in the ** some query **

```<code>SELECT
     tsc_document_status.warehouse_transfer_note_id,
     tsc_document_status.tsc_allocated_days AS days,
     tsc_document_status.tsc_accepted_Or_Created_date AS Received_date
     (******* some query ****) AS Expired_date
FROM
     tsc_document_status
</code>```

答:
Use the DATE_ADD function.

```<code>SELECT
t.warehouse_transfer_note_id,
t.tsc_allocated_days AS days,
t.tsc_accepted_Or_Created_date AS Received_date,
DATE_ADD(t.tsc_accepted_Or_Created_date, INTERVAL t.tsc_allocated_days DAY) AS Expired_date
FROM
tsc_document_status AS t
</code>```

Title: How to add days to a date in mysql

Body:
kindly give your valuable suggestion to sort following mysql query.

days give the no of days available for the project eg: 6

Received_date shows the starting date of the project in this format   eg: 2017-03-27

So I just need to get the value of the Expired_date using MYSQL

Expired_date (Received_date + days ) = 2017-04-03

kindly tell me what should i include in the ** some query **

SELECT
     tsc_document_status.warehouse_transfer_note_id,
     tsc_document_status.tsc_allocated_days AS days,
     tsc_document_status.tsc_accepted_Or_Created_date AS Received_date
     (******* some query ****) AS Expired_date
FROM
     tsc_document_status

Body:
Use the DATE_ADD function.

SELECT
t.warehouse_transfer_note_id,
t.tsc_allocated_days AS days,
t.tsc_accepted_Or_Created_date AS Received_date,
DATE_ADD(t.tsc_accepted_Or_Created_date, INTERVAL t.tsc_allocated_days DAY) AS Expired_date
FROM
tsc_document_status AS t


问:
Not a statement? (Bluej)
So the program i question is supposed to be really simple, take three inputted numbers, and multiply them by itself and display the result, only, Bluej insists that each time I ask it to multiply, it's not a statement. (Tbf, i'm new in the java business, so i still might be 100% wrong)</p>

```<code>private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0) {
        num1 * num1;
        System.out.println (num1);
    } else {
        System.out.println( "Enter a correct number, please.");
    }

    if ( num2 > 0) {
        num2 * num2;
        System.out.println (num2);
    } else {
        System.out.println("Really? Again. Do the right thing this time, jeez.");
    }

    if ( num3 > 0) {
        num3*num3;
        System.out.println (num3);
    } else {
        System.out.println("Just make it more then one!!");
    }
}
</code>```

答:
I think it's been Like this.

code

```<code>private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0 && num2 > 0 && num3 > 0) {
        num1 *= num1;
        num2 *= num2;
        num3 *= num3;
        System.out.println (num1);
        System.out.println (num2);
        System.out.println (num3);
    } else {
        System.out.println( "Enter positive numbers please.");
    }
    return 0;
}
</code>```

OR you can do like this also.

code

```<code>private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0 && num2 > 0 && num3 > 0) {

        System.out.println (num1*num1);
        System.out.println (num2*num2);
        System.out.println (num3*num3);
    } else {
        System.out.println( "Enter positive numbers please.");
    }
    return 0;
}
</code>```

Title: Not a statement? (Bluej)

Body:
So the program i question is supposed to be really simple, take three inputted numbers, and multiply them by itself and display the result, only, Bluej insists that each time I ask it to multiply, it's not a statement. (Tbf, i'm new in the java business, so i still might be 100% wrong)

private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0) {
        num1 * num1;
        System.out.println (num1);
    } else {
        System.out.println( "Enter a correct number, please.");
    }

    if ( num2 > 0) {
        num2 * num2;
        System.out.println (num2);
    } else {
        System.out.println("Really? Again. Do the right thing this time, jeez.");
    }

    if ( num3 > 0) {
        num3*num3;
        System.out.println (num3);
    } else {
        System.out.println("Just make it more then one!!");
    }
}

Body:
I think it's been Like this.

code

private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0 && num2 > 0 && num3 > 0) {
        num1 *= num1;
        num2 *= num2;
        num3 *= num3;
        System.out.println (num1);
        System.out.println (num2);
        System.out.println (num3);
    } else {
        System.out.println( "Enter positive numbers please.");
    }
    return 0;
}

OR you can do like this also.

code

private static double Square ( int num1, int num2, int num3) {

    if ( num1 > 0 && num2 > 0 && num3 > 0) {

        System.out.println (num1*num1);
        System.out.println (num2*num2);
        System.out.println (num3*num3);
    } else {
        System.out.println( "Enter positive numbers please.");
    }
    return 0;
}


问:
Can not deserialize instance of java.lang.String[] out of VALUE_STRING token
Can not deserialize instance of java.lang.String[] out of VALUE_STRING token [...] (through reference chain: [...].model.User["ethnicities"])

I have a user object with a property ethnicities.

From what I can tell the error is because the json "type" doesn't match the property type but in my case both are String arrays.

Am I doing something wrong?

Also, I can't figure out what VALUE_STRING represents in the parsing.

Server-side is using Loopback and the ethnicities property is defined as such:

"ethnicities": [
      ""
    ]

Android client is using Jackson to map the json to the pojo and vice versa.  Ethnicities in pojo looks like this:

```<code>private String[] ethnicities;
public String[] getEthnicities() {return ethnicities;}
public void setEthnicities(String[] ethnicities) {this.ethnicities = ethnicities;}
</code>```

The mapping to json:

```<code>try {
    ObjectMapper mapper = new ObjectMapper();
    jsonUserObject = mapper.writeValueAsString(user);
} catch (IOException e) {
    System.out.println("IOException converting user object to JSON");
}
</code>```

and the mapping from json:

```<code>try {
    ObjectMapper mapper = new ObjectMapper();
    user = mapper.readValue(userObjectJSON, User.class);
} catch (IOException e) {
    System.out.println("IOException converting JSON to user object");
}
</code>```

Here's some examples of incoming json:

```<code>"ethnicities": [
      "Asian",
      "American Indian",
      "Hispanic"
    ]

"ethnicities": [
  "Caucasian"
]

"ethnicities": null
</code>```

Thanks!

答:
Try setting this flag to ObjectMapper :

```<code>mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
</code>```

Body:
Can not deserialize instance of java.lang.String[] out of VALUE_STRING token [...] (through reference chain: [...].model.User["ethnicities"])

I have a user object with a property ethnicities.

From what I can tell the error is because the json "type" doesn't match the property type but in my case both are String arrays.

Am I doing something wrong?

Also, I can't figure out what VALUE_STRING represents in the parsing.

Server-side is using Loopback and the ethnicities property is defined as such:

"ethnicities": [
      ""
    ]

Android client is using Jackson to map the json to the pojo and vice versa.  Ethnicities in pojo looks like this:

private String[] ethnicities;
public String[] getEthnicities() {return ethnicities;}
public void setEthnicities(String[] ethnicities) {this.ethnicities = ethnicities;}

The mapping to json:

try {
    ObjectMapper mapper = new ObjectMapper();
    jsonUserObject = mapper.writeValueAsString(user);
} catch (IOException e) {
    System.out.println("IOException converting user object to JSON");
}

and the mapping from json:

try {
    ObjectMapper mapper = new ObjectMapper();
    user = mapper.readValue(userObjectJSON, User.class);
} catch (IOException e) {
    System.out.println("IOException converting JSON to user object");
}

Here's some examples of incoming json:

"ethnicities": [
      "Asian",
      "American Indian",
      "Hispanic"
    ]

"ethnicities": [
  "Caucasian"
]

"ethnicities": null

Thanks!

Body:
Try setting this flag to ObjectMapper :

mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);


问:
Logging exceptions in asp.net core / kestrel
The docs show how to set a page for when an exception occurs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling

But how do I record the details of the exception in a log file on my server?

Does kestrel log exceptions and errors anywhere by default or do I have to do this manually?

Are there any examples or documentation available?

答:
There's a package called Serilog.Extensions.Logging.File that adds file logging with a single line of code (AddFile()):

```<code>public void Configure(IApplicationBuilder app,
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddFile("Logs/myapp-{Date}.txt");
</code>```

From this article.

Body:
There's a package called Serilog.Extensions.Logging.File that adds file logging with a single line of code (AddFile()):

public void Configure(IApplicationBuilder app,
                      IHostingEnvironment env,
                      ILoggerFactory loggerFactory)
{
    loggerFactory.AddFile("Logs/myapp-{Date}.txt");

From this article.


问:
What exactly does lowering the priority of a constraint do?
I am constructing a variable size table view within another view. The table view should not scroll so I am programmatically determining its content size and adjusting a height constraint so that the table view always fits its content.

The problem I run into is a warning about a broken constraint:

```<code>Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x170498b00 h=--& v=--& UIView:0x1024f2c90.height == 322   (active)>",
"<NSLayoutConstraint:0x17428d660 UITableView:0x103152400.height == 322   (active)>",
"<NSLayoutConstraint:0x174482da0 V:[UITableView:0x103152400]-(27)-|   (active, names: '|':UIView:0x1024f2c90 )>",
"<NSLayoutConstraint:0x17429da10 V:|-(16)-[UITableView:0x103152400]   (active, names: '|':UIView:0x1024f2c90 )>"
)
</code>```

To fix this, I tried 2 things:

Set translatesAutoresizingMaskIntoConstraints = false.  This causes everything to go haywire with the table view.

Lower the priority of the adjustable height constraint to 999.

Point 2 solves my problem and I'm able to adjust the height of the view using the lower priority constraint.  But, I don't understand why this works.

So, how does Auto Layout interpret the priority of a constraint?  I would've expected the NSAutoresizingMaskLayoutConstraint to take over the lower priority constraint and make it so I could not resize the view using the constraint.

答:
To answer the question in the headline: Lowering the priority of a constraint tells the autolayout that the constraint is less important than all constraints with a higher priority.

This means that if two constraints are conflicting autolayout will use the one with the highest priority and disregard the other.

If two required constraints with identical priorities conflict, you will have an error message like the one you describe.

Body:
I am constructing a variable size table view within another view. The table view should not scroll so I am programmatically determining its content size and adjusting a height constraint so that the table view always fits its content.

The problem I run into is a warning about a broken constraint:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x170498b00 h=--& v=--& UIView:0x1024f2c90.height == 322   (active)>",
"<NSLayoutConstraint:0x17428d660 UITableView:0x103152400.height == 322   (active)>",
"<NSLayoutConstraint:0x174482da0 V:[UITableView:0x103152400]-(27)-|   (active, names: '|':UIView:0x1024f2c90 )>",
"<NSLayoutConstraint:0x17429da10 V:|-(16)-[UITableView:0x103152400]   (active, names: '|':UIView:0x1024f2c90 )>"
)

To fix this, I tried 2 things:

Set translatesAutoresizingMaskIntoConstraints = false.  This causes everything to go haywire with the table view.

Lower the priority of the adjustable height constraint to 999.

Point 2 solves my problem and I'm able to adjust the height of the view using the lower priority constraint.  But, I don't understand why this works.

So, how does Auto Layout interpret the priority of a constraint?  I would've expected the NSAutoresizingMaskLayoutConstraint to take over the lower priority constraint and make it so I could not resize the view using the constraint.


问:
Webview clicks not opening up links (Works in emulator not Device)
So as you can read form the title, that is the problem I am facing. All is well when I click the links from my webView in the emulator but when I transition into my phone, nothing happens when it is clicked. Here is what I have so far.</p>

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.main_selection_tab);

    dbh = new MyDBHandler(this);

    String url = "http://somelinkhere.com";

    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.loadUrl(url);

    addTabsOnCreate();
    populateBodypartListView();
}
</code>```

答:
I can't explain how it works in emulator and not working in actual devices. But it seems you have to override shouldOverrideUrlLoading method in webviewclient.

```<code>webView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return  false;
        }
    });
</code>```

return false means this webview will handle the urls.
more details from doumentation.

Body:
So as you can read form the title, that is the problem I am facing. All is well when I click the links from my webView in the emulator but when I transition into my phone, nothing happens when it is clicked. Here is what I have so far.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.main_selection_tab);

    dbh = new MyDBHandler(this);

    String url = "http://somelinkhere.com";

    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.loadUrl(url);

    addTabsOnCreate();
    populateBodypartListView();
}

Body:
I can't explain how it works in emulator and not working in actual devices. But it seems you have to override shouldOverrideUrlLoading method in webviewclient.

webView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return  false;
        }
    });

return false means this webview will handle the urls.
more details from doumentation.


问:
Jsoup parse to get text including greater than (>) and less than (<) symbol
There is text in html like "There is a nothing special <<string>> haha".

I want to get complete text including << and >>, so the output want to look like There is a nothing special <<string>> haha.

I had done

```<code>Elements e = element.select("a");
String text = e.text();
</code>```

but the output is There is a nothing special <> haha.

If print the e.html(), it would be

```<code>There is a nothing special <
<string>
>haha
</string>
</code>```

How do I fix it ?

答:
The input is not valid HTML. jsoup follows the rules defined in the HTML5 specification on how to parse such non-conforming input. What you end up with is what you see as output of e.html().

This transformation is lossy and there's no way to retrieve the original input when using jsoup.

Side note: The string There is a nothing special <<string>> haha should be encoded like this in an HTML document: There is a nothing special <<string>> haha

Body:
There is text in html like "There is a nothing special <<string>> haha".

I want to get complete text including << and >>, so the output want to look like There is a nothing special <<string>> haha.

I had done

Elements e = element.select("a");
String text = e.text();

but the output is There is a nothing special <> haha.

If print the e.html(), it would be

There is a nothing special <
<string>
>haha
</string>

How do I fix it ?

Body:
The input is not valid HTML. jsoup follows the rules defined in the HTML5 specification on how to parse such non-conforming input. What you end up with is what you see as output of e.html().

This transformation is lossy and there's no way to retrieve the original input when using jsoup.

Side note: The string There is a nothing special <<string>> haha should be encoded like this in an HTML document: There is a nothing special &lt;&lt;string&gt;&gt; haha


问:
Constructor expecting missing call to other constructor / candidate expects 1 argument, 0 provided?
You may have seen my post yesterday about the issues I had been having with my text-based adventure game. I got all of that fixed up and added some functionality, but in adding some inventory arrays of custom Slot objects my Character object decided to stop recognizing their initialization.

Here's the basic code:

Character Class

```<code>class Character {
    InvSlot inventory[30];
    FoodSlot foodInv[10];
    //Declaring armor slots, class, race, stats, etc

public:
    //All of the function declarations
</code>```

Character Constructor

```<code>Character::Character() :
    //Initializing armor slots, class, race, stats, etc to default values
{
    InvSlot inventory[30] = {emptyInv,...,emptyInv}; //The other 28 values are omitted here.
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood}; //The other 8 values are omitted here.
}
</code>```

InvSlot and FoodSlot Structs w/ Basic Empty Slots

```<code>struct InvSlot {
    bool isUsed;
    Item item;
    InvSlot(Item i);
};

struct FoodSlot {
    bool isUsed;
    Item item;
    FoodSlot(Food f);
};

InvSlot::InvSlot(Item i) : isUsed(false), item(i){}
InvSlot emptyInv = InvSlot(NoItem); //NoItem is a basic object of type Item which works

FoodSlot::FoodSlot(Food f) : isUsed(false, food(f), quantity(0){}
FoodSlot emptyFood = FoodSlot(NoFood); //Same deal with NoFood
</code>```

The Errors

First of all, the struct declarations and constructor definitions for InvSlot and FoodSlot are giving me the issue of candidate expects 1 argument, 0 provided. Second of all, the actual errors are on the final initializer in the Character constructor (before the curly braces): no matching function for call to 'FoodSlot::FoodSlot()' and no matching function for call to 'InvSlot::InvSlot()'. The thing is, I have already initialized the arrays in the curly braces and they aren't returning any errors themselves. On top of this, these two are the only two parameters for the character class which even use the InvSlot or FoodSlot objects. Can anybody help figure out what's going on, and how to fix it? I already checked other similar questions but they didn't help. Let me know if I need to add anything or if I missed something when typing up this post.

Thanks in advance!

答:
The sequence of what is currently happening:

(somewhere in main) Attempt to create an instance of Character.

Character is creating all of its data members: inventory and foodInv.

Since inventory is an array the constructor needs to be called 30 times, and it needs to be called before the execution of the constructor of Character. Because you don't provide the compiler with anything to call specifically, it will attempt to call the default constructor. And since you have defined parameterised constructor, the default has been deleted.

What you need:

Option1

in your header file:

```<code>class Character {
    InvSlot inventory[30] = {emptyInv,...,emptyInv};
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood};
</code>```

This is probably not the best option, since you clutter the header.

Option2

In the definition of your constructor:

```<code>Character::Character()
  : inventory{{emptyInv,...,emptyInv}}, foodinv{{emptyFood,...,emptyFood}}
{
}
</code>```

Funny thing is that you already have the : symbol in your constructor definition, meaning that you have first attempted the correct solution (or perhaps you were unaware of the meaning of that character). It is there specifically to call constructors on the fields.

Body:
You may have seen my post yesterday about the issues I had been having with my text-based adventure game. I got all of that fixed up and added some functionality, but in adding some inventory arrays of custom Slot objects my Character object decided to stop recognizing their initialization.

Here's the basic code:

Character Class

class Character {
    InvSlot inventory[30];
    FoodSlot foodInv[10];
    //Declaring armor slots, class, race, stats, etc

public:
    //All of the function declarations

Character Constructor

Character::Character() :
    //Initializing armor slots, class, race, stats, etc to default values
{
    InvSlot inventory[30] = {emptyInv,...,emptyInv}; //The other 28 values are omitted here.
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood}; //The other 8 values are omitted here.
}

InvSlot and FoodSlot Structs w/ Basic Empty Slots

struct InvSlot {
    bool isUsed;
    Item item;
    InvSlot(Item i);
};

struct FoodSlot {
    bool isUsed;
    Item item;
    FoodSlot(Food f);
};

InvSlot::InvSlot(Item i) : isUsed(false), item(i){}
InvSlot emptyInv = InvSlot(NoItem); //NoItem is a basic object of type Item which works

FoodSlot::FoodSlot(Food f) : isUsed(false, food(f), quantity(0){}
FoodSlot emptyFood = FoodSlot(NoFood); //Same deal with NoFood

The Errors

First of all, the struct declarations and constructor definitions for InvSlot and FoodSlot are giving me the issue of candidate expects 1 argument, 0 provided. Second of all, the actual errors are on the final initializer in the Character constructor (before the curly braces): no matching function for call to 'FoodSlot::FoodSlot()' and no matching function for call to 'InvSlot::InvSlot()'. The thing is, I have already initialized the arrays in the curly braces and they aren't returning any errors themselves. On top of this, these two are the only two parameters for the character class which even use the InvSlot or FoodSlot objects. Can anybody help figure out what's going on, and how to fix it? I already checked other similar questions but they didn't help. Let me know if I need to add anything or if I missed something when typing up this post.

Thanks in advance!

Body:
The sequence of what is currently happening:

(somewhere in main) Attempt to create an instance of Character.

Character is creating all of its data members: inventory and foodInv.

Since inventory is an array the constructor needs to be called 30 times, and it needs to be called before the execution of the constructor of Character. Because you don't provide the compiler with anything to call specifically, it will attempt to call the default constructor. And since you have defined parameterised constructor, the default has been deleted.

What you need:

Option1

in your header file:

class Character {
    InvSlot inventory[30] = {emptyInv,...,emptyInv};
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood};

This is probably not the best option, since you clutter the header.

Option2

In the definition of your constructor:

Character::Character()
  : inventory{{emptyInv,...,emptyInv}}, foodinv{{emptyFood,...,emptyFood}}
{
}

Funny thing is that you already have the : symbol in your constructor definition, meaning that you have first attempted the correct solution (or perhaps you were unaware of the meaning of that character). It is there specifically to call constructors on the fields.


问:
Laravel Multiple orderBy Group Views by Day
I'm using OctoberCMS based on Laravel and Twig.

I'm trying to sort a list of images from the database using orderBy.

I need to display the images grouped by date (desc), then ordered by views (desc) within that date.

I read here to use multiple orderBy passes.

Database Records

```<code>name     | created_at          | views
---------------------------------------
image 01 | 2017-03-27 07:08:31 | 3
image 02 | 2017-03-27 01:19:44 | 25
image 03 | 2017-03-25 01:43:06 | 9
image 04 | 2017-03-25 04:19:43 | 1
image 05 | 2017-03-25 15:19:43 | 12
image 06 | 2017-03-22 03:07:06 | 4
image 07 | 2017-03-22 08:10:07 | 16
image 08 | 2017-03-21 09:04:29 | 39
image 09 | 2017-03-20 07:38:31 | 5
image 10 | 2017-03-20 05:32:24 | 28
</code>```

Laravel

orderBy

Successfully orders by Date created_at, but ignores ordering by views. May be because of time.

```<code>$this->page["scopeGallery"] = Gallery::orderBy('created_at', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();
</code>```

groupBy

Returns null.

```<code>$this->page["scopeGallery"] = Gallery::select(\DB::raw('DATE(created_at) as day'))
                                      ->groupBy('day')
                                      ->orderBy('views', 'desc')
                                      ->get();
</code>```

Twig

```<code>{% for image in this.page.scopeGallery %}
    image.name
{% endfor %}
</code>```

Result I'm looking for

```<code>name     | created_at | views
------------------------------
image 02 | 2017-03-27 | 25
image 01 | 2017-03-27 | 3

image 05 | 2017-03-25 | 12
image 03 | 2017-03-25 | 9
image 04 | 2017-03-25 | 1

image 07 | 2017-03-22 | 16
image 06 | 2017-03-22 | 4

image 08 | 2017-03-21 | 39

image 10 | 2017-03-20 | 28
image 09 | 2017-03-20 | 5
</code>```

答:
I presume the created_at field is datetime.
Your first query will order by datetime and therefore the secondary orderby wont do much as the it will be applied if there are serveral created_at values that match.

This should work:

```<code>$this->page["scopeGallery"] = Gallery::orderByRaw(\DB::raw('DATE(created_at) desc'))
                                  ->orderBy('views', 'desc')
                                  ->get();
</code>```

That will create the following query:

```<code>select * from `your_table` order by DATE(created_at) desc, `views` desc
</code>```

Body:
I'm using OctoberCMS based on Laravel and Twig.

I'm trying to sort a list of images from the database using orderBy.

I need to display the images grouped by date (desc), then ordered by views (desc) within that date.

I read here to use multiple orderBy passes.

Database Records

name     | created_at          | views
---------------------------------------
image 01 | 2017-03-27 07:08:31 | 3
image 02 | 2017-03-27 01:19:44 | 25
image 03 | 2017-03-25 01:43:06 | 9
image 04 | 2017-03-25 04:19:43 | 1
image 05 | 2017-03-25 15:19:43 | 12
image 06 | 2017-03-22 03:07:06 | 4
image 07 | 2017-03-22 08:10:07 | 16
image 08 | 2017-03-21 09:04:29 | 39
image 09 | 2017-03-20 07:38:31 | 5
image 10 | 2017-03-20 05:32:24 | 28

Laravel

orderBy

Successfully orders by Date created_at, but ignores ordering by views. May be because of time.

$this->page["scopeGallery"] = Gallery::orderBy('created_at', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();

groupBy

Returns null.

$this->page["scopeGallery"] = Gallery::select(\DB::raw('DATE(created_at) as day'))
                                      ->groupBy('day')
                                      ->orderBy('views', 'desc')
                                      ->get();

Twig

{% for image in this.page.scopeGallery %}
    image.name
{% endfor %}

Result I'm looking for

name     | created_at | views
------------------------------
image 02 | 2017-03-27 | 25
image 01 | 2017-03-27 | 3

image 05 | 2017-03-25 | 12
image 03 | 2017-03-25 | 9
image 04 | 2017-03-25 | 1

image 07 | 2017-03-22 | 16
image 06 | 2017-03-22 | 4

image 08 | 2017-03-21 | 39

image 10 | 2017-03-20 | 28
image 09 | 2017-03-20 | 5

Body:
I presume the created_at field is datetime.
Your first query will order by datetime and therefore the secondary orderby wont do much as the it will be applied if there are serveral created_at values that match.

This should work:

$this->page["scopeGallery"] = Gallery::orderByRaw(\DB::raw('DATE(created_at) desc'))
                                  ->orderBy('views', 'desc')
                                  ->get();

That will create the following query:

select * from `your_table` order by DATE(created_at) desc, `views` desc


问:
iOS 4 app crashes at startup on iOS 3.1.3: Symbol not found: __NSConcreteStackBlock
I'm running Xcode 3.2.3 with the iOS 4.0 SDK. I built my app with Base SDK = iphoneos4.0, Active SDK = iphoneos4.0, Deployment Target = 3.1.3, and Architecture = standard (arm6 arm7). Compiler = GCC 4.2. As I understand it, this is the correct way to build an app for both iOS 4 and 3.

The app runs fine on devices running iOS 4. But it crashes on startup when you try to run it on a device with iOS 3.1.3 (an iPod Touch 1G):

```<code>dyld: Symbol not found: __NSConcreteStackBlock
  Referenced from: /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
  Expected in: /usr/lib/libSystem.B.dylib
</code>```

It appears to be an issue with a fairly "low level" dynamically-linked library, BEFORE my main() function even gets called. I have even tried re-starting the device, etc., with no luck. Here's part of the the crash log:

```<code>Process:         MyApp [60]
Path:            /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
Identifier:      MyApp
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-07-22 17:16:17.942 -0400
OS Version:      iPhone OS 3.1.3 (7E18)
Report Version:  104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x00000001, 0xe7ffdefe
Crashed Thread:  0

Dyld Error Message:
  Symbol not found: __NSConcreteStackBlock
  Referenced from: /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
  Expected in: /usr/lib/libSystem.B.dylib
  Dyld Version: 149

Binary Images:
    0x1000 -    0x80fff +MyApp armv6  <d5f0ff6f233b4b034c222c16438c88d9> /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
0x2fe00000 - 0x2fe26fff  dyld armv6  <544395a4b5546114b878d5131a84fd7f> /usr/lib/dyld
0x30410000 - 0x30536fff  libSystem.B.dylib armv6  <0373fd64e915a17160732b29d343f95f> /usr/lib/libSystem.B.dylib
</code>```

Thanks for any advice!

答: If you happen to be using the cocos2d libraries, there is a cleaner way to do this, you should configure the cocos2d target's Deployment target to 3.0</p>

Body:
I'm running Xcode 3.2.3 with the iOS 4.0 SDK. I built my app with Base SDK = iphoneos4.0, Active SDK = iphoneos4.0, Deployment Target = 3.1.3, and Architecture = standard (arm6 arm7). Compiler = GCC 4.2. As I understand it, this is the correct way to build an app for both iOS 4 and 3.

The app runs fine on devices running iOS 4. But it crashes on startup when you try to run it on a device with iOS 3.1.3 (an iPod Touch 1G):

dyld: Symbol not found: __NSConcreteStackBlock
  Referenced from: /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
  Expected in: /usr/lib/libSystem.B.dylib

It appears to be an issue with a fairly "low level" dynamically-linked library, BEFORE my main() function even gets called. I have even tried re-starting the device, etc., with no luck. Here's part of the the crash log:

Process:         MyApp [60]
Path:            /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
Identifier:      MyApp
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-07-22 17:16:17.942 -0400
OS Version:      iPhone OS 3.1.3 (7E18)
Report Version:  104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x00000001, 0xe7ffdefe
Crashed Thread:  0

Dyld Error Message:
  Symbol not found: __NSConcreteStackBlock
  Referenced from: /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
  Expected in: /usr/lib/libSystem.B.dylib
  Dyld Version: 149

Binary Images:
    0x1000 -    0x80fff +MyApp armv6  <d5f0ff6f233b4b034c222c16438c88d9> /var/mobile/Applications/192B30ED-16AC-431E-B0E9-67C1F41FD5DA/MyApp.app/MyApp
0x2fe00000 - 0x2fe26fff  dyld armv6  <544395a4b5546114b878d5131a84fd7f> /usr/lib/dyld
0x30410000 - 0x30536fff  libSystem.B.dylib armv6  <0373fd64e915a17160732b29d343f95f> /usr/lib/libSystem.B.dylib

Thanks for any advice!


问:
why is filling a row of a matrix much slower than filling vector of the same size
Why is assigning to a row/column of a matrix much slower than filling vector of the same size?

```<code>N <- 1e8
u <- numeric(N)
system.time(u <- 1:N)
##user  system elapsed
##0.091   0.100   0.191
u <- matrix(nrow=2,ncol=N)
system.time(u[1,] <- 1:N)
##user  system elapsed
##2.772   0.436   3.212
</code>```

My main concern is with arrays, but I imagine the answer for matrices will explain arrays as well.

```<code>N <- 1e3
uu <- matrix(N,N)
system.time({uu <- 1:(N*N)})
##user  system elapsed
##0.068   0.120   0.188
uu <- array(dim=c(2,N,N))
system.time({uu[1,,] <- 1:(N*N)})
##user  system elapsed
##4.409   0.241   4.657
</code>```

(I could not tell if assigning to an element of a large pre-allocated vector is slower than assigning to a variable, because the former always takes 0 time for any vector my system is capable of allocating.)

答:
Because you are filling in a row not a column. You get more cache misses, as well as address arithmetic overhead (locating base address for each column).

In R, a matrix, or a general array is essentially a long vector; dimension is just an attribute. The fastest index is the rightmost one, so elements are contiguous when you scan the matrix by its column, or an array by its last margin. This means, on a typical machine with 64 bytes L1 cache line size which can hold 8 double precision numeric, you have 1 cache miss per scanning 8 elements. But if you access a matrix of two rows by row for example, you get 1 cache miss per 4 elements.

Another issue, giving you an unfair comparison, is you are comparing overwriting with assignment, not overwriting with overwriting. Using u[] <- 1:N will force an overwriting to the preallocated vector u.

Consider the following benchmarking:

```<code>library(microbenchmark)
n <- 10000
u <- 1:n
m1 <- matrix(0, n, 2)
m2 <- matrix(0, 2, n)
x <- numeric(n)
microbenchmark (m1[,1] <- u, m2[1,] <- u, x[] <- u)
</code>```

Body:
Why is assigning to a row/column of a matrix much slower than filling vector of the same size?

N <- 1e8
u <- numeric(N)
system.time(u <- 1:N)
##user  system elapsed
##0.091   0.100   0.191
u <- matrix(nrow=2,ncol=N)
system.time(u[1,] <- 1:N)
##user  system elapsed
##2.772   0.436   3.212

My main concern is with arrays, but I imagine the answer for matrices will explain arrays as well.

N <- 1e3
uu <- matrix(N,N)
system.time({uu <- 1:(N*N)})
##user  system elapsed
##0.068   0.120   0.188
uu <- array(dim=c(2,N,N))
system.time({uu[1,,] <- 1:(N*N)})
##user  system elapsed
##4.409   0.241   4.657

(I could not tell if assigning to an element of a large pre-allocated vector is slower than assigning to a variable, because the former always takes 0 time for any vector my system is capable of allocating.)

Body:
Because you are filling in a row not a column. You get more cache misses, as well as address arithmetic overhead (locating base address for each column).

In R, a matrix, or a general array is essentially a long vector; dimension is just an attribute. The fastest index is the rightmost one, so elements are contiguous when you scan the matrix by its column, or an array by its last margin. This means, on a typical machine with 64 bytes L1 cache line size which can hold 8 double precision numeric, you have 1 cache miss per scanning 8 elements. But if you access a matrix of two rows by row for example, you get 1 cache miss per 4 elements.

Another issue, giving you an unfair comparison, is you are comparing overwriting with assignment, not overwriting with overwriting. Using u[] <- 1:N will force an overwriting to the preallocated vector u.

Consider the following benchmarking:

library(microbenchmark)
n <- 10000
u <- 1:n
m1 <- matrix(0, n, 2)
m2 <- matrix(0, 2, n)
x <- numeric(n)
microbenchmark (m1[,1] <- u, m2[1,] <- u, x[] <- u)


问:
Get attachment from single page by id, and paged it. (Wordpress)
How to get attachment from single page by ID, and set 12 img per page?

'post_parent' => 145, // not working, but without this param I get all attachments

```<code><?php
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post_parent' => 145, // not working, but without this param I get all attachments
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ( $attachment->have_posts() ) :
                    while ( $attachment->have_posts() ) : $attachment->the_post();

            ?>
                        <div class="gallery__item"><a href="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" alt=""></a></div>
            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>
</code>```

答:
I found out what the problem was. I use post_parent and tells post ID, thinking that take all attachments from this post, but WP_Query returns me ID's of images.

I get all id's of images in array with get_post_gallery()

```<code>$gal = get_post_gallery(11,false);
</code>```

and explode it

```<code>$ids = explode(',', $gal['ids']);
</code>```

after then everything worked!

also I use post__in insted post_parent

The final code:

```<code><?php
                $gal = get_post_gallery(11,false);
                $ids = explode(',', $gal['ids']);
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post__in' => $ids,
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ($attachment -> have_posts() ) :
                    while ($attachment -> have_posts() ) : $attachment -> the_post();
            ?>
                        <div class="gallery__item"><a href="<?php echo wp_get_attachment_url(); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url(); ?>" alt=""></a></div>
            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>
</code>```

Body:
How to get attachment from single page by ID, and set 12 img per page?

'post_parent' => 145, // not working, but without this param I get all attachments

<?php
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post_parent' => 145, // not working, but without this param I get all attachments
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ( $attachment->have_posts() ) :
                    while ( $attachment->have_posts() ) : $attachment->the_post();

            ?>

<a href="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url( $attachment->ID , false ); ?>" alt="">

            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>

Body:
I found out what the problem was. I use post_parent and tells post ID, thinking that take all attachments from this post, but WP_Query returns me ID's of images.

I get all id's of images in array with get_post_gallery()

$gal = get_post_gallery(11,false);

and explode it

$ids = explode(',', $gal['ids']);

after then everything worked!

also I use post__in insted post_parent

The final code:

<?php
                $gal = get_post_gallery(11,false);
                $ids = explode(',', $gal['ids']);
                $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                $attachment = new WP_Query( array(
                    'post__in' => $ids,
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
                    'posts_per_page'  => 12,
                    'paged'           => $paged
                ) );
                if ($attachment -> have_posts() ) :
                    while ($attachment -> have_posts() ) : $attachment -> the_post();
            ?>
                        <div class="gallery__item"><a href="<?php echo wp_get_attachment_url(); ?>" data-fancybox><img src="<?php echo wp_get_attachment_url(); ?>" alt=""></a></div>
            <?php

                    endwhile;
                    wp_reset_postdata();
                endif;
            ?>


问:
Polymorphism inside monads
I'm trying to pull a value out of a monad, but keep the value, which doesn't depend on the monad, polymorphic. Specifically:

```<code>foo :: (Monad mon, Ring a) => mon a
foo = return 3

main :: IO ()
main = do
  x <- foo
  print (x :: Double)
  print (x :: Int)
</code>```

The point is that the monadic portion of the computation is expensive to compute, so I only want to do it once, while keeping the value in the monad polymorphic. All of my attempts so far:

giving x the signature forall a. (Ring a) => a)

giving foo :: (Monad mon) => mon (forall a . (Ring a) => a)

enabling -XNoMonomorphismRestriction and NoMonoLocalBins

have either not worked or given errors about impredicative polymorphism, which I'm not willing to use. Is there some way to pull a polymorphic value out of a monad without impredicative polymorphism (or alternatively: is there a safe way to use impredicative polymorphism in GHC)?

答:
You can work around the absence of impredicative polymorphism by wrapping the polymorphic value in a special data type.</p>

```<code>newtype AnyRing = AnyRing (forall a. Ring a => a)

foo :: Monad m => m AnyRing

main = do
  AnyRing x <- foo
  print (x :: Double)
  print (x :: Int)
</code>```

Title: Polymorphism inside monads

Body:
I'm trying to pull a value out of a monad, but keep the value, which doesn't depend on the monad, polymorphic. Specifically:

foo :: (Monad mon, Ring a) => mon a
foo = return 3

main :: IO ()
main = do
  x <- foo
  print (x :: Double)
  print (x :: Int)

The point is that the monadic portion of the computation is expensive to compute, so I only want to do it once, while keeping the value in the monad polymorphic. All of my attempts so far:

giving x the signature forall a. (Ring a) => a)

giving foo :: (Monad mon) => mon (forall a . (Ring a) => a)

enabling -XNoMonomorphismRestriction and NoMonoLocalBins

have either not worked or given errors about impredicative polymorphism, which I'm not willing to use. Is there some way to pull a polymorphic value out of a monad without impredicative polymorphism (or alternatively: is there a safe way to use impredicative polymorphism in GHC)?

Body:
You can work around the absence of impredicative polymorphism by wrapping the polymorphic value in a special data type.

newtype AnyRing = AnyRing (forall a. Ring a => a)

foo :: Monad m => m AnyRing

main = do
  AnyRing x <- foo
  print (x :: Double)
  print (x :: Int)


问:
Mongo DB unknown Error?
I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

My java code:

```<code>    public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

    //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }
    }
    }
</code>```

The output is:
 it is getting printed continuously as

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

I cant figure out what is happening. i want to insert some data into the collection "items"
also if i want to know how to use Mongo in java. I know mysql well but shifting to mongo I cant relate both in queries. What is "query.put" is doing? Any suggestions please?

答: You got yourself an infinite loop because you forgot to call cursor.next() inside the while loop. </p>

Title: Mongo DB unknown Error?

Body:
I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

My java code:

    public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

    //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }
    }
    }

The output is:
 it is getting printed continuously as

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

I cant figure out what is happening. i want to insert some data into the collection "items"
also if i want to know how to use Mongo in java. I know mysql well but shifting to mongo I cant relate both in queries. What is "query.put" is doing? Any suggestions please?


问:
How to have a circular inner shadow for canvas shape?
In my canvas, I have a circle shape that moves with cursor.
I am trying to give this a little inner shadow, but it does not work.

Here is the code and demo : JSFIDDLE

```<code>function writeMessage(canvas, message, x, y) {
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);

    var pattern = context.createPattern(imageResized, 'no-repeat'); //Use imageResized, not imageObj.
    context.fillStyle = pattern;
    context.fill();

    context.font = '28pt Calibri';
    context.fillStyle = 'white';
    //context.fillText(message, x, y);
    context.beginPath();
    context.arc(x, y, 50, 0, 2 * Math.PI);
    context.stroke();

    context.beginPath();
    context.lineWidth = 5;
    context.shadowColor = 'black';
    context.strokeStyle = "rgba(0,0,0,1)";
    context.shadowBlur = 15;
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;
    context.arc(x, y, 50, 0, 2 * Math.PI, false);
    context.stroke();
    context.restore();

}
</code>```

I notice this settings would work if I add context.clip(); but then it would make the whole canvas crash.

Any idea to have an inner shadow for this circle ?

答:
I've just created Inset.js for this exact situation!

Inset.js

Only requires setting ctx.shadowInset = true;

For example: http://codepen.io/patlillis/pen/RpEoKE

```<code>var ctx = canvas.getContext("2d");
var w = canvas.width = window.innerWidth;
var h = canvas.height = window.innerHeight;

// Set up circle styles.
ctx.shadowInset = true;
ctx.shadowBlur = 15;
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.fillStyle = 'red';

// Set up mouse listener.
document.addEventListener('mousemove', function(e) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI);
    ctx.fill();
});
</code>```

Body:
In my canvas, I have a circle shape that moves with cursor.
I am trying to give this a little inner shadow, but it does not work.

Here is the code and demo : JSFIDDLE

function writeMessage(canvas, message, x, y) {
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);

    var pattern = context.createPattern(imageResized, 'no-repeat'); //Use imageResized, not imageObj.
    context.fillStyle = pattern;
    context.fill();

    context.font = '28pt Calibri';
    context.fillStyle = 'white';
    //context.fillText(message, x, y);
    context.beginPath();
    context.arc(x, y, 50, 0, 2 * Math.PI);
    context.stroke();

    context.beginPath();
    context.lineWidth = 5;
    context.shadowColor = 'black';
    context.strokeStyle = "rgba(0,0,0,1)";
    context.shadowBlur = 15;
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;
    context.arc(x, y, 50, 0, 2 * Math.PI, false);
    context.stroke();
    context.restore();

}

I notice this settings would work if I add context.clip(); but then it would make the whole canvas crash.

Any idea to have an inner shadow for this circle ?

Body:
I've just created Inset.js for this exact situation!

Inset.js

Only requires setting ctx.shadowInset = true;

For example: http://codepen.io/patlillis/pen/RpEoKE

var ctx = canvas.getContext("2d");
var w = canvas.width = window.innerWidth;
var h = canvas.height = window.innerHeight;

// Set up circle styles.
ctx.shadowInset = true;
ctx.shadowBlur = 15;
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.fillStyle = 'red';

// Set up mouse listener.
document.addEventListener('mousemove', function(e) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI);
    ctx.fill();
});


问:
Ruby loops style/convention
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

```<code>for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}
</code>```

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

答:
Try this</p>

```<code>i = 0
j = 10
loop do
  break if i > 9 || j < 1
  # do something
  i = i + 1
  j = j - 1
end
</code>```

Title: Ruby loops style/convention

Body:
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

Body:
Try this

i = 0
j = 10
loop do
  break if i > 9 || j < 1
  # do something
  i = i + 1
  j = j - 1
end


问:
php mysql result coming back wrong, every time from php, but is fine in sql pro and phpmyadmin
The following statement is returning a 1 in php. I've serialized and output the result and every other credential, and it is doing this on three seperate queries. When I run the query in sqlpro or phpmyadmin I get the result as 8. Please tell me someone has a bright idea.</p>

```<code>$numRFPsSwitch = 0;
$bquery = " SELECT COUNT(rp.id) AS 'NumRFPs'

   FROM  rfp_proposal rp

   WHERE rp.vendor_id = 1 AND rp.id IN(13,15,16,23,24,26,4,9) ";

$bresult = mysql_query($bquery, $connection);
$XMLFormatedString .= 'NumRFPs="';
while ($brow = mysql_fetch_object($bresult)){

$XMLFormatedString .= $brow->NumRFPs;
$numRFPsSwitch = 1;
}
</code>```

答:
The result will always be a single row. So the loop should be replaced with an if.
Concerning the problem: Did you check your <code>$connection</code>? </p>

Body:
The following statement is returning a 1 in php. I've serialized and output the result and every other credential, and it is doing this on three seperate queries. When I run the query in sqlpro or phpmyadmin I get the result as 8. Please tell me someone has a bright idea.

$numRFPsSwitch = 0;
$bquery = " SELECT COUNT(rp.id) AS 'NumRFPs'

   FROM  rfp_proposal rp

   WHERE rp.vendor_id = 1 AND rp.id IN(13,15,16,23,24,26,4,9) ";

$bresult = mysql_query($bquery, $connection);
$XMLFormatedString .= 'NumRFPs="';
while ($brow = mysql_fetch_object($bresult)){

$XMLFormatedString .= $brow->NumRFPs;
$numRFPsSwitch = 1;
}

Body:
The result will always be a single row. So the loop should be replaced with an if.
Concerning the problem: Did you check your $connection?


问:
Creating a map/contents of any object
In Python 3.6. What I'm trying to do is create a function that can accept any object and then generate a tree like contents.

Similar to a book:

```<code>1. Object
 1.1 member: integer
 1.2 member: list
   2.1 list: element 1
   2.2 list: element 2
 1.3 member: string
</code>```

My purpose is to use the numbers as a key for a technical readout, the number could also stand in for a more understandable ID number than id() generates. Because the objects I want to deal with are all types, I'd like the function to be recursive. Here is what I have so far:

```<code>def contents(a, n = 0, lim = 5, prefix=""):
    index = 1
    text = ""
    j = None
    if n < lim:
        try:
            for i in a.__dict__:
                text = text + "\n" + ("\t" *(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(a.__dict__[i], n = n + 1, prefix=str(n)+".") + ""
                index += 1
        except:
            try:
                for i, j in a.items():
                    text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(i, n = n + 1, prefix=str(n)+".") + ""
                    index += 1
                except:
                    if isinstance(a, str):
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "
                    else:
                        try:
                            for i in a:
                                text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(i) + contents(i, n = n + 1, prefix=str(n)+".") + " "
                                index += 1

                    except:
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "

    else:
        text = text + "limit. \n"
    return text
</code>```

a is the object, n is the current number of recursion, lim is the recursion limit, prefix has to do with the object ID displayed.

Here's the testing object

```<code>class Aclass:

    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]
</code>```

The problem I'm running into has to do with strange revursive behavior with lists, I already made an exception for strings, because the string would register as an iterable made up of iterables, which would recurse indefinitely if I hadn't put in a limit. Now simple lists of numbers like [1, 2, 3, 4] will often list the number twice as if it breaks down into a one item list [1] and then reports on the number inside: 1.

答:
You should have a look at the pprint module, which is part of the standard distribution. It solves this problem already, and so might serve as a basis for your code. (I can easily see, for instance, adding numbers by subclassing the PrettyPrinter class.)

This code:

```<code>class Aclass:
    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

import pprint
s = pprint.pformat(a, indent=4)
print(s)
</code>```

Produces this output:

```<code>[   <__main__.Aclass object at 0x1060fb160>,
    1,
    '2',
    3,
    4,
    <__main__.Aclass object at 0x1060fb198>,
    {'c': 'd', 'e': 'f'}]
</code>```

Title: Creating a map/contents of any object

Body:
In Python 3.6. What I'm trying to do is create a function that can accept any object and then generate a tree like contents.

Similar to a book:

1. Object
 1.1 member: integer
 1.2 member: list
   2.1 list: element 1
   2.2 list: element 2
 1.3 member: string

My purpose is to use the numbers as a key for a technical readout, the number could also stand in for a more understandable ID number than id() generates. Because the objects I want to deal with are all types, I'd like the function to be recursive. Here is what I have so far:

def contents(a, n = 0, lim = 5, prefix=""):
    index = 1
    text = ""
    j = None
    if n < lim:
        try:
            for i in a.__dict__:
                text = text + "\n" + ("\t" *(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(a.__dict__[i], n = n + 1, prefix=str(n)+".") + ""
                index += 1
        except:
            try:
                for i, j in a.items():
                    text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(i, n = n + 1, prefix=str(n)+".") + ""
                    index += 1
                except:
                    if isinstance(a, str):
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "
                    else:
                        try:
                            for i in a:
                                text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(i) + contents(i, n = n + 1, prefix=str(n)+".") + " "
                                index += 1

                    except:
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "

    else:
        text = text + "limit. \n"
    return text

a is the object, n is the current number of recursion, lim is the recursion limit, prefix has to do with the object ID displayed.

Here's the testing object

class Aclass:

    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

The problem I'm running into has to do with strange revursive behavior with lists, I already made an exception for strings, because the string would register as an iterable made up of iterables, which would recurse indefinitely if I hadn't put in a limit. Now simple lists of numbers like [1, 2, 3, 4] will often list the number twice as if it breaks down into a one item list [1] and then reports on the number inside: 1.

Body:
You should have a look at the pprint module, which is part of the standard distribution. It solves this problem already, and so might serve as a basis for your code. (I can easily see, for instance, adding numbers by subclassing the PrettyPrinter class.)

This code:

class Aclass:
    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

import pprint
s = pprint.pformat(a, indent=4)
print(s)

Produces this output:

[   <__main__.Aclass object at 0x1060fb160>,
    1,
    '2',
    3,
    4,
    <__main__.Aclass object at 0x1060fb198>,
    {'c': 'd', 'e': 'f'}]


问:
react + react-bootstrap. is it better to create function or fine to write function as a property
I am looking at the react-bootstrap components site, and specifically the <FormControl> component.

For validating whether the input value is OK, is it acceptable to write it inline or as a function?

For example,

```<code><FormControl
  onChange={() => {this.setState({ /* do some ternary check here */ })}
/>
</code>```

I've noticed in a lot of tutorials that authors will either move a lot of these out to functions (ie. onChange={this.doSomething}), or sometimes it seems to make sense to do them the way above.

How can I know which way is preferable?

答:
If by using a ternary operator you can validate the input field then write it inline, and if you want to check many conditions and want to do some computation then better to write a function and put all the logic inside that.

Basically function is used to make your code more structured and readable, lets say you want to check 3 conditions so if you write those conditions inline then it will become little messy, and unnecessary it will increase the size of render part, try to keep render as small as possible, because render is the starting point of your component, if someone wants check your code, he will start from render so it will help him to understand the logic easily.

One more benefit with writing function is, you can use that with other input fields of same type also.

Body:
I am looking at the react-bootstrap components site, and specifically the <FormControl> component.

For validating whether the input value is OK, is it acceptable to write it inline or as a function?

For example,

<FormControl
  onChange={() => {this.setState({ /* do some ternary check here */ })}
/>

I've noticed in a lot of tutorials that authors will either move a lot of these out to functions (ie. onChange={this.doSomething}), or sometimes it seems to make sense to do them the way above.

How can I know which way is preferable?