问:
FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service
I am beginner in android. i create a new service and run it in android mobile API Level-23. when i press button to startservice it show me ERROR. now i Create new project but problem is same there.

```<code>**FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service com.example.uzair.servicesapp.myIntentService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference**
</code>```

MainActivity.java

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static int i =0;
    private Intent  ii;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ii = new Intent(this,myIntentService.class);
       Toast.makeText(this, "this is custom toast", Toast.LENGTH_SHORT).show();
 }

    public void clickme2(View view)
    {
        startService(ii);
        Toast.makeText(this, " Service start toast", Toast.LENGTH_SHORT).show();
    }

    public void clickme(View view) {

 stopService(ii);
Toast.makeText(this, "Service stop toast", Toast.LENGTH_SHORT).show();
        i++;
    }
}
</code>```

MyIntentService.java

```<code>import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
public class myIntentService extends IntentService {

    public myIntentService()
    {
        super("myIntentService");
        Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this, "OnhandleIntent toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Destroy toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uzair.servicesapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".myIntentService"/>

    </application>

</manifest>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.uzair.servicesapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickme"
        android:text="@string/click_me"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="118dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="clickme2" />
</RelativeLayout>
</code>```

答:
Your are creating and stater service so you need to create an intent-filter to this service in the Manisfest file. In your manifest file edit:</p>

```<code>    <service android:name=".myIntentService">
       <intent-filter>
            <action android:name="com.example.uzair.servicesapp.myIntentService" />
        </intent-filter>
    </service>
</code>```

Body:
I am beginner in android. i create a new service and run it in android mobile API Level-23. when i press button to startservice it show me ERROR. now i Create new project but problem is same there.

**FATAL EXCEPTION: java.lang.RuntimeException: Unable to instantiate service com.example.uzair.servicesapp.myIntentService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference**

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static int i =0;
    private Intent  ii;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ii = new Intent(this,myIntentService.class);
       Toast.makeText(this, "this is custom toast", Toast.LENGTH_SHORT).show();
 }

    public void clickme2(View view)
    {
        startService(ii);
        Toast.makeText(this, " Service start toast", Toast.LENGTH_SHORT).show();
    }

    public void clickme(View view) {

 stopService(ii);
Toast.makeText(this, "Service stop toast", Toast.LENGTH_SHORT).show();
        i++;
    }
}

MyIntentService.java

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
public class myIntentService extends IntentService {

    public myIntentService()
    {
        super("myIntentService");
        Toast.makeText(this, "IntentService Constuctor toast", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this, "OnhandleIntent toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Destroy toast", Toast.LENGTH_SHORT);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uzair.servicesapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".myIntentService"/>

    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.uzair.servicesapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickme"
        android:text="@string/click_me"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="118dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="clickme2" />
</RelativeLayout>

Body:
Your are creating and stater service so you need to create an intent-filter to this service in the Manisfest file. In your manifest file edit:

    <service android:name=".myIntentService">
       <intent-filter>
            <action android:name="com.example.uzair.servicesapp.myIntentService" />
        </intent-filter>
    </service>


来源: stackexchange

问:
Add Column values in sql server query
I have result of two queries like:

Result of query 1

```<code>ID   Value
1    4
2    0
3    6
4    9
</code>```

Result of query 2

```<code>ID   Value
1    6
2    4
3    0
4    1
</code>```

I want to add values column "Value" and show final result:

Result of Both queries

```<code>ID   Value
1    10
2    4
3    6
4    10
</code>```

plz guide me...

答:
Try using a JOIN:

```<code>SELECT
    T1.ID,
    T1.Value + T2.Value AS Value
FROM (...query1...) AS T1
JOIN (...query2...) AS T2
ON T1.Id = T2.Id
</code>```

You may also need to consider what should happen if there is an Id present in one result but not in the other. The current query will omit it from the results. You may want to investigate OUTER JOIN as an alternative.

ContentLicense: CC BY-SA 2.5

Title: Add Column values in sql server query

Body:
I have result of two queries like:

Result of query 1

ID   Value
1    4
2    0
3    6
4    9

Result of query 2

ID   Value
1    6
2    4
3    0
4    1

I want to add values column "Value" and show final result:

Result of Both queries

ID   Value
1    10
2    4
3    6
4    10

plz guide me...

Body:
Try using a JOIN:

SELECT
    T1.ID,
    T1.Value + T2.Value AS Value
FROM (...query1...) AS T1
JOIN (...query2...) AS T2
ON T1.Id = T2.Id

You may also need to consider what should happen if there is an Id present in one result but not in the other. The current query will omit it from the results. You may want to investigate OUTER JOIN as an alternative.


问:
How to have radio buttons in horizontal way in orbeon forms?
As I want to make a survey form like this.

答: I can see how having the questions laid out on lines and the answers in columns makes sense in this case, but you can't create this exact layout right now just with Form Builder. For now, if using Form Builder, the values of the checkboxes will need to be repeated for each questions, as follows:

ContentLicense: CC BY-SA 3.0


问:
Accessing Json values Python
I have a json file, and i am trying to access the value, but i keep getting an error that says "TypeError: string indices must be integers, not str"

This is the Json data.

```<code>{'sentiment': '{\n  "0": {\n    "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders \n    "username": "@NigeriaNewsdesk:, @todayng", \n    "score": 0.0\n  }\n}'}
</code>```

data = val['sentiment']
printing data returns this back to me

```<code>{
 "0": {
  "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders",
  "username": "@NigeriaNewsdesk:, @todayng",
  "score": 0.0
 }
}
</code>```

But when i try to access the key/value pairs, i get an error
for records in data:
    print(records["0"]["username"])

```<code>TypeError: string indices must be integers, not str
</code>```

Any idea why i am getting these errors? Thanks

答: In the json you posted, sentiment stores a json string, not a json object. You need to parse the json - e.g. json.loads(val['sentiment']), or store the json as a json object.

Title: Accessing Json values Python

Body:
I have a json file, and i am trying to access the value, but i keep getting an error that says "TypeError: string indices must be integers, not str"

This is the Json data.

{'sentiment': '{\n  "0": {\n    "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders \n    "username": "@NigeriaNewsdesk:, @todayng", \n    "score": 0.0\n  }\n}'}

data = val['sentiment']
printing data returns this back to me

{
 "0": {
  "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders",
  "username": "@NigeriaNewsdesk:, @todayng",
  "score": 0.0
 }
}

But when i try to access the key/value pairs, i get an error
for records in data:
    print(records["0"]["username"])

TypeError: string indices must be integers, not str

Any idea why i am getting these errors? Thanks


问:
Making a client's website live with a customized domain name
I'm trying to make a website for a client right now, and I'm using Sublime Text to build it from Scratch using JQuery, JavaScript, HTML5, and CSS3.

However, I don't know how to make it live with a custom domain name when it's built from scratch. Furthermore, I need to make sure the client is paying for any monthly fees that may occur.

Finally, should I switch to only building websites with customizing site building tools like WordPress or SquareSpace? I haven't seen many tutorials on how to host a website after bulding it from scratch for a client.
Thanks!

答:
What was answered above is 100% correct, but let's give you a more detail.

You need to find hosting. There are lots of free resources out there, but you should be cautious. My recommendation would be something like https://getforge.com/

Once you have the site uploaded, you want to test it and make sure it is working in a production environment. i.e. no broken links, missing images, etc...

Now lets assume you have a domain already, if not you want to register one (typically $12USD per year for a .com).

Once the domain is secured, you will need to point the domain to your hosting company. More often than not it's best to let the domain registrar manage the DNS, and just change the IP address the A record for the domain to the new hosting account you setup in step 1.

Last but not least, pretty much every hosting service has an option to add on domains, or add a custom domain. This is pretty simple typically.

Now it will take some time for the change you made in step 4 to propagate. Have no fear, if everything was done correctly, you will have a live site now!

More advanced model of this would be how I launch static sites.

Build site on my local machine and setup a git repository

Push my local repository to Bitbucket

Set up continuous deployment a CDN like Netlify

Point the domain

Assign the domain to the deployment on Netlify,

Go have cocktails


问:
What's the purpose of having both db level and code level uniqueness validations in Rails?
I see a table that has both db-level and code-level validations in Rails.

```<code>CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);
</code>```

and code level:

```<code>class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end
</code>```

What's the benefit of having both?

答:
What's the benefit of having both?

Apart from the obvious "Extra security" aspect, having the validates_uniqueness_of adds a quality gate on your app side to check before trying to commit.

Without validates_uniqueness_of, it will attempt to query the database to create, so the error returns from the database.

With validates_uniqueness_of, it will query the database to see if it exists before trying to create, so the error returns from the app.  It's preferable to have errors return from the app, since you have full control.

Also something to think about...
I could see issues maybe later down the road, you remove that constraint from the database, but wait.. your model still has that constraint!  or vice-versa.

Body:
I see a table that has both db-level and code-level validations in Rails.

CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);

and code level:

class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end

What's the benefit of having both?


问:
How set cursor inside textbox after page load with jquery
Alright i have a asp.net textbox and i want to set cursor inside textbox after page loaded like when you open google.

I only need set cursor inside textbox code.

I tried this but not working

```<code>$('txtSendTo').focus();
</code>```

答:
I was not able to set cursor inside an input field when a link is clicked. However adding event.preventDefault() at the start of the function and returning false fixed it. Here is the code if someone is having the same issue</p>

```<code>$("#search-button").click(function (event) {
  event.preventDefault();
  $("#textbox").focus();
  return false;
});
</code>```

Body:
Alright i have a asp.net textbox and i want to set cursor inside textbox after page loaded like when you open google.

I only need set cursor inside textbox code.

I tried this but not working

$('txtSendTo').focus();

Body:
I was not able to set cursor inside an input field when a link is clicked. However adding event.preventDefault() at the start of the function and returning false fixed it. Here is the code if someone is having the same issue

$("#search-button").click(function (event) {
  event.preventDefault();
  $("#textbox").focus();
  return false;
});


问:
Postgresql query to have atleast two different results for same refrence
I have the following ER Model

I need to write a postgresql query that does this.

Select all donors where:

```<code>1)Diagnosis.name starts with "abc".

2)There should be a second Diagnosis.name for the same donor, and it should be "xyz"
</code>```

Consider this as sample data:

Donor table has:

```<code>id|    name

1 |John
2 |Sam
</code>```

Event table has:

```<code>id | event_type  | donor_fk

1  | diagnosis   | 1
2  | diagnosis   | 2
3  | diagnosis   | 2
4  | observation | 3
5  | intervention| 3
</code>```

Diagnosis table has:

```<code>id | name | event_FK

1  |abc   | 2
2  |xyz   | 3
</code>```

I am wondering how can i check if the two instances of diagnosis.name are for the same donor?

The result of the query should return all the data for donor named "Sam".

I am no where close to a solution since i posted this question. I was thinking in the direction of self join of diagnosis table but there is no reference to itself in this table so self join does not make sense.

答:
/* Not very efficient but a bit readable solution would be: */

```<code>select distinct a.*
from (
    select do.id, do.name
    from diagnosis diag
    join event e on diag.event_fk = e.id
        and upper(diag.name) like 'ABC%' /* here ya filter 1 */
    join donor do on d.id = e.donor_fk
) a
join (
    select do.id, do.name
    from diagnosis diag
    join event e on diag.event_fk = e.id
        and upper(diag.name) like 'XYZ'  /* here ya filter 2 */
    join donor do on d.id = e.donor_fk
) b on a.id = b.id
  ;
</code>```

Body:
I have the following ER Model

I need to write a postgresql query that does this.

Select all donors where:

1)Diagnosis.name starts with "abc".

2)There should be a second Diagnosis.name for the same donor, and it should be "xyz"

Consider this as sample data:

Donor table has:

id|    name

1 |John
2 |Sam

Event table has:

id | event_type  | donor_fk

1  | diagnosis   | 1
2  | diagnosis   | 2
3  | diagnosis   | 2
4  | observation | 3
5  | intervention| 3

Diagnosis table has:

id | name | event_FK

1  |abc   | 2
2  |xyz   | 3

I am wondering how can i check if the two instances of diagnosis.name are for the same donor?

The result of the query should return all the data for donor named "Sam".

I am no where close to a solution since i posted this question. I was thinking in the direction of self join of diagnosis table but there is no reference to itself in this table so self join does not make sense.

Body:
/* Not very efficient but a bit readable solution would be: */

select distinct a.*
from (
    select do.id, do.name
    from diagnosis diag
    join event e on diag.event_fk = e.id
        and upper(diag.name) like 'ABC%' /* here ya filter 1 */
    join donor do on d.id = e.donor_fk
) a
join (
    select do.id, do.name
    from diagnosis diag
    join event e on diag.event_fk = e.id
        and upper(diag.name) like 'XYZ'  /* here ya filter 2 */
    join donor do on d.id = e.donor_fk
) b on a.id = b.id
  ;


问:
flask-admin: how to customize the view according to the individual user instead of the role?
As we all know, flask-admin allows the users with same role have the same privilege. However, in my app I'd like to restrict only the user who created a query to view and edit.

For example, there are many users with the same role called "developers", he/she creates a code review and wait for approval.

The pic below shows developer Gina can see developer Bill's project in the list(which is not desired). What I'd like to achieve is only Gina and the reviewers(Wesker and Steve here) can view this project in the list.

I've put the code here
, if it's not appropriate I will remove the link. Thanks in advance.

答:
Overriding ModelView, you can filter results to show logged user own results:

```<code>def get_query(self):
  return self.session.query(self.model).filter(self.model.user==current_user)

def get_count_query(self):
  return self.session.query(func.count('*')).filter(self.model.user==current_user)
</code>```

You can find more info here:
Flask-Admin default filters

Body:
Overriding ModelView, you can filter results to show logged user own results:

def get_query(self):
  return self.session.query(self.model).filter(self.model.user==current_user)

def get_count_query(self):
  return self.session.query(func.count('*')).filter(self.model.user==current_user)

You can find more info here:
Flask-Admin default filters


问:
High-scale signal processing in R
I have high-dimensional data, for brain signals, that I would like to explore using R.

Since I am a data scientist I really do not work with Matlab, but R and Python. Unfortunately, the team I am working with is using Matlab to record the signals. Therefore, I have several questions for those of you who are interested in data science.

The Matlab files, recorded data, are single objects with the following dimensions:
1000*32*6000

1000: denotes the sampling rate of the signal.

32: denotes the number of channels.

6000: denotes the time in seconds, so that is 1 hour and 40 minutes long.

The questions/challenges I am facing:

I converted the "mat" files I have into CSV files, so I can use them in R.
However, CSV files are 2 dimensional files with the dimensions: 1000*192000.

the CSV files are rather large, about 1.3 gigabytes. Is there a
better way to convert "mat" files into something compatible with R,
and smaller in size? I have tried "R.matlab" with readMat, but it is
not compatible with the 7th version of Matlab; so I tried to save as V6 version, but it says "Error: cannot allocate vector of size 5.7 Gb"

the time it takes to read the CSV file is rather long! It takes
    about 9 minutes to load the data. That is using "fread" since the
    base R function read.csv takes forever. Is there a better way to
    read files faster?

Once I read the data into R, it is 1000*192000; while it is actually
    1000*32*6000. Is there a way to have multidimensional object in R,
    where accessing signals and time frames at a given time becomes
    easier. like dataset[1007,2], which would be the time frame of the
    1007 second and channel 2. The reason I want to access it this way
    is to compare time frames easily and plot them against each other.

Any answer to any question would be appreciated.

答: This is a good reference for reading large CSV files:  https://rpubs.com/msundar/large_data_analysis A key takeaway is to assign the datatype for each column that you are reading versus having the read function decide based on the content.</p>

Title: High-scale signal processing in R


问:
C - representing binary in #defines
The code snippet below works as is but if I uncomment the first #define and comment the second the compiler complains about expecting a ')' at the assignment statement. Thought it might be wanting a cast but that did not help. Please point out my stupid oversight.

Thanks,
jh

```<code>//#define SMI_READ  (0b10 << 10)
#define SMI_READ  (0x2 << 10)
    ...
    command |= SMI_READ;
</code>```

答:
In general, to answer a question like this we need to see the complete and unedited text of the error messages, and it also really helps if you provide a complete program that we can attempt to compile for ourselves.  (It might seem to you that the error messages are useless, but often it's just that they only make sense if you know how to think like a compiler engineer.)

However, in this case, I can make a high-confidence guess, because the only difference between the two macros is that the one that doesn't work uses a binary number, 0b10, and the one that does work uses a hexadecimal number, 0x2.  Binary numbers are not part of any version of the C standard, although they are a common extension.  I therefore deduce that your compiler doesn't support them and is giving an unclear error message when it encounters them.

Title: C - representing binary in #defines

Body:
The code snippet below works as is but if I uncomment the first #define and comment the second the compiler complains about expecting a ')' at the assignment statement. Thought it might be wanting a cast but that did not help. Please point out my stupid oversight.

Thanks,
jh

//#define SMI_READ  (0b10 << 10)
#define SMI_READ  (0x2 << 10)
    ...
    command |= SMI_READ;


问:
How to use Calabash x-platform with Amazon Device Farm
I am planning to use x-platform frameworks with Amazon device farm but the x-platform folder hierarchy is different than what Amazon is accepting. Is there any way to solve this?

There is a thread in amazon forum but it was solved by not using x-platform.

what x-platform is:

答:
I work for the AWS Device Farm team.

Device Farm accepts a zip file which is the zipped features folder.
So if all of you test code were under features folder you would zip the features folder.
After unzipping the features folder should not have another features folder inside it.

Also if you have customer code in env.rb or 01_launch.rb files this can cause the tests to be not parsed on Device farm. It does a dry run of your test package before it can start running the tests.

If you are reading ENV for platform that will be another reason why it will not get parsed on device farm.

Hope that helps.


问:
Add alternating row color to SQL Server Reporting services report
How do you shade alternating rows in a SQL Server Reporting Services report?

Edit: There are a bunch of good answers listed below--from quick and simple to complex and comprehensive. Alas, I can choose only one...

答:
Go to the table row's BackgroundColor property and choose "Expression..."

Use this expression:

```<code>= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
</code>```

This trick can be applied to many areas of the report.

And in .NET 3.5+ You could use:

```<code>= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
</code>```

Not looking for rep--I just researched this question myself and thought I'd share.

OwnerDisplayName: mharen

LastEditorDisplayName: Michael Haren

Body:
Go to the table row's BackgroundColor property and choose "Expression..."

Use this expression:

= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

This trick can be applied to many areas of the report.

And in .NET 3.5+ You could use:

= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

Not looking for rep--I just researched this question myself and thought I'd share.


问:
How to run test cases from the browser in cakephp
I'm new to testing, so please forgive me for this question

In the cakephp manual under the "Creating tests" chapter, one can read

When you have created a test case, you can execute it by browsing to http://your.cake.domain/cake_folder/test.php (depending on how your specific setup looks) and clicking App test cases, and then click the link to your specific file.

I don't understand the url, and how to apply to my case.

I'd like to run the following test case stored at: /app/tests/cases/models/box.test.php

My domain is www.box.local

I don't understand what url should I enter? Please enlighten me.

答:
In the Cake app there are two important files in /app/webroot/: index.php and test.php. Normal requests are all handled by the index.php file. To run tests, you have to invoke the test.php file. As such, if you are normally visiting the URL www.box.local/, just go to www.box.local/test.php. If your Cake app is in a sub folder and the normal URL is www.box.local/cakeapp/, use www.box.local/cakeapp/test.php.

The actual tests you launch from the interface there.


问:
Are properties set in the specified order?
Suppose I have a class with 3 instance attributes, 'a', 'b' and 'c', which are initialized each with property setters. Now, my property 'b' assignment should use the value of the instance variable 'a'. So for 'b' to be initialized, 'a' has to be initialized beforehand.

Following the code below, does python set the instance 'a' first, then goes to instance 'b', and then finnally to 'c', or may the initialisation occur in any random order, which might destroy the possibility to sucessfully initialise the variables?

```<code>class Foo(object):

    def __init__(self):
        self.a = None
        self.b = None
        self.c = None

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, value):
        value = self.a
        self._b = value

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, value):
        value = self.b
        self._c = value
</code>```

I am asking this question in a simplified version because I am having difficulties in a real case. In that case, I used logs to view the execution of the execution of the initialisation, and it appears to me that it starts by executing the last property ('c' in this case), instead of the desired first, 'a'.

答:
__init__ is like any other method in Python; the statements in it are executed in the order given, so in your example code, a is set before b, which is set before c, always.

The Python language spec in general provides stronger ordering guarantees than languages like C/C++ (e.g. a, b, c = d, e, f guarantees that d is read first, then e, then f, and a is set first, then b, then c).

It does not matter if they are properties, plain attributes, or whatever; assignment might do funky things, but those things occur in the order the statements occur.

Body:
Suppose I have a class with 3 instance attributes, 'a', 'b' and 'c', which are initialized each with property setters. Now, my property 'b' assignment should use the value of the instance variable 'a'. So for 'b' to be initialized, 'a' has to be initialized beforehand.

Following the code below, does python set the instance 'a' first, then goes to instance 'b', and then finnally to 'c', or may the initialisation occur in any random order, which might destroy the possibility to sucessfully initialise the variables?

class Foo(object):

    def __init__(self):
        self.a = None
        self.b = None
        self.c = None

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, value):
        value = self.a
        self._b = value

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, value):
        value = self.b
        self._c = value

I am asking this question in a simplified version because I am having difficulties in a real case. In that case, I used logs to view the execution of the execution of the initialisation, and it appears to me that it starts by executing the last property ('c' in this case), instead of the desired first, 'a'.


问:
Interpreting conditional probabilities returned by naiveBayes classifier in e1071:R
Working on a classification solution using the following process:

a. Perform Naive Bayes classification in R using e1071.

b. Get the a-priori table and conditional probabilities tables

c. Use the values for prediction using a PL/SQL program within an application. i.e. Eventual prediction will not involve usage of the R predict function.

In step b, am seeing negative and greater than 1 conditional probabilities returned by R after model generation - are they really conditional probabilities?

Illustrating the issue with 2 data sets - one that I am able to interpret and one that I am unable to interpret.

Data set 1:
Fruit identification ( saw this in a nice Naive Bayes illustration in this forum)

```<code>Data Frame Fruit_All:

Long    Sweet   Yellow  Fruit

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes Yes Yes Banana

No  Yes Yes Banana

No  Yes Yes Orange

No  Yes Yes Orange

No  Yes Yes Orange

Yes Yes Yes Other

No  Yes No  Other

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes No  Yes Banana

Yes No  No  Banana

No  No  Yes Banana

No  No  Yes Orange

No  No  Yes Orange

No  No  Yes Orange

Yes Yes No  Other

No  No  No  Other
</code>```

Performing Naive Bayes classification:

```<code>  `NB.fit <- naiveBayes(Fruit~., data=Fruit_All,laplace=0)`
</code>```

where Fruit is the class column, Fruit_All is the complete data frame.

The returned conditional probabilities in NB.fit are exactly as expected.

Also, all the row probabilities neatly add up to 1.  e.g.0.1 + 0.9 for Banana+Yellow

Conditional probabilities:

```<code>        Long
Y         No Yes
  Banana 0.2 0.8
  Orange 1.0 0.0
  Other  0.5 0.5

        Sweet
Y          No  Yes
  Banana 0.30 0.70
  Orange 0.50 0.50
  Other  0.25 0.75

        Yellow
Y          No  Yes
  Banana 0.10 0.90
  Orange 0.00 1.00
  Other  0.75 0.25

A-priori probabilities:

Banana Orange  Other
   0.5    0.3    0.2
</code>```

I can use the above to easily write code to predict the outcome for an input provided e.g. For Long, Sweet and Yellow all equal to yes.

The fruit for which this product is maximum :

P(Long|Fruit) * P(Sweet|Fruit) * P(Yellow|Fruit) * apriori P(Fruit)

Data Set 2:  Iris data set available in R

```<code>  `NB.fit <- naiveBayes(Species~., data=iris)`
</code>```

Conditional probabilities:

```<code>         Sepal.Length
Y             [,1]      [,2]

  setosa     5.006 0.3524897

  versicolor 5.936 0.5161711

  virginica  6.588 0.6358796

            Sepal.Width
Y             [,1]      [,2]

  setosa     3.428 0.3790644

  versicolor 2.770 0.3137983

  virginica  2.974 0.3224966

            Petal.Length
Y             [,1]      [,2]

  setosa     1.462 0.1736640

  versicolor 4.260 0.4699110

  virginica  5.552 0.5518947

            Petal.Width
Y             [,1]      [,2]

  setosa     0.246 0.1053856

  versicolor 1.326 0.1977527

  virginica  2.026 0.2746501
</code>```

In this case, the same function doesn't seem to be returning conditional probabilities as some of the values are greater than 1 and none of the rows add up to 1.

Note: If I use the predict function in R , I get correct results as predictions for Iris.

I understand the Iris data set is a bit different as the variables are continuous numeric values and not factors unlike the fruit example.

For other complex data sets, I even see negative values as conditional probabilities returned by the classifier. Though the final result is fine within R.

Questions:

Are the conditional probabilities returned for the Iris data set really conditional probabilities?

Will the same product maximization I did in the fruit example hold good for Iris and even for data sets where the conditional probabilities are negative?

Is it possible to write a custom prediction function based on the Iris conditional probability tables?

答:
This answer is just about a year late but I just stumbled upon it. As you write, the predictors are numeric and are therefore treated differently that factors. What you get are the means (first columns) and sd's (second column) of the conditional Gaussian distributions. Thus, for

```<code>            Petal.Width
Y             [,1]      [,2]

  setosa     0.246 0.1053856
</code>```

We have that the mean Petal Width is 0.246 and the standard deviation is 0.10. You can see that too from

```<code>> iris %>% dplyr::filter(Species=="setosa") %>%
           dplyr::summarize(mean(Petal.Width), sd(Petal.Width))
  mean(Petal.Width) sd(Petal.Width)
1             0.246       0.1053856
</code>```

The Gaussian density is used to invert the conditional probability using Bayes formula to obtain the proper conditional probabilities.

Body:
Working on a classification solution using the following process:

a. Perform Naive Bayes classification in R using e1071.

b. Get the a-priori table and conditional probabilities tables

c. Use the values for prediction using a PL/SQL program within an application. i.e. Eventual prediction will not involve usage of the R predict function.

In step b, am seeing negative and greater than 1 conditional probabilities returned by R after model generation - are they really conditional probabilities?

Illustrating the issue with 2 data sets - one that I am able to interpret and one that I am unable to interpret.

Data set 1:
Fruit identification ( saw this in a nice Naive Bayes illustration in this forum)

Data Frame Fruit_All:

Long    Sweet   Yellow  Fruit

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes Yes Yes Banana

No  Yes Yes Banana

No  Yes Yes Orange

No  Yes Yes Orange

No  Yes Yes Orange

Yes Yes Yes Other

No  Yes No  Other

Yes Yes Yes Banana

Yes Yes Yes Banana

Yes No  Yes Banana

Yes No  No  Banana

No  No  Yes Banana

No  No  Yes Orange

No  No  Yes Orange

No  No  Yes Orange

Yes Yes No  Other

No  No  No  Other

Performing Naive Bayes classification:

  `NB.fit <- naiveBayes(Fruit~., data=Fruit_All,laplace=0)`

where Fruit is the class column, Fruit_All is the complete data frame.

The returned conditional probabilities in NB.fit are exactly as expected.

Also, all the row probabilities neatly add up to 1.  e.g.0.1 + 0.9 for Banana+Yellow

Conditional probabilities:

        Long
Y         No Yes
  Banana 0.2 0.8
  Orange 1.0 0.0
  Other  0.5 0.5

        Sweet
Y          No  Yes
  Banana 0.30 0.70
  Orange 0.50 0.50
  Other  0.25 0.75

        Yellow
Y          No  Yes
  Banana 0.10 0.90
  Orange 0.00 1.00
  Other  0.75 0.25

A-priori probabilities:

Banana Orange  Other
   0.5    0.3    0.2

I can use the above to easily write code to predict the outcome for an input provided e.g. For Long, Sweet and Yellow all equal to yes.

The fruit for which this product is maximum :

P(Long|Fruit) * P(Sweet|Fruit) * P(Yellow|Fruit) * apriori P(Fruit)

Data Set 2:  Iris data set available in R

  `NB.fit <- naiveBayes(Species~., data=iris)`

Conditional probabilities:

         Sepal.Length
Y             [,1]      [,2]

  setosa     5.006 0.3524897

  versicolor 5.936 0.5161711

  virginica  6.588 0.6358796

            Sepal.Width
Y             [,1]      [,2]

  setosa     3.428 0.3790644

  versicolor 2.770 0.3137983

  virginica  2.974 0.3224966

            Petal.Length
Y             [,1]      [,2]

  setosa     1.462 0.1736640

  versicolor 4.260 0.4699110

  virginica  5.552 0.5518947

            Petal.Width
Y             [,1]      [,2]

  setosa     0.246 0.1053856

  versicolor 1.326 0.1977527

  virginica  2.026 0.2746501

In this case, the same function doesn't seem to be returning conditional probabilities as some of the values are greater than 1 and none of the rows add up to 1.

Note: If I use the predict function in R , I get correct results as predictions for Iris.

I understand the Iris data set is a bit different as the variables are continuous numeric values and not factors unlike the fruit example.

For other complex data sets, I even see negative values as conditional probabilities returned by the classifier. Though the final result is fine within R.

Questions:

Are the conditional probabilities returned for the Iris data set really conditional probabilities?

Will the same product maximization I did in the fruit example hold good for Iris and even for data sets where the conditional probabilities are negative?

Is it possible to write a custom prediction function based on the Iris conditional probability tables?

Body:
This answer is just about a year late but I just stumbled upon it. As you write, the predictors are numeric and are therefore treated differently that factors. What you get are the means (first columns) and sd's (second column) of the conditional Gaussian distributions. Thus, for

            Petal.Width
Y             [,1]      [,2]

  setosa     0.246 0.1053856

We have that the mean Petal Width is 0.246 and the standard deviation is 0.10. You can see that too from

> iris %>% dplyr::filter(Species=="setosa") %>%
           dplyr::summarize(mean(Petal.Width), sd(Petal.Width))
  mean(Petal.Width) sd(Petal.Width)
1             0.246       0.1053856

The Gaussian density is used to invert the conditional probability using Bayes formula to obtain the proper conditional probabilities.


问:
Google ReCaptcha Uncaught DOMException: Blocked a frame with origin "https://www.google.com"
I'm not sure why this is happening, and it isn't the usual, common error of:

Uncaught SecurityError: Block a frame with origin.

The error I'm getting is:

Uncaught DOMException: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.

I'm following Google's instructions on how to enable ReCaptcha, but it isn't working for me!

```<code>// top of the page
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
// then somewhere in the bottom
<div class="g-recaptcha" data-sitekey="@Model.Register.CaptchaSiteKey"></div>
</code>```

My CaptchaSiteKey is being loaded (I debugged and checked).

答:
As explained by the answer here https://stackoverflow.com/a/29014899/1853802, change all the http(s) protocols on your page to //

e.g.

```<code><script src="http://example1.com"></script> => <script src="//example1.com"></script>

<link href="https://example2.com" /> => <link href="//example2.com />
</code>```

This solved it for me.

NB: Remember to clear your cache afterwards.

Body:
I'm not sure why this is happening, and it isn't the usual, common error of:

Uncaught SecurityError: Block a frame with origin.

The error I'm getting is:

Uncaught DOMException: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.

I'm following Google's instructions on how to enable ReCaptcha, but it isn't working for me!

// top of the page

// then somewhere in the bottom

My CaptchaSiteKey is being loaded (I debugged and checked).

Body:
As explained by the answer here https://stackoverflow.com/a/29014899/1853802, change all the http(s) protocols on your page to //

e.g.

<script src="http://example1.com"></script> => <script src="//example1.com"></script>

<link href="https://example2.com" /> => <link href="//example2.com />

This solved it for me.

NB: Remember to clear your cache afterwards.


问:
Java Swing JFrame Layout
I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.

If I write the code of the button after the textfield then only the button is displayed.

Any idea why?

```<code>    JFrame mainframe=new JFrame();
    mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainframe.setBounds(0,0,200,200);
    JButton jb=new JButton();
    jb.setText("Leech");
    mainframe.add(jb);
    JTextField link=new JTextField(50);
    mainframe.add(link);
    mainframe.pack();
    mainframe.setVisible(true);
</code>```

答:
if you see BorderLayout Documentation
mainframe.add(jb); is equals to mainframe.add(jb,BorderLayout.CENTER);
mainframe.add(link); is equals to mainframe.add(jb,BorderLayout.CENTER);

so it just show the last one

Title: Java Swing JFrame Layout

Body:
I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.

If I write the code of the button after the textfield then only the button is displayed.

Any idea why?

    JFrame mainframe=new JFrame();
    mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainframe.setBounds(0,0,200,200);
    JButton jb=new JButton();
    jb.setText("Leech");
    mainframe.add(jb);
    JTextField link=new JTextField(50);
    mainframe.add(link);
    mainframe.pack();
    mainframe.setVisible(true);


问:
Python 3 - How to properly setup this multiprocessing job?
I have a file with like 10,000 rows, each row represents parameters to a download job. I have like 5 custom downloaders. Each job can take anywhere from 5 seconds to 2 minutes. How would I create something that iterates through the 10,000 rows, assigning each job to a downloader if that downloader isn't currently working?

EDIT:

The difficult part for me is that each Downloader is an instance of a class, and the differences between the instances are the port_numbers I specify when I instantiate each of the 5 Downloader objects. So I have a = Downloader(port_number=7751) ... e = Downloader(port_number=7755). Then, if I were to use a Downloader I would do a.run(row).

How do I define the workers as these a, b, c, d, e rather than a downloader function?

答:
There are many ways to do it - the simplest way would be to just use multiprocessing.Pool and let it organize the workers for you - 10k rows is not all that much, let's say that an average URL is even a full kilobyte long it will still take only 10MB of memory and memory is cheap.

So, just read the file in memory and map it to multiprocessing.Pool to do your bidding:

```<code>from multiprocessing import Pool

def downloader(param):  # our downloader process
    # download code here
    # param will hold a line from your file (including newline at the end, strip before use)
    # e.g. res = requests.get(param.strip())
    return True  # lets provide some response back

if __name__ == "__main__":  # important protection for cross-platform use

    with open("your_file.dat", "r") as f:  # open your file
        download_jobs = f.readlines()  # store each line in a list

    download_pool = Pool(processes=5)  # make our pool use 5 processes
    responses = download_pool.map(downloader, download_jobs)  # map our data, line by line
    download_pool.close()  # lets exit cleanly
    # you can check the responses for each line in the `responses` list
</code>```

You can also use threading instead of multiprocessing (or multiprocessing.pool.ThreadPool as a drop-in replacement for this) to do everything within a single process if you need shared memory. A single thread is more than enough for download purposes unless you're doing additional processing.

UPDATE

If you want your downloaders to run as class instances, you can transform the downloader function into a factory for your Downloader instances, and then just pass what you need to instantiate those instances alongside your URLs. Here is a simple Round-Robin approach:

```<code>from itertools import cycle
from multiprocessing import Pool

class Downloader(object):

    def __init__(self, port_number=8080):
        self.port_number = port_number

    def run(self, url):
        print("Downloading {} on port {}".format(url, self.port_number))

def init_downloader(params):  # our downloader initializator
    downloader = Downloader(**params[0])  # instantiate our downloader
    downloader.run(params[1])  # run our downloader
    return True  # you can provide your

if __name__ == "__main__":  # important protection for cross-platform use

    downloader_params = [  # Downloaders will be initialized using these params
        {"port_number": 7751},
        {"port_number": 7851},
        {"port_number": 7951}
    ]

    downloader_cycle = cycle(downloader_params)  # use cycle for round-robin distribution
    with open("your_file.dat", "r") as f:  # open your file
        # read our file line by line and attach downloader params to it
        download_jobs = [[next(downloader_cycle), row.strip()] for row in f]

    download_pool = Pool(processes=5)  # make our pool use 5 processes
    responses = download_pool.map(init_downloader, download_jobs)  # map our data
    download_pool.close()  # lets exit cleanly
    # you can check the responses for each line in the `responses` list
</code>```

Keep in mind that this is not the most balanced solution as it can happen to have two Downloader instances with the same port running, but it will average over large enough data.

If you want to make sure that you don't have two Downloader instances running off of the same port, you'll either need to build your own pool, or you'll need to create a central process that will issue ports to your Downloader instances when they need them.

Body:
There are many ways to do it - the simplest way would be to just use multiprocessing.Pool and let it organize the workers for you - 10k rows is not all that much, let's say that an average URL is even a full kilobyte long it will still take only 10MB of memory and memory is cheap.

So, just read the file in memory and map it to multiprocessing.Pool to do your bidding:

from multiprocessing import Pool

def downloader(param):  # our downloader process
    # download code here
    # param will hold a line from your file (including newline at the end, strip before use)
    # e.g. res = requests.get(param.strip())
    return True  # lets provide some response back

if __name__ == "__main__":  # important protection for cross-platform use

    with open("your_file.dat", "r") as f:  # open your file
        download_jobs = f.readlines()  # store each line in a list

    download_pool = Pool(processes=5)  # make our pool use 5 processes
    responses = download_pool.map(downloader, download_jobs)  # map our data, line by line
    download_pool.close()  # lets exit cleanly
    # you can check the responses for each line in the `responses` list

You can also use threading instead of multiprocessing (or multiprocessing.pool.ThreadPool as a drop-in replacement for this) to do everything within a single process if you need shared memory. A single thread is more than enough for download purposes unless you're doing additional processing.

UPDATE

If you want your downloaders to run as class instances, you can transform the downloader function into a factory for your Downloader instances, and then just pass what you need to instantiate those instances alongside your URLs. Here is a simple Round-Robin approach:

from itertools import cycle
from multiprocessing import Pool

class Downloader(object):

    def __init__(self, port_number=8080):
        self.port_number = port_number

    def run(self, url):
        print("Downloading {} on port {}".format(url, self.port_number))

def init_downloader(params):  # our downloader initializator
    downloader = Downloader(**params[0])  # instantiate our downloader
    downloader.run(params[1])  # run our downloader
    return True  # you can provide your

if __name__ == "__main__":  # important protection for cross-platform use

    downloader_params = [  # Downloaders will be initialized using these params
        {"port_number": 7751},
        {"port_number": 7851},
        {"port_number": 7951}
    ]

    downloader_cycle = cycle(downloader_params)  # use cycle for round-robin distribution
    with open("your_file.dat", "r") as f:  # open your file
        # read our file line by line and attach downloader params to it
        download_jobs = [[next(downloader_cycle), row.strip()] for row in f]

    download_pool = Pool(processes=5)  # make our pool use 5 processes
    responses = download_pool.map(init_downloader, download_jobs)  # map our data
    download_pool.close()  # lets exit cleanly
    # you can check the responses for each line in the `responses` list

Keep in mind that this is not the most balanced solution as it can happen to have two Downloader instances with the same port running, but it will average over large enough data.

If you want to make sure that you don't have two Downloader instances running off of the same port, you'll either need to build your own pool, or you'll need to create a central process that will issue ports to your Downloader instances when they need them.


问:
How to iterate through multiple UILabels
I am looking for an elegant way to iterate through an array and assign each of its values to one or more of five UILabels

This code illustrates what I am trying to do (although it is very long and repetitive)

```<code>    if touches.count >= 1 {
        positionTouch1LBL.text = String(describing: touches[0].location(in: view))
    } else {
        positionTouch1LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 2 {
        positionTouch2LBL.text = String(describing: touches[1].location(in: view))
    } else {
        positionTouch2LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 3 {
        positionTouch3LBL.text = String(describing: touches[2].location(in: view))
    } else {
        positionTouch3LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 4 {
        positionTouch4LBL.text = String(describing: touches[3].location(in: view))
    } else {
        positionTouch4LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 5 {
        positionTouch5LBL.text = String(describing: touches[4].location(in: view))
    } else {
        positionTouch5LBL.text = "0.0 / 0.0"
    }
</code>```

答:
You could do that by putting your labels in an array and iterate through them in the following way:

```<code>let labelsArray = [UILabel(), UILabel(), ... ] // An array containing your labels

for (index, element) in labelsArray.enumerated() {
    if index < touches.count {
        element.text = String(describing: touches[index].location(in: view))
    } else {
        element.text = "0.0 / 0.0"
    }
}
</code>```

Good luck!

Body:
I am looking for an elegant way to iterate through an array and assign each of its values to one or more of five UILabels

This code illustrates what I am trying to do (although it is very long and repetitive)

    if touches.count >= 1 {
        positionTouch1LBL.text = String(describing: touches[0].location(in: view))
    } else {
        positionTouch1LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 2 {
        positionTouch2LBL.text = String(describing: touches[1].location(in: view))
    } else {
        positionTouch2LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 3 {
        positionTouch3LBL.text = String(describing: touches[2].location(in: view))
    } else {
        positionTouch3LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 4 {
        positionTouch4LBL.text = String(describing: touches[3].location(in: view))
    } else {
        positionTouch4LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 5 {
        positionTouch5LBL.text = String(describing: touches[4].location(in: view))
    } else {
        positionTouch5LBL.text = "0.0 / 0.0"
    }

Body:
You could do that by putting your labels in an array and iterate through them in the following way:

let labelsArray = [UILabel(), UILabel(), ... ] // An array containing your labels

for (index, element) in labelsArray.enumerated() {
    if index < touches.count {
        element.text = String(describing: touches[index].location(in: view))
    } else {
        element.text = "0.0 / 0.0"
    }
}

Good luck!


问:
Heroku ENOENT: no such file or directory, stat '/app/build/index.html'
I'm having trouble running a simple test site in Heroku. For some reason  it's trying to serve the content from /app/build/ when I want it to serve from /build/.

Error: ENOENT: no such file or directory, stat '/app/build/index.html'

I read here not to use __dirname in the express app as Heroku set it to /app and that I should use process.cwd();

```<code>process.env.PWD = process.cwd();
</code>```

But it didn't work. Below is my server.js express app and folder structure

```<code>const path = require('path');
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();

process.env.PWD = process.cwd();

app.use(express.static(process.env.PWD + '/build'));

app.get('*', function (req, res) {
  const index = path.join(process.env.PWD, '/build/index.html');
  res.sendFile(index);
});

app.listen(port);
console.log('server_started');
</code>```

答:
dist folder is ignored. therefore heroku returns this error.
When you list your application files in heroku, you can see it is missing.

How to list folder/files in heroku

run heroku run bash in command line inside of your app folder

type dir and enter. then you will see the list of folders and files

Body:
I'm having trouble running a simple test site in Heroku. For some reason  it's trying to serve the content from /app/build/ when I want it to serve from /build/.

Error: ENOENT: no such file or directory, stat '/app/build/index.html'

I read here not to use __dirname in the express app as Heroku set it to /app and that I should use process.cwd();

process.env.PWD = process.cwd();

But it didn't work. Below is my server.js express app and folder structure

const path = require('path');
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();

process.env.PWD = process.cwd();

app.use(express.static(process.env.PWD + '/build'));

app.get('*', function (req, res) {
  const index = path.join(process.env.PWD, '/build/index.html');
  res.sendFile(index);
});

app.listen(port);
console.log('server_started');


问:
Fucntion parameter values to replace the integer from a string
I have a function the parameter has more than one values which I'm passing them after a loop. I want to use the values Im getting to replace integers in a string by there older. This is my code below</p>

```<code>onGetValues: function(response) {
            var message = response;
            var myValues = [];
            //Then Im looping it here to get all the value passed from the response ie "my name", "surname", "age"
            for (var i = 0;  i < message.length; i++) {
                myValues += message[i];
            }
            //global object with a string value like 12==12AND03==Im thirty
            var test == originalGlobalString
            //how can loop in the string above to replace the integers in the string with the values from  from the respnse parameter values and display like my name == surname AND age == im thirty?
            },
</code>```

答:
What you have put forward is not making sense to me, but here is part of what you are asking for:

Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/

JavaScript

```<code>$(function() {
  var myData = [
    "My Name", "Surname", "Age", "I'm thirty"
  ];

  function pad(i) {
    if (i.toString().length < 2) {
      return "0" + i;
    } else {
      return i;
    }
  }

  function getValues(t) {
    var myValues = [];
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        $.each(response, function(i, v) {
          myValues.push(v);
          myString += pad(i) + "==" + v + "AND";
        });
        //Remove last "AND"
        myString = myString.slice(0, -3);
        console.log("Array: ", myValues);
        console.log("String: ", myString);
        if (t == "array") {
          $("#results").html(myValues.join(", "));
        } else {
          $("#results").html(myString);
        }
      }
    });
  }
  $("#btn-1").click(function(e) {
    console.log("Click Event fired.");
    getValues();
  });
});
</code>```

Now if you want to get a string that says:

```<code>My Name==SurnameANDAge==I'm thirty
</code>```

You can step past one of your steps and do something like:

```<code>function getValues(t) {
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        for (var i = 0; i < response.length; i += 2) {
          myString += response[i] + "==" + response[i + 1] + "AND";
        }
        console.log(myString);
        $("#results").html(myString.slice(0, -3));
      }
    });
  }
</code>```

Since you didn't really clarify what you're doing with this, it's hard to help further.

Update

It took a bit of head scratching, but then I realized what you were trying to do. Basically we want to template, so seek in the string for a Integer and replace it with a corresponding string, based on that index in an array.

For example, if you have this string:

```<code>"0==1AND2==I'm thirty"
</code>```

and you have this array:

```<code>["My Name", "Surname", "Age"]
</code>```

The result would be a new string:

```<code>"My Name==SurnameANDAge==I'm thirty"
</code>```

Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/5/

```<code>  function getValues(response) {
    var partsA = testString.split("AND");
    console.log("A:", partsA);
    var partsB = [];
    var newString = "";
    $.each(partsA, function(k, v) {
      partsB = v.split("==");
      console.log("B-1:", partsB);
      if (!isNaN(partsB[0])) {
        partsB[0] = myData[parseInt(partsB[0])];
      }
      if (!isNaN(partsB[1])) {
        partsB[1] = myData[parseInt(partsB[1])];
      }
      console.log("B-2:", partsB);
      partsA[k] = partsB.join("==");
    });
    newString = partsA.join("AND");
    console.log("S:", newString);
    return newString;
  }
</code>```

This chunks the string into pieces based on "AND". We then break those into chunks based on "==". We examine each part, using isNaN() (Is Not a Number function), and if we find a number, we substitute the number with the string value from our data array.

For the test data, our console will show:

```<code>A: Array [ "0==1", "2==Im thirty" ]
B-1: Array [ "0", "1" ]
B-2: Array [ "My Name", "Surname" ]
B-1: Array [ "2", "Im thirty" ]
B-2: Array [ "Age", "Im thirty" ]
S: My Name==SurnameANDAge==I'm thirty
</code>```

The function then return the string. This could be improved to escape things like " or ' that could cause issues. Also if you have a string like:

```<code>"0 is Mary==1AND2==I'm Thirty"
</code>```

This will fail and 0 will not be detected since isNaN() will return true on a string of this nature. Your result would be:

```<code>"0 is Mary==SurnameANDAge==I'm Thirty"
</code>```

Hope that helps.

Body:
I have a function the parameter has more than one values which I'm passing them after a loop. I want to use the values Im getting to replace integers in a string by there older. This is my code below

onGetValues: function(response) {
            var message = response;
            var myValues = [];
            //Then Im looping it here to get all the value passed from the response ie "my name", "surname", "age"
            for (var i = 0;  i < message.length; i++) {
                myValues += message[i];
            }
            //global object with a string value like 12==12AND03==Im thirty
            var test == originalGlobalString
            //how can loop in the string above to replace the integers in the string with the values from  from the respnse parameter values and display like my name == surname AND age == im thirty?
            },

Body:
What you have put forward is not making sense to me, but here is part of what you are asking for:

Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/

JavaScript

$(function() {
  var myData = [
    "My Name", "Surname", "Age", "I'm thirty"
  ];

  function pad(i) {
    if (i.toString().length < 2) {
      return "0" + i;
    } else {
      return i;
    }
  }

  function getValues(t) {
    var myValues = [];
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        $.each(response, function(i, v) {
          myValues.push(v);
          myString += pad(i) + "==" + v + "AND";
        });
        //Remove last "AND"
        myString = myString.slice(0, -3);
        console.log("Array: ", myValues);
        console.log("String: ", myString);
        if (t == "array") {
          $("#results").html(myValues.join(", "));
        } else {
          $("#results").html(myString);
        }
      }
    });
  }
  $("#btn-1").click(function(e) {
    console.log("Click Event fired.");
    getValues();
  });
});

Now if you want to get a string that says:

My Name==SurnameANDAge==I'm thirty

You can step past one of your steps and do something like:

function getValues(t) {
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        for (var i = 0; i < response.length; i += 2) {
          myString += response[i] + "==" + response[i + 1] + "AND";
        }
        console.log(myString);
        $("#results").html(myString.slice(0, -3));
      }
    });
  }

Since you didn't really clarify what you're doing with this, it's hard to help further.

Update

It took a bit of head scratching, but then I realized what you were trying to do. Basically we want to template, so seek in the string for a Integer and replace it with a corresponding string, based on that index in an array.

For example, if you have this string:

"0==1AND2==I'm thirty"

and you have this array:

["My Name", "Surname", "Age"]

The result would be a new string:

"My Name==SurnameANDAge==I'm thirty"

Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/5/

  function getValues(response) {
    var partsA = testString.split("AND");
    console.log("A:", partsA);
    var partsB = [];
    var newString = "";
    $.each(partsA, function(k, v) {
      partsB = v.split("==");
      console.log("B-1:", partsB);
      if (!isNaN(partsB[0])) {
        partsB[0] = myData[parseInt(partsB[0])];
      }
      if (!isNaN(partsB[1])) {
        partsB[1] = myData[parseInt(partsB[1])];
      }
      console.log("B-2:", partsB);
      partsA[k] = partsB.join("==");
    });
    newString = partsA.join("AND");
    console.log("S:", newString);
    return newString;
  }

This chunks the string into pieces based on "AND". We then break those into chunks based on "==". We examine each part, using isNaN() (Is Not a Number function), and if we find a number, we substitute the number with the string value from our data array.

For the test data, our console will show:

A: Array [ "0==1", "2==Im thirty" ]
B-1: Array [ "0", "1" ]
B-2: Array [ "My Name", "Surname" ]
B-1: Array [ "2", "Im thirty" ]
B-2: Array [ "Age", "Im thirty" ]
S: My Name==SurnameANDAge==I'm thirty

The function then return the string. This could be improved to escape things like " or ' that could cause issues. Also if you have a string like:

"0 is Mary==1AND2==I'm Thirty"

This will fail and 0 will not be detected since isNaN() will return true on a string of this nature. Your result would be:

"0 is Mary==SurnameANDAge==I'm Thirty"

Hope that helps.


问:
How return list object to show in view
I have controller where I use service. That service do some querys and return List like this:

Controller:

```<code> public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }
</code>```

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

```<code><div id="event_box" class="margin-bottom-10"></div>
</code>```

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

```<code> return Json(consulta, JsonRequestBehavior.AllowGet);
</code>```

but How can I receive specific object into view?

答:
A ViewBag should work:

@ViewBag.TexttoLargo

You may want to parse the ViewBag result as it it looks like it is terminated with a return.

Title: How return list object to show in view

Body:
I have controller where I use service. That service do some querys and return List like this:

Controller:

 public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

 return Json(consulta, JsonRequestBehavior.AllowGet);

but How can I receive specific object into view?


问:
Python: l2-Penalty for logistic regression model from statsmodels?
Is there a way to put an l2-Penalty for the logistic regression model in statsmodel through a parameter or something else? I just found the l1-Penalty in the docs but nothing for the l2-Penalty.</p>

答:
If you look closely at the Documentation for statsmodels.regression.linear_model.OLS.fit_regularized you'll see that the current version of statsmodels allows for Elastic Net regularization which is basically just a convex combination of the L1- and L2-penalties (though more robust implementations employ some post-processing to diminish undesired behaviors of the naive implementations, see "Elastic Net" on Wikipedia for details):

2

If you take a look at the parameters for fit_regularized in the documentation:

OLS.fit_regularized(method='elastic_net', alpha=0.0, L1_wt=1.0, start_params=None, profile_scale=False, refit=False, **kwargs)

you'll realize that L1_wt is just lambda_1 in the first equation. So to get the L2-Penalty you're looking for, you just pass L1_wt=0 as an argument when you call the function. As an example:

```<code>model = sm.OLS(y, X)
results = model.fit_regularized(method='elastic_net', alpha=1.0, L1_wt=0.0)
print(results.summary())
</code>```

should give you  an L2 Penalized Regression predicting target y from input X.

Hope that helps!

P.S. Three final comments:

1) statsmodels currently only implements elastic_net as an option to the method argument. So that gives you L1 and L2 and any linear combination of them but nothing else (for OLS at least);

2) L1 Penalized Regression = LASSO (least absolute shrinkage and selection operator);

3) L2 Penalized Regression = Ridge Regression, the Tikhonov–Miller method, the Phillips–Twomey method, the constrained linear inversion method, and the method of linear regularization.

Body:
If you look closely at the Documentation for statsmodels.regression.linear_model.OLS.fit_regularized you'll see that the current version of statsmodels allows for Elastic Net regularization which is basically just a convex combination of the L1- and L2-penalties (though more robust implementations employ some post-processing to diminish undesired behaviors of the naive implementations, see "Elastic Net" on Wikipedia for details):

2

If you take a look at the parameters for fit_regularized in the documentation:

OLS.fit_regularized(method='elastic_net', alpha=0.0, L1_wt=1.0, start_params=None, profile_scale=False, refit=False, **kwargs)

you'll realize that L1_wt is just lambda_1 in the first equation. So to get the L2-Penalty you're looking for, you just pass L1_wt=0 as an argument when you call the function. As an example:

model = sm.OLS(y, X)
results = model.fit_regularized(method='elastic_net', alpha=1.0, L1_wt=0.0)
print(results.summary())

should give you  an L2 Penalized Regression predicting target y from input X.

Hope that helps!

P.S. Three final comments:

1) statsmodels currently only implements elastic_net as an option to the method argument. So that gives you L1 and L2 and any linear combination of them but nothing else (for OLS at least);

2) L1 Penalized Regression = LASSO (least absolute shrinkage and selection operator);

3) L2 Penalized Regression = Ridge Regression, the Tikhonov–Miller method, the Phillips–Twomey method, the constrained linear inversion method, and the method of linear regularization.


答:
Read in your 10000 rows into a list of strings.

```<code>with open('foo.dat') as f:
    data = f.readlines()
</code>```

Assuming that the data does not include a port number and the edited question mentions 5 ports, you should add that to the data.

```<code>data = [(p, d) for p, d in zip(itertools.cycle([7751, 7752, 7753, 7754, 7755]), data)]
</code>```

Write a function that takes one of those tuples as an argument, splits it, creates a Downloader object and runs it.

```<code>def worker(target):
    port, params = target
    d = Downloader(port_number=port)
    d.run(params)
    return params # for lack of more information.
</code>```

Use the imap_unordered method of a multiprocessing.Pool, giving it the function you've defined and the list of tuples as arguments.

The iterator returned by imap_unordered will start yielding results as soon as they become available. You could print them to show the progress.

```<code>p = multiprocessing.Pool()
for params in p.imap_unordered(worker, data):
    print('Finished downloading', params)
</code>```

Edit

P.S: if the only method of your Downloader object you'll ever use is run(), it should not be an object. It is a function in disguise! Look up the "stop writing classes" video on Youtube and watch it.

Title: Python 3 - How to properly setup this multiprocessing job?

Body:
I have a file with like 10,000 rows, each row represents parameters to a download job. I have like 5 custom downloaders. Each job can take anywhere from 5 seconds to 2 minutes. How would I create something that iterates through the 10,000 rows, assigning each job to a downloader if that downloader isn't currently working?

EDIT:

The difficult part for me is that each Downloader is an instance of a class, and the differences between the instances are the port_numbers I specify when I instantiate each of the 5 Downloader objects. So I have a = Downloader(port_number=7751) ... e = Downloader(port_number=7755). Then, if I were to use a Downloader I would do a.run(row).

How do I define the workers as these a, b, c, d, e rather than a downloader function?

Body:
Read in your 10000 rows into a list of strings.

with open('foo.dat') as f:
    data = f.readlines()

Assuming that the data does not include a port number and the edited question mentions 5 ports, you should add that to the data.

data = [(p, d) for p, d in zip(itertools.cycle([7751, 7752, 7753, 7754, 7755]), data)]

Write a function that takes one of those tuples as an argument, splits it, creates a Downloader object and runs it.

def worker(target):
    port, params = target
    d = Downloader(port_number=port)
    d.run(params)
    return params # for lack of more information.

Use the imap_unordered method of a multiprocessing.Pool, giving it the function you've defined and the list of tuples as arguments.

The iterator returned by imap_unordered will start yielding results as soon as they become available. You could print them to show the progress.

p = multiprocessing.Pool()
for params in p.imap_unordered(worker, data):
    print('Finished downloading', params)

Edit

P.S: if the only method of your Downloader object you'll ever use is run(), it should not be an object. It is a function in disguise! Look up the "stop writing classes" video on Youtube and watch it.


问:
How to convert Number in word in Twig File
I want to convert Price:200$ in words like Price:Two Hundred$.

In twig like this {{ price }} but this is show Number.

Can any one know how it is possible show this price in word in Twig ?

答:
The Intl filter provided by the official Twig's extensions repository can spellout numbers:

```<code>{{ 19.2|localizednumber('spellout') }}
{# Output: nineteen point two #}
</code>```

For this filter to work,  the PHP intl extension is needed and the twig/extensions package must be installed.

If you use Twig directly, register the extension like this:

```<code>$twig->addExtension(new Twig_Extensions_Extension_Intl());
</code>```

If you use Symfony, register this service:

```<code>services:
    Twig_Extensions_Extension_Intl:
        class: Twig_Extensions_Extension_Intl
        private: true
        tags:
            - { name: twig.extension }
</code>```

Body:
The Intl filter provided by the official Twig's extensions repository can spellout numbers:

{{ 19.2|localizednumber('spellout') }}
{# Output: nineteen point two #}

For this filter to work,  the PHP intl extension is needed and the twig/extensions package must be installed.

If you use Twig directly, register the extension like this:

$twig->addExtension(new Twig_Extensions_Extension_Intl());

If you use Symfony, register this service:

services:
    Twig_Extensions_Extension_Intl:
        class: Twig_Extensions_Extension_Intl
        private: true
        tags:
            - { name: twig.extension }


问:
How to divide block in piece when they overlap
Some input I'm looking to build a simple minimal bittorrent client.
I reading the protocol spec for a 2-3 days now.

here what my understanding on it thus far . Assuming that torrent has a piece length of 26000 bytes and according to non official spec block size is 16384. Something like this.

Now upon request of a block of piece message would look like this

```<code>piece 0
block offset 0
block length 16484
</code>```

So far so good.

Now, for next block which overlap in piece 0 and 1 what should the request look like

```<code>piece 0  ## since the start of byte is in piece 0 use piece 0 instead of piece 1
block offset 16384
block length 16384
</code>```

Now on the receiving end I need to recreate the piece of 26000 bytes so that I can compare that with pieces (hash) to match the piece for correctness.

Is my understanding correct ?

Also I'm let suppose the piece verification failed and may be it because of the first block i.e Block 0 (which is faulty or corrupt)
then I should requeue Block 0 and Block 1 (which was valid btw and also a part of piece 1) to retransmit again.

And now suddenly the piece and block distribution become a bit complex then what I assume it be. and I hoping there is a simpler solution to this.

Any thought

答:
Will use the more distinct term 'chunk' instead of the ambiguous 'block'.

A torrent is divided into pieces.

A piece is divided into chunks.

A chunk is cut from one piece.

A torrent is divided into pieces when it's created. With the Request message, a piece is in turn further divided into chunks by the downloading BitTorrent client.

How the client cut the chunks out from a piece doesn't matter, as long as no single chunk is larger than 16 KB (16384 bytes).

The simplest and most rational way to divide a piece, is to do it in as few chunks as possible, by dividing it in 16 KB chunks and let the last chunk of the piece be smaller if necessary.

The Request message format: <len=0013><id=6><Piece_index><Chunk_offset><Chunk_length>

<Piece_index > integer specifying the zero-based piece index

<Chunk_offset> integer specifying the zero-based byte offset within the piece

<Chunk_length> integer specifying the requested number of bytes

When requesting a chunk:

the whole chunk must be within the piece specified by the Piece_index,

ie Chunk_offset+Chunk_length must be less or equal to the size of that specific piece*.

the Chunk_length can not be larger than 16 KB (16384 bytes) and must be at least 1 byte

the peer that get the request must have the piece specified by the Piece_index

If any of the conditions is not met, the peer receiving the request will close the connection.

* For all pieces except the very last one that is the 'piece length' defined in the info-dictionary.

The size of the last piece can by calculated as:

size_last_piece = size_of_torrent - (number_of_pieces - 1) * 'piece length'

Body:
Some input I'm looking to build a simple minimal bittorrent client.
I reading the protocol spec for a 2-3 days now.

here what my understanding on it thus far . Assuming that torrent has a piece length of 26000 bytes and according to non official spec block size is 16384. Something like this.

Now upon request of a block of piece message would look like this

piece 0
block offset 0
block length 16484

So far so good.

Now, for next block which overlap in piece 0 and 1 what should the request look like

piece 0  ## since the start of byte is in piece 0 use piece 0 instead of piece 1
block offset 16384
block length 16384

Now on the receiving end I need to recreate the piece of 26000 bytes so that I can compare that with pieces (hash) to match the piece for correctness.

Is my understanding correct ?

Also I'm let suppose the piece verification failed and may be it because of the first block i.e Block 0 (which is faulty or corrupt)
then I should requeue Block 0 and Block 1 (which was valid btw and also a part of piece 1) to retransmit again.

And now suddenly the piece and block distribution become a bit complex then what I assume it be. and I hoping there is a simpler solution to this.

Any thought


问:
regex doesn't work with data binding
I am doing validation with Angular,

```<code><div ng-if="field.required !== 'true'">
   <input id="fld-{{field.id}}" name="{{field.id}}" ng-model="$ctrl.configuration[$ctrl.selectedPlatform][field.id]" ng-pattern="{{field.regex}}">
</div>
</code>```

This is the field data:

```<code>{
  "id": "addItemToHistoryAfterNSeconds",
  "label": "Add Video to History after how many seconds?",
  "type": "string",
  "default": "5",
  "regex": "/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/"
}
</code>```

So this basically matches numeric value, for testing purpose.

However, the validation doesn't pass, shows ng-invalid.

When I write ng-patter="/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/" directly, the validation pass.

Anyone knows why?

Update:

I want to valid only numeric value, so I will be using:

```<code>/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/
</code>```

答:
There is a difference between how regex is defined in the HTML and JS code. If ng-pattern allows you to use "/regex-here/" notation with single backslashes denoting literal backslashes, JS code does not as you define strings there using C strings (that is, string literals where you may use escape sequences).

There, you may use either a constructor initialization (using a string), or a regex literal.

Remember that you need to use double backslashes in a string literal, and single backslashes in a regex literal to denote a literal backslash (needed for a regex escape).

```<code>"regex": "^\\+?([0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$"
"regex": /^\+?([0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/
</code>```

should work.

Title: regex doesn't work with data binding

Body:
I am doing validation with Angular,

   <input id="fld-{{field.id}}" name="{{field.id}}" ng-model="$ctrl.configuration[$ctrl.selectedPlatform][field.id]" ng-pattern="{{field.regex}}">

This is the field data:

{
  "id": "addItemToHistoryAfterNSeconds",
  "label": "Add Video to History after how many seconds?",
  "type": "string",
  "default": "5",
  "regex": "/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/"
}

So this basically matches numeric value, for testing purpose.

However, the validation doesn't pass, shows ng-invalid.

When I write ng-patter="/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/" directly, the validation pass.

Anyone knows why?

Update:

I want to valid only numeric value, so I will be using:

/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/

Body:
There is a difference between how regex is defined in the HTML and JS code. If ng-pattern allows you to use "/regex-here/" notation with single backslashes denoting literal backslashes, JS code does not as you define strings there using C strings (that is, string literals where you may use escape sequences).

There, you may use either a constructor initialization (using a string), or a regex literal.

Remember that you need to use double backslashes in a string literal, and single backslashes in a regex literal to denote a literal backslash (needed for a regex escape).

"regex": "^\\+?([0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$"
"regex": /^\+?([0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/

should work.


问:
How to get exact search results on top using Apache Lucene?
How to get best score searches on top using Apache Lucene?

```<code>1. State Authority
2. Authority State
</code>```

Now user searches for "Authority State" or "State Authority", we are getting same results for both in above fashion. But for "Authority State" Search results should be

```<code>1. Authority State
2. State Authority
</code>```

Following is lucene query on fields:

```<code>name:Authority State*
name:Authority State
name:Authority*
name:State*

for (String field : INDEXED_FIELDS) {
           bool.should(qb.keyword().wildcard().onField(field).matching(userInputBuilder.toString()).createQuery());
        }

        for (String field : INDEXED_FIELDS) {
          for (String match : pattern) {
               bool.should(qb.keyword().onField(field).matching(match).createQuery());
          }
        }
</code>```

There is no sorting on results.

Could anyone suggest how to get exact results?

答:
The keyword query type just looks to match the same tokens of the input, not taking into consideration the order.

When you need it to take into consideration the order of the tokens within the phrase use the phrase query:

```<code>Query query = queryBuilder
                .phrase()
                    .withSlop( 2 )//or other options of the Phrase query
                    .onField( field )
                    .sentence( userInputBuilder.toString() )
                .createQuery();
</code>```

You might also be interested in trying out the latest "Simple Query Builder".

In case you're interested into "debugging" the scores, you could have the query engine output not just the results but also the score value and the evaluation formula used for each hit:

```<code>List<Object[]> results = (List<Object[]>) fullTextSession
    .createFullTextQuery( mltQuery, Coffee.class )
    .setProjection( ProjectionConstants.THIS, ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION )
    .list();
</code>```

This will get you, for each hit, an array of three elements:

the matched entity instance

the score value

a string explaining how it was scored

Body:
How to get best score searches on top using Apache Lucene?

1. State Authority
2. Authority State

Now user searches for "Authority State" or "State Authority", we are getting same results for both in above fashion. But for "Authority State" Search results should be

1. Authority State
2. State Authority

Following is lucene query on fields:

name:Authority State*
name:Authority State
name:Authority*
name:State*

for (String field : INDEXED_FIELDS) {
           bool.should(qb.keyword().wildcard().onField(field).matching(userInputBuilder.toString()).createQuery());
        }

        for (String field : INDEXED_FIELDS) {
          for (String match : pattern) {
               bool.should(qb.keyword().onField(field).matching(match).createQuery());
          }
        }

There is no sorting on results.

Could anyone suggest how to get exact results?

Body:
The keyword query type just looks to match the same tokens of the input, not taking into consideration the order.

When you need it to take into consideration the order of the tokens within the phrase use the phrase query:

Query query = queryBuilder
                .phrase()
                    .withSlop( 2 )//or other options of the Phrase query
                    .onField( field )
                    .sentence( userInputBuilder.toString() )
                .createQuery();

You might also be interested in trying out the latest "Simple Query Builder".

In case you're interested into "debugging" the scores, you could have the query engine output not just the results but also the score value and the evaluation formula used for each hit:

List<Object[]> results = (List<Object[]>) fullTextSession
    .createFullTextQuery( mltQuery, Coffee.class )
    .setProjection( ProjectionConstants.THIS, ProjectionConstants.SCORE, ProjectionConstants.EXPLANATION )
    .list();

This will get you, for each hit, an array of three elements:

the matched entity instance

the score value

a string explaining how it was scored


问:
Angular 2 two way data binding with ngModel
First off I am new to Typescript and Angular 2 and this seems like an obvious answer but I can't seem to get it to work. I have the following model

```<code>export interface IBrand {
    brandID: number;
    name: string;
    image: string;
}
</code>```

Then I have the component class

```<code>import { Component, OnInit }  from '@angular/core';
import { Router, RouteParams } from '@angular/router-deprecated'
import { bootstrap } from '@angular/platform-browser-dynamic';

import { IBrand } from './brand';
import { BrandService } from './brand.service';

@Component({
    selector: 'data-bind',
    templateUrl: 'app/dashboardApp/brands/brand-list.component.html',
    styleUrls: ['app/dashboardApp/brands/brand-list.component.css']
})

export class BrandListComponent implements OnInit {
    brands: IBrand[];
    errorMessage: string;
    newBrand: IBrand;
    pageTitle: string = 'Brands';

    constructor(private _brandService: BrandService,
        private _router: Router) {
    }

    ngOnInit(): void {
        this._brandService.getBrands()
            .subscribe(
            brands => this.brands = brands,
            error => this.errorMessage = <any>error);
    }
}
</code>```

And then I have the following html

```<code><div class="form-group">
    <label for="brandName">Brand:</label>
    <input type="text" class="form-control" placeholder="Name" id="brandName" [(ngModel)]="newBrand.name" />
</div>
</code>```

I can't get the properties of IBrand to work successfully and I get the error

platform-browser.umd.js:962 ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined

However I can bind it easily to something like pageTitle. Any ideas that can point me in the right direction?

答:
It's been a while since I have asked this question, and it's starting to get some views so I will add my answer.

First I would need to change my interface to a class and add a constructor.

```<code>export class Brand {
  constructor() {}
  brandID: number;
  name: string;
  image: string;
}
</code>```

Now that I have a constructor I can use the new operator to instantiate the object.

```<code>export class BrandListComponent implements OnInit {
  brands: Brand[];
  errorMessage: string;
  newBrand: Brand = new Brand();
  pageTitle: string = 'Brands';

  (...)
}
</code>```

Now I have the desired brand initialized without any data and I can bind it to the model. Hope this helps.

Body:
First off I am new to Typescript and Angular 2 and this seems like an obvious answer but I can't seem to get it to work. I have the following model

export interface IBrand {
    brandID: number;
    name: string;
    image: string;
}

Then I have the component class

import { Component, OnInit }  from '@angular/core';
import { Router, RouteParams } from '@angular/router-deprecated'
import { bootstrap } from '@angular/platform-browser-dynamic';

import { IBrand } from './brand';
import { BrandService } from './brand.service';

@Component({
    selector: 'data-bind',
    templateUrl: 'app/dashboardApp/brands/brand-list.component.html',
    styleUrls: ['app/dashboardApp/brands/brand-list.component.css']
})

export class BrandListComponent implements OnInit {
    brands: IBrand[];
    errorMessage: string;
    newBrand: IBrand;
    pageTitle: string = 'Brands';

    constructor(private _brandService: BrandService,
        private _router: Router) {
    }

    ngOnInit(): void {
        this._brandService.getBrands()
            .subscribe(
            brands => this.brands = brands,
            error => this.errorMessage = <any>error);
    }
}

And then I have the following html

    Brand:
    <input type="text" class="form-control" placeholder="Name" id="brandName" [(ngModel)]="newBrand.name" />

I can't get the properties of IBrand to work successfully and I get the error

platform-browser.umd.js:962 ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined

However I can bind it easily to something like pageTitle. Any ideas that can point me in the right direction?

Body:
It's been a while since I have asked this question, and it's starting to get some views so I will add my answer.

First I would need to change my interface to a class and add a constructor.

export class Brand {
  constructor() {}
  brandID: number;
  name: string;
  image: string;
}

Now that I have a constructor I can use the new operator to instantiate the object.

export class BrandListComponent implements OnInit {
  brands: Brand[];
  errorMessage: string;
  newBrand: Brand = new Brand();
  pageTitle: string = 'Brands';

  (...)
}

Now I have the desired brand initialized without any data and I can bind it to the model. Hope this helps.