问:
Parse a file 2 lines at a time
Python beginner here. I have a file that looks like that (every field is \t separated):

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)
</code>```

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

```<code>with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"
</code>```

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

```<code>with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))
</code>```

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

答:
you can use the pandas module to read the file in as a dataframe (although you might have a little trouble getting your column names sorted out.

Assuming you aren't familiar with pandas (put it on your list of things to learn, it's well worth it for anything data related) you might try something like this:

```<code>with open('file.txt') as f:
    data = f.readlines()

indexes = []
for i, line in enumerate(data[:-1]):
    if (line.split('    ')[2] == data[i+1].split('    ')[2]) and line.split('    ')[2] == 'SYNONYMOUS':
        indexes.append(i)

for i in indexes:
     print data[i], data[i+1] # or do whatever you want with those
</code>```

indexes is a list of the positions of the first of each pair of lines in your file that match your conditions.

Depending on what you want to do pandas might be a better way something like (and this is just a guess because I can't load you example into pandas because of the different lenghts of lines (due to the ...))

```<code>import pandas as pd

df = pd.read_csv('file.txt', sep='\t', header=0) # might be header=None

df.columns=['mutation', 'strain', 'syn', 'info']

match_df = df.loc[df['syn'] == df['syn'].shift(1)] # might need to specify axis= for .shift
</code>```

this would give you a dataframe of (again) the first of each pair.

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
you can use the pandas module to read the file in as a dataframe (although you might have a little trouble getting your column names sorted out.

Assuming you aren't familiar with pandas (put it on your list of things to learn, it's well worth it for anything data related) you might try something like this:

with open('file.txt') as f:
    data = f.readlines()

indexes = []
for i, line in enumerate(data[:-1]):
    if (line.split('    ')[2] == data[i+1].split('    ')[2]) and line.split('    ')[2] == 'SYNONYMOUS':
        indexes.append(i)

for i in indexes:
     print data[i], data[i+1] # or do whatever you want with those

indexes is a list of the positions of the first of each pair of lines in your file that match your conditions.

Depending on what you want to do pandas might be a better way something like (and this is just a guess because I can't load you example into pandas because of the different lenghts of lines (due to the ...))

import pandas as pd

df = pd.read_csv('file.txt', sep='\t', header=0) # might be header=None

df.columns=['mutation', 'strain', 'syn', 'info']

match_df = df.loc[df['syn'] == df['syn'].shift(1)] # might need to specify axis= for .shift

this would give you a dataframe of (again) the first of each pair.


来源: stackexchange

问:
ClientError (SignatureDoesNotMatch) when trying to upload file to Amazon S3 from an EC2 instance in a Flask app
I'm trying to write a Flask app to upload to an AWS S3 bucket. Where, when I run this locally in PyCharm it works fine. However, once I deployed it to AWS (deploying the Flask app on port 80) I now get an error...

```<code>botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the ListBuckets operation: The request sture we calculated does not match the signature you provided. Check your key and signing method.
</code>```

When the keys work locally...but don't work on the AWS EC2 instance. Some of my initial thoughts were maybe a port issue or an issue with boto3. Though I'm not sure because it works locally, just not on AWS.

Any help? Here is my code...with keys and URLs removed ofc

app.py

```<code>from flask import Flask, render_template, flash
from werkzeug.utils import secure_filename
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from tools import s3_upload

'''
Author: xxx
'''

app = Flask(__name__)
app.config.from_object('config')
# Flask Secret Key
app.secret_key = 'xxxxx'

# Limits what file types can be uploaded
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

# Initializes upload form
class UploadForm(FlaskForm):
    example = FileField(validators=[FileRequired()])

# Route for root, handles on click action for upload form
@app.route('/', methods=['POST', 'GET'])
def upload_page():
    form = UploadForm()
    if form.validate_on_submit():
        file = form.example.data
        filename = secure_filename(file.filename)
        output = s3_upload(file,filename)
        flash('{src} uploaded to S3'.format(src=form.example.data.filename))
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()
</code>```

tools.py

```<code>import boto3
from flask import current_app as app

'''
Author: xxx
'''

def s3_upload(source_file, source_filename):
    # What directory on Amazon S3 Bucket to upload to.
    upload_dir = app.config["S3_UPLOAD_DIRECTORY"]

    #Connect to S3 and upload file
    s3 = boto3.client('s3')
    s3.upload_fileobj(source_file, app.config["S3_BUCKET"], upload_dir + "/" + source_filename)
</code>```

config.py

```<code>S3_KEY = 'xxx'
S3_SECRET = 'xxxx'
S3_UPLOAD_DIRECTORY = 'xxxx'
S3_BUCKET = 'xxxx'
ALLOWED_EXTENSIONS = ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']

SECRET_KEY = "xxxx"
DEBUG = True
</code>```

答: The issue turned out to be a key issue with AWS and also a network security issue of me using a port that is blocked on the network here. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a Flask app to upload to an AWS S3 bucket. Where, when I run this locally in PyCharm it works fine. However, once I deployed it to AWS (deploying the Flask app on port 80) I now get an error...

botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the ListBuckets operation: The request sture we calculated does not match the signature you provided. Check your key and signing method.

When the keys work locally...but don't work on the AWS EC2 instance. Some of my initial thoughts were maybe a port issue or an issue with boto3. Though I'm not sure because it works locally, just not on AWS.

Any help? Here is my code...with keys and URLs removed ofc

app.py

from flask import Flask, render_template, flash
from werkzeug.utils import secure_filename
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from tools import s3_upload

'''
Author: xxx
'''

app = Flask(__name__)
app.config.from_object('config')
# Flask Secret Key
app.secret_key = 'xxxxx'

# Limits what file types can be uploaded
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

# Initializes upload form
class UploadForm(FlaskForm):
    example = FileField(validators=[FileRequired()])

# Route for root, handles on click action for upload form
@app.route('/', methods=['POST', 'GET'])
def upload_page():
    form = UploadForm()
    if form.validate_on_submit():
        file = form.example.data
        filename = secure_filename(file.filename)
        output = s3_upload(file,filename)
        flash('{src} uploaded to S3'.format(src=form.example.data.filename))
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()

tools.py

import boto3
from flask import current_app as app

'''
Author: xxx
'''

def s3_upload(source_file, source_filename):
    # What directory on Amazon S3 Bucket to upload to.
    upload_dir = app.config["S3_UPLOAD_DIRECTORY"]

    #Connect to S3 and upload file
    s3 = boto3.client('s3')
    s3.upload_fileobj(source_file, app.config["S3_BUCKET"], upload_dir + "/" + source_filename)

config.py

S3_KEY = 'xxx'
S3_SECRET = 'xxxx'
S3_UPLOAD_DIRECTORY = 'xxxx'
S3_BUCKET = 'xxxx'
ALLOWED_EXTENSIONS = ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']

SECRET_KEY = "xxxx"
DEBUG = True


问:
Data Binding Library create wrong type in auto generated java class
I have a POJO class like this (I removed irrelevant fields)

```<code>public class FeedingTable {

    private String Day;

    private Integer Fasting; <-- note that this field is Integer
}
</code>```

and use it in a Layout xml:

```<code><data>

    <variable
        name="friday"
        type="models.FeedingTable" />
</data>

<!-- other views -->
<EditText
    android:id="@+id/fasting"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="number"
    android:text="@={friday.fasting}">
<!-- other views -->
</code>```

when I compile my project, I've got compile time error, I checked it and I figure out the generated java class for this layout create a Short field for the EditText and it have problem in casting Short to Integer.

```<code>// somewhere in generated java class
private android.databinding.InverseBindingListener fridayFastingandroidTextAttrChanged = new android.databinding.InverseBindingListener() {
    @Override
    public void onChange() {
        // Inverse of friday.fasting
        //         is friday.setFasting((java.lang.Integer) callbackArg_0)
        java.lang.Short callbackArg_0 = utilities.BindingUtils.getShortText(fridayFasting);
        // localize variables for thread safety
        // friday
        models.FeedingTable friday = mFriday;
        // friday.fasting
        java.lang.Integer fridayFasting = null; <-- ???????!!!!!!
        // friday != null
        boolean fridayJavaLangObjectNull = false;

        fridayJavaLangObjectNull = (friday) != (null);
        if (fridayJavaLangObjectNull) {

            friday.setFasting(((java.lang.Integer) (callbackArg_0))); <-- in this line I have error
        }
    }
};
</code>```

why this happens? I try to clean and rebuild project, but no success. why data binder create Short instead of Integer? if you see it's create java.lang.Integer fridayFasting = null; but never use it. I'm seriously confused how data binder works!

答:
You've already recognized that there is no automatic conversion between String and Integer and have added two-way binding for Short. I imagine it is something like this:

```<code>package utilities;
public class BindingUtils {
    @InverseBindingAdapter(attribute = "android:text")
    public static Short getShortText(TextView view) {...}
}
</code>```

But there is no conversion from Short to Integer. Data Binding got a little confused because there is a cast conversion from short to int and tried to use straight casting to solve the problem.

If you're using Android Studio 3.0, you can use InverseMethods to do conversions. You'd use something like this:

```<code>public class BindingUtils {
    @InverseMethod("stringToInteger")
    public static String intToString(Integer value) { ... }

    public static Integer stringToInteger(String value) { ... }
}
</code>```

You can read more about them here.

On an Android Studio 2.3, you must use the proper types in your InverseBindingAdapter and cannot rely on data binding to do class conversions.

```<code>public class BindingUtils {
    @InverseBindingAdapter(attribute = "android:text")
    public static Integer getIntText(TextView view) {...}

    @BindingAdapter("android:text")
    public static void setIntText(TextView view, Integer value) { ... }
}
</code>```

Body:
I have a POJO class like this (I removed irrelevant fields)

public class FeedingTable {

    private String Day;

    private Integer Fasting; <-- note that this field is Integer
}

and use it in a Layout xml:

<data>

    <variable
        name="friday"
        type="models.FeedingTable" />
</data>

<EditText
    android:id="@+id/fasting"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="number"
    android:text="@={friday.fasting}">

when I compile my project, I've got compile time error, I checked it and I figure out the generated java class for this layout create a Short field for the EditText and it have problem in casting Short to Integer.

// somewhere in generated java class
private android.databinding.InverseBindingListener fridayFastingandroidTextAttrChanged = new android.databinding.InverseBindingListener() {
    @Override
    public void onChange() {
        // Inverse of friday.fasting
        //         is friday.setFasting((java.lang.Integer) callbackArg_0)
        java.lang.Short callbackArg_0 = utilities.BindingUtils.getShortText(fridayFasting);
        // localize variables for thread safety
        // friday
        models.FeedingTable friday = mFriday;
        // friday.fasting
        java.lang.Integer fridayFasting = null; <-- ???????!!!!!!
        // friday != null
        boolean fridayJavaLangObjectNull = false;

        fridayJavaLangObjectNull = (friday) != (null);
        if (fridayJavaLangObjectNull) {

            friday.setFasting(((java.lang.Integer) (callbackArg_0))); <-- in this line I have error
        }
    }
};

why this happens? I try to clean and rebuild project, but no success. why data binder create Short instead of Integer? if you see it's create java.lang.Integer fridayFasting = null; but never use it. I'm seriously confused how data binder works!

Body:
You've already recognized that there is no automatic conversion between String and Integer and have added two-way binding for Short. I imagine it is something like this:

package utilities;
public class BindingUtils {
    @InverseBindingAdapter(attribute = "android:text")
    public static Short getShortText(TextView view) {...}
}

But there is no conversion from Short to Integer. Data Binding got a little confused because there is a cast conversion from short to int and tried to use straight casting to solve the problem.

If you're using Android Studio 3.0, you can use InverseMethods to do conversions. You'd use something like this:

public class BindingUtils {
    @InverseMethod("stringToInteger")
    public static String intToString(Integer value) { ... }

    public static Integer stringToInteger(String value) { ... }
}

You can read more about them here.

On an Android Studio 2.3, you must use the proper types in your InverseBindingAdapter and cannot rely on data binding to do class conversions.

public class BindingUtils {
    @InverseBindingAdapter(attribute = "android:text")
    public static Integer getIntText(TextView view) {...}

    @BindingAdapter("android:text")
    public static void setIntText(TextView view, Integer value) { ... }
}


问:
.Net Core localization, what am I doing wrong?
I am playing with .Net core and localization. I have followed a couple of articles, chiefly https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization but can't seem to get data from my resource file.

Startup.ConfigureServices

```<code>   services.AddLocalization(opts => opts.ResourcesPath = "Resources");

        services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                var supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-GB"),
                };

                opts.DefaultRequestCulture = new RequestCulture("en-GB");
                // Formatting numbers, dates, etc.
                opts.SupportedCultures = supportedCultures;
                // UI strings that we have localized.
                opts.SupportedUICultures = supportedCultures;
            });

        services
            .AddMvc()
            .AddJsonOptions(opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => opts.ResourcesPath = "Resources")
            .AddDataAnnotationsLocalization()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
</code>```

A ViewModel I would Like to be localized

```<code>[Validator(typeof(LoginViewModelValidator))]
public class Login
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class LoginViewModelValidator : AbstractValidator<Login>
{
    public LoginViewModelValidator(IStringLocalizer<LoginViewModelValidator> localizer)
    {
        RuleFor(login => login.Email).NotEmpty()
            .WithMessage(x => localizer["Email"])
            .EmailAddress()
            .WithMessage(x => localizer["Email address must be valid"]);
        RuleFor(reg => reg.Password).NotEmpty().WithMessage(x => localizer["Password required"]);
    }
}
</code>```

Location of resource file

Resource file contents

As far as I can tell the localizer should be able to find the localized string, as my current culture is en-GB.

Does anyone know what i have done wrong.

I am also confused as the msdn article explains

If the localized value of "About Title" is not found, then the indexer
  key is returned, that is, the string "About Title".

but how can it ever lookup using "About Title" as a name as it has a space in it and cannot be entered into the .resx name?

Thanks

EDIT

I have removed the culture configuration from IServicesCollection and added it to the middlewrae pipeline instead:

```<code> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var supportedCultures = new[]
            {
                new CultureInfo("en-GB"),
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-GB"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

            app.UseStaticFiles();

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

I also enusured the naming of the resource was correct. IE Full namespace, minus the assembly name then classname then culture.

ViewModels.LoginViewModelValidator.en-GB.resx and it all works now. Thanks for the comments everyone

答:
I think you also need this in ConfigureServices

```<code>services.AddLocalization(options => options.ResourcesPath = "Resources");
</code>```

Did you wire up the RequestLocalization middleware in Configure?

```<code>var locOptions =
app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
</code>```

I am not sure about the sub folders you have under the Resources folder I am not doing that in my projects and it is working for me.

Body:
I am playing with .Net core and localization. I have followed a couple of articles, chiefly https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization but can't seem to get data from my resource file.

Startup.ConfigureServices

   services.AddLocalization(opts => opts.ResourcesPath = "Resources");

        services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                var supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-GB"),
                };

                opts.DefaultRequestCulture = new RequestCulture("en-GB");
                // Formatting numbers, dates, etc.
                opts.SupportedCultures = supportedCultures;
                // UI strings that we have localized.
                opts.SupportedUICultures = supportedCultures;
            });

        services
            .AddMvc()
            .AddJsonOptions(opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => opts.ResourcesPath = "Resources")
            .AddDataAnnotationsLocalization()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

A ViewModel I would Like to be localized

[Validator(typeof(LoginViewModelValidator))]
public class Login
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class LoginViewModelValidator : AbstractValidator<Login>
{
    public LoginViewModelValidator(IStringLocalizer<LoginViewModelValidator> localizer)
    {
        RuleFor(login => login.Email).NotEmpty()
            .WithMessage(x => localizer["Email"])
            .EmailAddress()
            .WithMessage(x => localizer["Email address must be valid"]);
        RuleFor(reg => reg.Password).NotEmpty().WithMessage(x => localizer["Password required"]);
    }
}

Location of resource file

Resource file contents

As far as I can tell the localizer should be able to find the localized string, as my current culture is en-GB.

Does anyone know what i have done wrong.

I am also confused as the msdn article explains

If the localized value of "About Title" is not found, then the indexer
  key is returned, that is, the string "About Title".

but how can it ever lookup using "About Title" as a name as it has a space in it and cannot be entered into the .resx name?

Thanks

EDIT

I have removed the culture configuration from IServicesCollection and added it to the middlewrae pipeline instead:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var supportedCultures = new[]
            {
                new CultureInfo("en-GB"),
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-GB"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Auth}/{action=Login}/{id?}");
            });
        }

I also enusured the naming of the resource was correct. IE Full namespace, minus the assembly name then classname then culture.

ViewModels.LoginViewModelValidator.en-GB.resx and it all works now. Thanks for the comments everyone

Body:
I think you also need this in ConfigureServices

services.AddLocalization(options => options.ResourcesPath = "Resources");

Did you wire up the RequestLocalization middleware in Configure?

var locOptions =
app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);

I am not sure about the sub folders you have under the Resources folder I am not doing that in my projects and it is working for me.


问:
Get property value from xml file in Jenkinsfile
I have a Jenkinsfile in which I need a property from my .csproj file (dotnet core project)

I have tried this:

def versionPrefix =  sh(script: 'cat ./src/project.csproj | grep (?<=<VersionPrefix>).*(?=</VersionPrefix>)')

I know I'm probably far off, so I'm not necessarily looking for something close to this, but I am looking for a solution not requiring plugins (preferably).

答:
Solution without pipeline

First install the Environment Script Plugin

Then configure as the image bellow

Enviroment Script Plugin

In the image I get the version from the build.xml file, the "-o" arg in egrep (also works with grep) is to return only the part I want and not the entire line, the rest is pure regex to match the number version with . (dot), something like

1.3.13

Solution WITH pipeline

Just adjust the grep in the image for yout need's

```<code>def versionPrefix =  sh(script: 'grep -o (?<=<VersionPrefix>).*(?=</VersionPrefix>) ./src/project.csproj')
</code>```

Body:
Solution without pipeline

First install the Environment Script Plugin

Then configure as the image bellow

Enviroment Script Plugin

In the image I get the version from the build.xml file, the "-o" arg in egrep (also works with grep) is to return only the part I want and not the entire line, the rest is pure regex to match the number version with . (dot), something like

1.3.13

Solution WITH pipeline

Just adjust the grep in the image for yout need's

def versionPrefix =  sh(script: 'grep -o (?<=<VersionPrefix>).*(?=</VersionPrefix>) ./src/project.csproj')


问:
python command line programming examples, recipes
There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.

My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loops and I just dont think that is the most efficient approach.

Could someone provide links to open source cli programs that I may pick to gain a bit of an understanding? Or, books, tutorials, etc that I could get my hands on. I have dug around but have had little success (my google skills must be lacking).

答:
I like baker. You use it like so:</p>

```<code>% cat my.py
import baker

@baker.command
def cmd(start, end):
    print '%s %s' % (start, end)

if __name__ == '__main__':
    baker.run()

% python my.py cmd 2010-12-01 2010-12-31
2010-12-01 2010-12-31
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I like baker. You use it like so:

% cat my.py
import baker

@baker.command
def cmd(start, end):
    print '%s %s' % (start, end)

if __name__ == '__main__':
    baker.run()

% python my.py cmd 2010-12-01 2010-12-31
2010-12-01 2010-12-31


答:
Maybe this will be helpful, it includes the methods you described:
https://docs.oracle.com/cd/E18727_01/doc.121/e13483/T359831T498954.htm</p>

Title: Can't find the digit check algorithm

Body:
I can´t find which algorithm is being used to to calculate the 2 digits check digit of my bank references.

Some examples

0404 3295 60983
0707 3328 25810
0900 9907 32991
0900 8912 91695
0707 2268 89938
0808 1153 45010
0808 0964 91963
0900 6632 28254
0707 2802 64344
0909 0256 01882
0707 3004 54587
0707 3164 30453
0404 2914 27064
0707 3306 30672
0404 1467 53870
0808 1733 55047
0808 2349 11733
0707 3158 51956
0707 3346 64573
0404 3396 83589

I know that the last 2 digits are the check digits, because of the user account.

for example:
Area: 040
User account: 43266008
Bank reference: 0404 3266 00828
so... 28 <- Check digits.

I tried with Mod 97 and Base 10 (Luhn)

I don't know other algorithms like:
Mod 22, Base 36, Algorithm 45

¿Any idea?

Grouping and counting my samples, if it help for something:

CheckDigits SamplesCount
01  2720
02  2698
03  2743
04  2719
05  2820
06  2737
07  2795
08  2737
09  2760
10  2778
11  2787
12  2780
13  2779
14  2658
15  2711
16  2770
17  2718
18  2675
19  2669
20  2675
21  2780
22  2737
23  2721
24  2723
25  2631
26  2694
27  2615
28  2800
29  2903
30  2718
31  2712
32  2733
33  2813
34  2782
35  2820
36  2754
37  2686
38  2755
39  2774
40  2688
41  2738
42  2799
43  2669
44  2774
45  2754
46  2623
47  2684
48  2711
49  2740
50  2735
51  2658
52  2793
53  2752
54  2782
55  2818
56  2718
57  2735
58  2738
59  2755
60  2716
61  2818
62  2738
63  2716
64  2710
65  2607
66  2640
67  2799
68  2763
69  2827
70  2968
71  2734
72  2679
73  2758
74  2730
75  2856
76  2713
77  2768
78  2694
79  2684
80  2693
81  2798
82  2739
83  2809
84  2754
85  2710
86  2833
87  2820
88  2739
89  2733
90  2739
91  2745
92  2805
93  2686
94  2771
95  2758
96  2754
97  2688

Example:

The reference for Sears and Oxxo have a check digit that is Mod10 (Luhn).

(You can calculate the luhn check digit in this page: https://planetcalc.com/2464/)

Reference: 0900 5719 759
Check digit (Luhn): 3

How do i get the 88?


问:
Why i got 'undefined' when function contructer called with already existed object?
Here is my CODE in snippet .

Also tell me what is happening under the hood of javascript engine when i called this CODE

    function foo(a){

        this.a = a;

    }

    var obj0 ={

        foo:foo
    };

    var obj1 ={

        foo:foo
    };

    console.log( obj0.foo(5) );  // undefined
    console.log( obj1.foo(10) ); // undefined```

答:
Well it returns undefined because there's no return statement in

```<code>function foo(a) {
  this.a = a;
}
</code>```

When you call console.log(obj.foo(5)) you don't instantiate a new foo object using foo as a constructor function, you simply call foo as a regular function (here as a method of obj).

However, if you'd had instantiated an object you'd have used : console.log(new obj.foo(5)).

Calling foo on obj0 with 1 as its parameter simply sets obj0's property a to 1 and nothing more. However if you wanted something to be returned you'd have written :

```<code>function foo(a) {
  this.a=a;
  return /*something here*/;
}
</code>```

EDIT

You say that you call the constructor function on an already existing object, that is technically true : you call the function but not as a constructor function. A constructor function is called as a constructor function with the new keyword and then, and only then, will return a new object.

What you're actually doing is just using foo as a setter for a on those objects (and there's no return statement, so it returns undefined).

Body:
Well it returns undefined because there's no return statement in

function foo(a) {
  this.a = a;
}

When you call console.log(obj.foo(5)) you don't instantiate a new foo object using foo as a constructor function, you simply call foo as a regular function (here as a method of obj).

However, if you'd had instantiated an object you'd have used : console.log(new obj.foo(5)).

Calling foo on obj0 with 1 as its parameter simply sets obj0's property a to 1 and nothing more. However if you wanted something to be returned you'd have written :

function foo(a) {
  this.a=a;
  return /*something here*/;
}

EDIT

You say that you call the constructor function on an already existing object, that is technically true : you call the function but not as a constructor function. A constructor function is called as a constructor function with the new keyword and then, and only then, will return a new object.

What you're actually doing is just using foo as a setter for a on those objects (and there's no return statement, so it returns undefined).


问:
How to combine two update queries having different set and where clause?
I wish to optimize database access by combining this two queries, if possible.

How to combine this two statements into one?

```<code>update tbl_priority SET a=1 where j='j1' and priority='1';
update tbl_priority SET g=1 where j='j1';
</code>```

Any help, suggestion is highly appreciated.

答:
I don't see a nice clean way of combining these two update statements, because the logic in the WHERE clause does not agree.  However, we can retain the common condition j = 'j1' in the WHERE clause, and then use a CASE expression to handle the a assignement:

```<code>UPDATE tbl_priority
SET a = CASE WHEN priority = '1' THEN 1 ELSE a END,
    g = 1
WHERE j = 'j1'
</code>```

Note that this is not ideal because we have a branch of the CASE expression which assigns a back to itself.  This by itself should not cause a particular record to show up as having been modified though.

Body:
I wish to optimize database access by combining this two queries, if possible.

How to combine this two statements into one?

update tbl_priority SET a=1 where j='j1' and priority='1';
update tbl_priority SET g=1 where j='j1';

Any help, suggestion is highly appreciated.

Body:
I don't see a nice clean way of combining these two update statements, because the logic in the WHERE clause does not agree.  However, we can retain the common condition j = 'j1' in the WHERE clause, and then use a CASE expression to handle the a assignement:

UPDATE tbl_priority
SET a = CASE WHEN priority = '1' THEN 1 ELSE a END,
    g = 1
WHERE j = 'j1'

Note that this is not ideal because we have a branch of the CASE expression which assigns a back to itself.  This by itself should not cause a particular record to show up as having been modified though.


问:
Why does creating a blank matrix return null instead of 0.0?
I have a Java method fill0s() that inputs a smaller matrix into a larger matrix, supposedly filled with 0s:

```<code>public class PoolingFunctions {

    // Fill needed spaces with 0
    public static Double[][] fill0s(Double[][] image, int filter_size){
        int columns_remaining = filter_size - (image[0].length%filter_size);
        int rows_remaining = filter_size - (image.length%filter_size);
        // CREATE A MATRIX: HERE LIES THE PROBLEM: //////////////////////////////
        Double [][] blank_matrix = new Double [(image.length)+columns_remaining][(image[0].length)+rows_remaining];
            for (int i = 0; i<image.length; i++) {
                for (int j = 0; j<image[i].length; j++) {
                    blank_matrix[i][j] = image[i][j];
                }
            }

        return blank_matrix;
    }
}
</code>```

And after calling this method:

```<code>public class MainPooling{
    public static void main(String[] args) {
        Double[][] image =  {   {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0}
                            };

        Double[][] formatted_image;
        formatted_image = PoolingFunctions.fill0s(image,3);
        TestMatricesJava.print2dMatrix(formatted_image);
    }
}
</code>```

I get the following result:

```<code>1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
null null null null null null
null null null null null null
</code>```

My question is: Why does the function return a null instead of a 0.0?

答:
Since Double is a class, the default value for an array of Double is null, not 0.0.

You'll need to either use the primitive type double or initialize the matrix explicitly.

Body:
I have a Java method fill0s() that inputs a smaller matrix into a larger matrix, supposedly filled with 0s:

public class PoolingFunctions {

    // Fill needed spaces with 0
    public static Double[][] fill0s(Double[][] image, int filter_size){
        int columns_remaining = filter_size - (image[0].length%filter_size);
        int rows_remaining = filter_size - (image.length%filter_size);
        // CREATE A MATRIX: HERE LIES THE PROBLEM: //////////////////////////////
        Double [][] blank_matrix = new Double [(image.length)+columns_remaining][(image[0].length)+rows_remaining];
            for (int i = 0; i<image.length; i++) {
                for (int j = 0; j<image[i].length; j++) {
                    blank_matrix[i][j] = image[i][j];
                }
            }

        return blank_matrix;
    }
}

And after calling this method:

public class MainPooling{
    public static void main(String[] args) {
        Double[][] image =  {   {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0}
                            };

        Double[][] formatted_image;
        formatted_image = PoolingFunctions.fill0s(image,3);
        TestMatricesJava.print2dMatrix(formatted_image);
    }
}

I get the following result:

1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
null null null null null null
null null null null null null

My question is: Why does the function return a null instead of a 0.0?


问:
Unable to train Tesseract in Ubuntu
I am new in Tesseract,  I am trying to train Tesseract in Ubuntu, I am using JTessBoxEditor for trainer, I have successfully generated .tif and .box file, but I am unable to Trainer data using it,  during JTessBoxEditor Trainer, I don't know which Tesseract Executable location need to select for training data.
Can some please help here. Thanks in advance.

答: You'd need to build the Tesseract training tools first. Their installation directory can be determined by executing which tesseract command.

ContentLicense: CC BY-SA 4.0

Title: Unable to train Tesseract in Ubuntu


问:
Displaying JPA resultList in console
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

```<code>public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}
</code>```

I'm trying to display it in console, but the result I get is:

```<code>Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]
</code>```

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

```<code>Bronie@7662c85f
</code>```

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.

答:
I see three parts in your question:

In the first part of your question you are displaying the SQL query that hibernate creates to query the database to recover the rows. The dynamic table and column names are strange but it's an implementation detail.

In the second part of your question you talks about a neeed to separate columns. You don't have to separate anything, your query goes like this:

The entity manager reads the database row

Instantiates and object of the class mapped and requested

Initializes the properties of the object with data in the row

Third part, printing an object:

The print result you showed is the default, the class name with the address in the Virtual Machine. As others say, you can Override the toString method to change default behaviour, and print by default wathever you like. Please consider default printing something internal and create custom methos for end user views or printing.

Title: Displaying JPA resultList in console

Body:
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}

I'm trying to display it in console, but the result I get is:

Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

Bronie@7662c85f

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.


问:
Add class to empty elements only
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

```<code>if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}
</code>```

答:
This is probably what you're looking for:

```<code>$('.Prodotto').filter(':empty').addClass('empty-content');
</code>```

Or even shorter:

```<code>$('.Prodotto:empty').addClass('empty-content');
</code>```

In your code you're first testing if there are any empty elements with the class Prodotto, but then you query Prodotto a second time and apply the new class to all of them.

Title: Add class to empty elements only

Body:
The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}

Body:
This is probably what you're looking for:

$('.Prodotto').filter(':empty').addClass('empty-content');

Or even shorter:

$('.Prodotto:empty').addClass('empty-content');

In your code you're first testing if there are any empty elements with the class Prodotto, but then you query Prodotto a second time and apply the new class to all of them.


答:
Try</p>

```<code>update tbl_priority SET g=1, a = CASE WHEN priority='1' THEN 1 ELSE a END
where j='j1' ;
</code>```

Title: How to combine two update queries having different set and where clause?

Body:
Try

update tbl_priority SET g=1, a = CASE WHEN priority='1' THEN 1 ELSE a END
where j='j1' ;


问:
Variables in Adobe Flex
I'm tyring to use a variable that I declare in my CDATA later on in my flex document. How can I manipulate "userid" in the CDATA and also send it off in the later HTTPService code?

```<code><fx:Style source="felxible_1.css"/>

<fx:Script>
    <![CDATA[
        public var userid:String;
    ]]>
</fx:Script>

<fx:Declarations>

    <mx:HTTPService
        id="fetch_list_1"
        result="listfetched1(event)"
        method="POST"
        url="find_data_1.php"
        useProxy="false">
        <mx:request xmlns="">
            <userid>userid</userid>
        </mx:request>
    </mx:HTTPService>

</fx:Declarations>
</code>```

答:
You need to use the "binding" syntax.  In your script, make the variable send update messages when you change it:

```<code>[Bindable] var userid:String;
</code>```

Then, in the markup, tell the userid tag to update when the variable changes.

```<code><userid>{userid}</userid>
</code>```

Title: Variables in Adobe Flex

Body:
I'm tyring to use a variable that I declare in my CDATA later on in my flex document. How can I manipulate "userid" in the CDATA and also send it off in the later HTTPService code?

<fx:Style source="felxible_1.css"/>

<fx:Script>
    <![CDATA[
        public var userid:String;
    ]]>
</fx:Script>

<fx:Declarations>

    <mx:HTTPService
        id="fetch_list_1"
        result="listfetched1(event)"
        method="POST"
        url="find_data_1.php"
        useProxy="false">
        <mx:request xmlns="">
            <userid>userid</userid>
        </mx:request>
    </mx:HTTPService>

</fx:Declarations>

Body:
You need to use the "binding" syntax.  In your script, make the variable send update messages when you change it:

[Bindable] var userid:String;

Then, in the markup, tell the userid tag to update when the variable changes.

<userid>{userid}</userid>


问:
Model and input features for Random forest don't match
I am trying to perform Machine Learning on the dataset and trying to display the samples and test data. My goal is to later load my IMAGE and test it with the model. Kindly help me in solving the error.

```<code>%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_mldata
import numpy as np
import random
from sklearn import ensemble

mnist = fetch_mldata('MNIST original', data_home='./')

#Define variables
n_samples = len(mnist.data)
x = mnist.data.reshape((n_samples, -1))# array of feature of 28*28 pixel
y = mnist.target                         # Class label from 0-9 as there are digits

#Create random indices
sample_index=random.sample(range(len(x)),len(x)/5) #Selecting randomly list of len(x)/5 from the size of x
valid_index=[i for i in range(len(x)) if i not in sample_index]# Selecting the rest of the digits

#Sample and validation images
sample_images=[x[i] for i in sample_index]# 28*28 size of array which was used to classify digits in different classes
valid_images=[x[i] for i in valid_index]

#Sample and validation targets
sample_target=[y[i] for i in sample_index] # digits 0-9
valid_target=[y[i] for i in valid_index]

#Using the Random Tree Classifier
classifier = ensemble.RandomForestClassifier(n_estimators=30)

#Fit model with sample data
classifier.fit(sample_images, sample_target)

#Attempt to predict validation data
score=classifier.score(valid_images, valid_target)
print 'Random Tree Classifier:\n'
print 'Score\t'+str(score)

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

def plot_decision_regions(X, y, classifier,
                    test_idx=None, resolution=0.02):
    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                         np.arange(x2_min, x2_max, resolution))
</code>```

Till here I am not having any error, but after this line:

```<code>Z = classifier.predict(np.c_[xx1.ravel(), xx2.ravel()])
plot_decision_regions(x,y,classifier,test_idx=10)
</code>```

I am having the following error:

```<code>ValueError: Number of features of the model must match the input. Model n_features is 784 and input n_features is 2
</code>```

答:
When you are calling the function classifier.predict you need to pass a new set of testing samples as argument from which your classifier will predict new labels. However, you are passing a meshed matrix, which doesn't make any sense at all. Obviously, your matrix has only 2 columns and the predictor complains as it expects to have 784 columns as your trainset had.

I also recommend you check other areas of your code as I spotted some mistakes (e.g. len(x)/5 has to be casted as int).

Hope this helps. Good luck!

Body:
I am trying to perform Machine Learning on the dataset and trying to display the samples and test data. My goal is to later load my IMAGE and test it with the model. Kindly help me in solving the error.

%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_mldata
import numpy as np
import random
from sklearn import ensemble

mnist = fetch_mldata('MNIST original', data_home='./')

#Define variables
n_samples = len(mnist.data)
x = mnist.data.reshape((n_samples, -1))# array of feature of 28*28 pixel
y = mnist.target                         # Class label from 0-9 as there are digits

#Create random indices
sample_index=random.sample(range(len(x)),len(x)/5) #Selecting randomly list of len(x)/5 from the size of x
valid_index=[i for i in range(len(x)) if i not in sample_index]# Selecting the rest of the digits

#Sample and validation images
sample_images=[x[i] for i in sample_index]# 28*28 size of array which was used to classify digits in different classes
valid_images=[x[i] for i in valid_index]

#Sample and validation targets
sample_target=[y[i] for i in sample_index] # digits 0-9
valid_target=[y[i] for i in valid_index]

#Using the Random Tree Classifier
classifier = ensemble.RandomForestClassifier(n_estimators=30)

#Fit model with sample data
classifier.fit(sample_images, sample_target)

#Attempt to predict validation data
score=classifier.score(valid_images, valid_target)
print 'Random Tree Classifier:\n'
print 'Score\t'+str(score)

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

def plot_decision_regions(X, y, classifier,
                    test_idx=None, resolution=0.02):
    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                         np.arange(x2_min, x2_max, resolution))

Till here I am not having any error, but after this line:

Z = classifier.predict(np.c_[xx1.ravel(), xx2.ravel()])
plot_decision_regions(x,y,classifier,test_idx=10)

I am having the following error:

ValueError: Number of features of the model must match the input. Model n_features is 784 and input n_features is 2


问:
DELETE query in Postgres hangs indefinitely
Currently I am trying to delete a row(s) in a particular database table api_user. Yet deleting hangs for seemingly infinite time ( currently been running for 1800 seconds as I've been looking for answers ). The row in question had foreign key dependents, yet all of those dependents were deleted already, thats been verified.

I'm running all of my database introspection through Postico ( just another database GUI client ) So When i cancel the query i receive this error message.

```<code>ERROR: canceling statement due to user request
CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."api_event" x WHERE $1::pg_catalog.text OPERATOR(pg_catalog.= ) "user_id"::pg_catalog.text FOR KEY SHARE OF x"
</code>```

There are indexes that referenced the rows in this table. api_event is one table that had indexes on and foreign keys to this table. All of the dependent rows from api_event were deleted.

I've checked pg_stat_activity for any queries that could be running concurrently to no avail, and so I'm at a point where I'm not sure what the next question I should be asking is. Any direction would be great!

Running EXPLAIN DELETE FROM api_user WHERE organization_id = '<replaced value>'; returns this to me:

Delete on api_user  (cost=54.94..2903.50 rows=1874 width=6)
  ->  Bitmap Heap Scan on api_user  (cost=54.94..2903.50 rows=1874 width=6)
        Recheck Cond: ((organization_id)::text = '<replaced value>'::text)
        ->  Bitmap Index Scan on api_user_organization_id  (cost=0.00..54.47 rows=1874 width=0)
              Index Cond: ((organization_id)::text = '<replaced value>'::text)

Lock Monitoring

Did you check if it's waiting for a lock? – a_horse_with_no_name

As per request I searched the locks on my database. I used this query:

```<code> select t.relname,
        l.locktype,
        page,
        virtualtransaction,
        pid,
        mode,
        granted
 from pg_locks l,
      pg_stat_all_tables t
 where l.relation=t.relid
 order by relation asc;
</code>```

The first return, my DELETE was not running, container 3 rows of locks from pg_class, pg_index, and pg_namespace.

The second return, my DELETE was running, contained 21 rows of locks. All of which were of a relname from a previously deleted set of rows that had either a foreign key or an index with this row.

Road to Resolution

Through more questions and researching, an interesting tidbit arose that not all foreign keys on child tables have indexes. After composing a query to see what foreign keys don't have indexes I noted that api_event did not have an index to its api_user foreign key. Now api_event is a humongous table.

Creating an index on api_event solved the issue.

```<code>CREATE INDEX CONCURRENTLY user_id_to_events ON api_event(user_id);
</code>```

答: I'm not sure (and not able to comment) but I think you are experiencing an heavy re-indexation or a vacuum after your deletion. </p>

Body:
Currently I am trying to delete a row(s) in a particular database table api_user. Yet deleting hangs for seemingly infinite time ( currently been running for 1800 seconds as I've been looking for answers ). The row in question had foreign key dependents, yet all of those dependents were deleted already, thats been verified.

I'm running all of my database introspection through Postico ( just another database GUI client ) So When i cancel the query i receive this error message.

ERROR: canceling statement due to user request
CONTEXT: SQL statement "SELECT 1 FROM ONLY "public"."api_event" x WHERE $1::pg_catalog.text OPERATOR(pg_catalog.= ) "user_id"::pg_catalog.text FOR KEY SHARE OF x"

There are indexes that referenced the rows in this table. api_event is one table that had indexes on and foreign keys to this table. All of the dependent rows from api_event were deleted.

I've checked pg_stat_activity for any queries that could be running concurrently to no avail, and so I'm at a point where I'm not sure what the next question I should be asking is. Any direction would be great!

Running EXPLAIN DELETE FROM api_user WHERE organization_id = '<replaced value>'; returns this to me:

Delete on api_user  (cost=54.94..2903.50 rows=1874 width=6)
  ->  Bitmap Heap Scan on api_user  (cost=54.94..2903.50 rows=1874 width=6)
        Recheck Cond: ((organization_id)::text = '<replaced value>'::text)
        ->  Bitmap Index Scan on api_user_organization_id  (cost=0.00..54.47 rows=1874 width=0)
              Index Cond: ((organization_id)::text = '<replaced value>'::text)

Lock Monitoring

Did you check if it's waiting for a lock? – a_horse_with_no_name

As per request I searched the locks on my database. I used this query:

 select t.relname,
        l.locktype,
        page,
        virtualtransaction,
        pid,
        mode,
        granted
 from pg_locks l,
      pg_stat_all_tables t
 where l.relation=t.relid
 order by relation asc;

The first return, my DELETE was not running, container 3 rows of locks from pg_class, pg_index, and pg_namespace.

The second return, my DELETE was running, contained 21 rows of locks. All of which were of a relname from a previously deleted set of rows that had either a foreign key or an index with this row.

Road to Resolution

Through more questions and researching, an interesting tidbit arose that not all foreign keys on child tables have indexes. After composing a query to see what foreign keys don't have indexes I noted that api_event did not have an index to its api_user foreign key. Now api_event is a humongous table.

Creating an index on api_event solved the issue.

CREATE INDEX CONCURRENTLY user_id_to_events ON api_event(user_id);


问:
UILabel dynamically change font size and keep position?
I have to change a font size and while I do it :

Keep it centered in the same position

adjust the frame to fit.

When I do number 2, it will not stay centered :

```<code>   label.font = label.font.withSize(max*percentage)
  label.sizeToFit()
</code>```

If I don't, i will have to change frame and find how it fit the font dynamically.
Is there any elegant way of 2 rows ?

答:
If you want to keep the same center for your label, you must first define a center. You can create a UIView and then center your label on the view, and then set clipToBounds to false. In this case your label is centered in the view.

This UIView can actually be anything. You just need constraint to tell swift that your label is centered related to something, when updating frame, keep it centered. Here is an example with a label centered in my view controller

I have a time to increase font size per second

```<code>func timerDidFire(timer: Timer) {
    size += 5
    label.font = label.font.withSize(CGFloat(size))
    label.sizeToFit()
}
</code>```

And the simulator result is

Body:
I have to change a font size and while I do it :

Keep it centered in the same position

adjust the frame to fit.

When I do number 2, it will not stay centered :

   label.font = label.font.withSize(max*percentage)
  label.sizeToFit()

If I don't, i will have to change frame and find how it fit the font dynamically.
Is there any elegant way of 2 rows ?

Body:
If you want to keep the same center for your label, you must first define a center. You can create a UIView and then center your label on the view, and then set clipToBounds to false. In this case your label is centered in the view.

This UIView can actually be anything. You just need constraint to tell swift that your label is centered related to something, when updating frame, keep it centered. Here is an example with a label centered in my view controller

I have a time to increase font size per second

func timerDidFire(timer: Timer) {
    size += 5
    label.font = label.font.withSize(CGFloat(size))
    label.sizeToFit()
}

And the simulator result is


问:
Compare between two hashmap in javascript
I try to find a solution to compare two hashmaps in javascript but I have a difficulty.

This is my situation, I have a hashmap composed of a key + value in form of an array.

Example : 125 : [1 , 2 , 3].

And then I take this data and I compare it with another hashmap with this kind.

Example :

```<code>123 : [[1 , 1 , 1][2 , 8.7 , 10]]
124 : [[0 , 0, 5.4][3 , 4 , 5][7, 9.1 , 6]
125 : [[1 , 2 , 3][0.4 , 4 , 8]]
</code>```

The second hashmap is similar to the first , but its value could contain an array of N arrays. The goal : To parse the second hashmap with my first hashmap and search if once it finds the value of the first in an array of the second it must return "OK"

For example in this case : it will return "OK" because we can notice that the key 125 and her value in the first hashmap is include in 125 : [[1 , 2 , 3][0.4 , 4 , 8]]

I should not only test on the values but also on the keys

答:
The use of JSON.stringify can simplify your life:

let compareKey = JSON.stringify([1, 2, 3]);

let hash = {
 123 : [[1 , 1 , 1], [2 , 8.7 , 10]],
 124 : [[0 , 0, 5.4], [3 , 4 , 5], [7, 9.1 , 6]],
 125 : [[1 , 2 , 3], [0.4 , 4 , 8]]
};

for(let hashKey in hash) {

 hash[hashKey].forEach(el => {
  if (JSON.stringify(el) === compareKey)
   console.log(hashKey);
 });

}```

Body:
I try to find a solution to compare two hashmaps in javascript but I have a difficulty.

This is my situation, I have a hashmap composed of a key + value in form of an array.

Example : 125 : [1 , 2 , 3].

And then I take this data and I compare it with another hashmap with this kind.

Example :

123 : [[1 , 1 , 1][2 , 8.7 , 10]]
124 : [[0 , 0, 5.4][3 , 4 , 5][7, 9.1 , 6]
125 : [[1 , 2 , 3][0.4 , 4 , 8]]

The second hashmap is similar to the first , but its value could contain an array of N arrays. The goal : To parse the second hashmap with my first hashmap and search if once it finds the value of the first in an array of the second it must return "OK"

For example in this case : it will return "OK" because we can notice that the key 125 and her value in the first hashmap is include in 125 : [[1 , 2 , 3][0.4 , 4 , 8]]

I should not only test on the values but also on the keys


问:
PHP Sublime Text Use Find and Replace Regular Expression
I got a problem, i need to search and replace some words
Here is an example :

```<code>$num = $enreg1["num"];
$daterecep = $enreg1["date_recep"];
</code>```

And I want at the end :

```<code>$num = $enreg1->num;
$daterecep = $enreg1->date_recep;
</code>```

Then i wrote this regular expression :

```<code>enreg[1-9]?\["[\w]+"]
</code>```

It's working fine, i find all my word like I Want but the problem is when I want to replace what I found.
Because I just want to replace the [" by ->   and   "] by nothing.

If someone know how is working Sublime Text for replace !

Thanks for your help !!!!

答:
You will need to add parenthesis in your regular expression to get matched values, like this:

```<code>(enreg[1-9]?)\["([\w]+)"]
</code>```

Then, you can retrieve this values using $x in the replace input ($1 for the first value, $2 for the second...).

In your case, you will have to use the following replace pattern :

```<code>$1->$2
</code>```

For the first line, $1 will be replaced by "enreg1" and $2 by "num" so you will have:

```<code>$num = $enreg1->num;
</code>```

Body:
I got a problem, i need to search and replace some words
Here is an example :

$num = $enreg1["num"];
$daterecep = $enreg1["date_recep"];

And I want at the end :

$num = $enreg1->num;
$daterecep = $enreg1->date_recep;

Then i wrote this regular expression :

enreg[1-9]?\["[\w]+"]

It's working fine, i find all my word like I Want but the problem is when I want to replace what I found.
Because I just want to replace the [" by ->   and   "] by nothing.

If someone know how is working Sublime Text for replace !

Thanks for your help !!!!

Body:
You will need to add parenthesis in your regular expression to get matched values, like this:

(enreg[1-9]?)\["([\w]+)"]

Then, you can retrieve this values using $x in the replace input ($1 for the first value, $2 for the second...).

In your case, you will have to use the following replace pattern :

$1->$2

For the first line, $1 will be replaced by "enreg1" and $2 by "num" so you will have:

$num = $enreg1->num;


问:
Allowing admins to add users with Devise
I'm trying to make it so only admins can add uses with devise. I've gotten it mostly working however now when I'm logged in as an admin and submit the sign up form it kicks me back with the error: You are already signed in.

I've tried to follow the instructions here: http://wiki.summercode.com/rails_authentication_with_devise_and_cancan but it doesn't seem to mention this situation.

Do I need to do further overriding in the editors_controller to allow this?

Here are my routes ("editors" is the name of my user model):

```<code>devise_for :admins, :skip => [:registrations]

as :admin do
  get 'admin/editors'        => 'editors#index',                  as: :admin_editors
  get 'admin/editors/new'    => 'editors#new',                    as: :new_editor
  delete 'admin/editors/:id' => 'editors#destroy',                as: :destroy_editor
end

devise_for :editors, :skip => [:registrations],  :controllers => { :registrations => "editors" }
</code>```

and my editors_controller in "app/controllers/"

```<code>    class EditorsController < Devise::RegistrationsController
  before_filter :check_permissions, :only => [:new, :create, :cancel]
  skip_before_filter :require_no_authentication

  def dashboard
    render "editors/dashboard.html.haml"
  end

  def index
    @editors = Editor.all
    respond_to do |format|
      format.html
    end
  end

  private
    def check_permissions
      authorize! :create, resource
    end
end
</code>```

EDIT
I noticed this Processing by Devise::RegistrationsController#create as HTML in the logs when I submit the form. I had suspected that perhaps the skip_before_filter :require_no_authentication wasn't being called, but assumed that because the EditorsController was inheriting from RegistrationController that before filter would work properly. Is that not the case?

答:
Using Rails 4.2.6 here (my model is User instead of Editor).  The following solution bypasses (I think) any devise actions that may interfere with new User creation by the admin:

Add this action to the Users controller:

```<code>def savenew
  User.create_new_user(user_params)
  redirect_to action: 'index'
end
</code>```

Add this private method to the Users controller if it does not exist:

```<code>private

def user_params
  params.require(:user).permit(:email, :password,
                               :password_confirmation)
end
</code>```

Add this to config/routes.rb:

```<code>match '/savenew', to: 'users#savenew', via: :post
</code>```

Add this class method to the User model:

```<code>def self.create_new_user(params)
  @user = User.create!(params)
end
</code>```

I don't have a separate Admin class in my application.  Instead, I defined an admin attribute for Users and check for it with a :validate_admin before_action filter in the UsersController.

I wanted to be able to create a new user from the :index view, so I added a button:

```<code><%= button_to 'New User', '/new_user', class: 'btn btn-primary',
                          method: :get %>
</code>```

You might have to tweak the above solution if you have any after_create actions in the User model (e.g. sending a welcome email).

Body:
I'm trying to make it so only admins can add uses with devise. I've gotten it mostly working however now when I'm logged in as an admin and submit the sign up form it kicks me back with the error: You are already signed in.

I've tried to follow the instructions here: http://wiki.summercode.com/rails_authentication_with_devise_and_cancan but it doesn't seem to mention this situation.

Do I need to do further overriding in the editors_controller to allow this?

Here are my routes ("editors" is the name of my user model):

devise_for :admins, :skip => [:registrations]

as :admin do
  get 'admin/editors'        => 'editors#index',                  as: :admin_editors
  get 'admin/editors/new'    => 'editors#new',                    as: :new_editor
  delete 'admin/editors/:id' => 'editors#destroy',                as: :destroy_editor
end

devise_for :editors, :skip => [:registrations],  :controllers => { :registrations => "editors" }

and my editors_controller in "app/controllers/"

    class EditorsController < Devise::RegistrationsController
  before_filter :check_permissions, :only => [:new, :create, :cancel]
  skip_before_filter :require_no_authentication

  def dashboard
    render "editors/dashboard.html.haml"
  end

  def index
    @editors = Editor.all
    respond_to do |format|
      format.html
    end
  end

  private
    def check_permissions
      authorize! :create, resource
    end
end

EDIT
I noticed this Processing by Devise::RegistrationsController#create as HTML in the logs when I submit the form. I had suspected that perhaps the skip_before_filter :require_no_authentication wasn't being called, but assumed that because the EditorsController was inheriting from RegistrationController that before filter would work properly. Is that not the case?

Body:
Using Rails 4.2.6 here (my model is User instead of Editor).  The following solution bypasses (I think) any devise actions that may interfere with new User creation by the admin:

Add this action to the Users controller:

def savenew
  User.create_new_user(user_params)
  redirect_to action: 'index'
end

Add this private method to the Users controller if it does not exist:

private

def user_params
  params.require(:user).permit(:email, :password,
                               :password_confirmation)
end

Add this to config/routes.rb:

match '/savenew', to: 'users#savenew', via: :post

Add this class method to the User model:

def self.create_new_user(params)
  @user = User.create!(params)
end

I don't have a separate Admin class in my application.  Instead, I defined an admin attribute for Users and check for it with a :validate_admin before_action filter in the UsersController.

I wanted to be able to create a new user from the :index view, so I added a button:

<%= button_to 'New User', '/new_user', class: 'btn btn-primary',
                          method: :get %>

You might have to tweak the above solution if you have any after_create actions in the User model (e.g. sending a welcome email).


问:
Angular 2-4 observable that comes from a click event
I have a function that returns an Observable when a row in a table is clicked.

```<code>private onEnrollmentHistory(val: Enrollment[]) {
        this.enrollments = val;
        console.log(this.enrollments);
    }

    getEnrollmentHistoryById(id: number) {
        this.toggleMoreInfoDialog();
        return this.store.getEnrollmentHistoryById(id)
            .subscribe(
                this.onEnrollmentHistory
            );
    }
</code>```

I'm not sure how to get this info into the component HTML.
I can't do
 because the ID isn't known until someone clicks on it.  Is there some syntax I'm missing to have some text in a div bound to this Observable?  something like

?

the function is called from a table row

```<code><td>
 (click)="getEnrollmentHistoryById(id)" class="fa fa-2x fa-info">
</td>

 <div class="container">
      <div class="row">
         here are enrollments
          <div *ngFor="let e of enrollments">
                {{e}}
            </div>
       </div>
 </div>
</code>```

This is meant to be read only, I just need grab something from the DB with the observable, and show it on the page on a click event.

答:
My solution was to add a variable to the component
enrollmentHistory = new Observable<Enrollment[]>(null);
and on the click event do

enrollmentHistory = this.getEnrollmentHistoryById(id)
and in the view

 and this gave me what i needed.

Body:
I have a function that returns an Observable when a row in a table is clicked.

private onEnrollmentHistory(val: Enrollment[]) {
        this.enrollments = val;
        console.log(this.enrollments);
    }

    getEnrollmentHistoryById(id: number) {
        this.toggleMoreInfoDialog();
        return this.store.getEnrollmentHistoryById(id)
            .subscribe(
                this.onEnrollmentHistory
            );
    }

I'm not sure how to get this info into the component HTML.
I can't do
 because the ID isn't known until someone clicks on it.  Is there some syntax I'm missing to have some text in a div bound to this Observable?  something like

?

the function is called from a table row

 (click)="getEnrollmentHistoryById(id)" class="fa fa-2x fa-info">

         here are enrollments

                {{e}}

This is meant to be read only, I just need grab something from the DB with the observable, and show it on the page on a click event.

Body:
My solution was to add a variable to the component
enrollmentHistory = new Observable<Enrollment[]>(null);
and on the click event do

enrollmentHistory = this.getEnrollmentHistoryById(id)
and in the view
<div *ngFor="let e of enrollmentHistory | async"> and this gave me what i needed.


问:
Parse a file 2 lines at a time
Python beginner here. I have a file that looks like that (every field is \t separated):

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)
</code>```

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

```<code>with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"
</code>```

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

```<code>with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))
</code>```

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

答:
You can make two array and store there the current line and the before line:

```<code>list = []
list_before =[]
with open ('file.txt', 'r') as mutmut_mutants:
 list.append(mutmut_mutants.readline().split())
 print(list)
</code>```

Then compare if the current and the before list have in the same position the word SYNNONYMOUS.

```<code>print(list[0][0][:3]) = "cnr"
print(list[0][0][-4:]) = "_SNP"
</code>```

hope if it helps

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
You can make two array and store there the current line and the before line:

list = []
list_before =[]
with open ('file.txt', 'r') as mutmut_mutants:
 list.append(mutmut_mutants.readline().split())
 print(list)

Then compare if the current and the before list have in the same position the word SYNNONYMOUS.

print(list[0][0][:3]) = "cnr"
print(list[0][0][-4:]) = "_SNP"

hope if it helps


问:
Sandboxes and Wordpress, Joomla or Drupal Sites?
I'm looking into building database driven websites based on opensource platforms in a sandbox area rather than having them accessible via the final URL until clients have paid up.

Is anyone aware of any problems this may cause with paths or functionality, or, know of any good articles on the subject?

many thanks
Shaun

答: I develop all joomla sites on a local server and then upload to the production server once approved. In Joomla, when I upload the files to the production server, I usually need to change the mysql server as well and it can all be changed from the configuration.php file</p>


问:
Find all dependencies that include a given package
I excluded an artifact because it causes conflicts, namely the jsr311-api given below. Yet when I run the generated jar I'm still getting the java.lang.NoSuchMethodError error. I suspect that another dependency is also including this artifact. How can I find out which one? My dependency list is quite large. Which dependencies include the package javax.ws.rs.core?

```<code>    <dependency>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-kernel</artifactId>
        <version>1.7.3</version>
        <exclusions>
            <!-- Causes java.lang.NoSuchMethodError: javax.ws.rs.core.Response$Status$Family.familyOf(I)Ljavax/ws/rs/core/Response$Status$Family; -->
            <exclusion>
                <artifactId>jsr311-api</artifactId>
                <groupId>javax.ws.rs</groupId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

答:
Go to

http://search.maven.org/#advancedsearch%7Cgav

and use classname search to find

javax.ws.rs.core.Response

If you use a Nexus 2.x in your company, you can use classname search there as well.

If you want to find out where a given artifact (that you e.g. found by classnmae search) comes from, use dependency:tree in Maven.

Body:
I excluded an artifact because it causes conflicts, namely the jsr311-api given below. Yet when I run the generated jar I'm still getting the java.lang.NoSuchMethodError error. I suspect that another dependency is also including this artifact. How can I find out which one? My dependency list is quite large. Which dependencies include the package javax.ws.rs.core?

    <dependency>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-kernel</artifactId>
        <version>1.7.3</version>
        <exclusions>

            <exclusion>
                <artifactId>jsr311-api</artifactId>
                <groupId>javax.ws.rs</groupId>
            </exclusion>
        </exclusions>
    </dependency>


问:
RxJava: Only emit if the first item for a given period
I want to transform my source Flowable in such a way that events only go though if they are the first item within a specified period.

That is, I want the first item to go through and then drop all subsequent items until there was a period of, say, 10 seconds, in which no upstream event arrived.

Note that is this neither

debounce: This would emit each item iff it was not followed by another one for 10 seconds - but this will force a 10 second delay on even the first item. I want to emit the first item right away.

throttleFirst: This would emit the first item and then drop all subsequent items for 10 seconds after that first one. I want to have the blocking period reset after each upstream item.

I've now solved it like this:

```<code>source
  .flatMap { Flowable.just(1).concatWith(Flowable.just(-1).delay(10, TimeUnit.SECONDS)) }
  .scan(0, { x, y -> x + y })
  .map { it > 0 }
  .distinctUntilChanged()
  .filter { it }
</code>```

NOTE: I don't care about the actual items in source, only that they occur - but, of course, I could just wrap the items in a Pair along with 1 or -1).

Is there a simpler way to use built-in RxJava(2) Operators to achieve the same goal?

答:
It is possible by using the fact that switchMap only subscribes to one Flowable at once and using a boolean to check if it has to emit:

```<code>class ReduceThrottle<T>(val period: Long, val unit: TimeUnit) : FlowableTransformer<T, T> {
    override fun apply(upstream: Flowable<T>): Publisher<T> {
        return Flowable.defer {
            val doEmit = AtomicBoolean(true)

            upstream.switchMap { item ->
                val ret = if (doEmit.compareAndSet(true, false)) {
                    // We haven't emitted in the last 10 seconds, do the emission
                    Flowable.just(item)
                } else {
                    Flowable.empty()
                }

                ret.concatWith(Completable.timer(period, unit).andThen(Completable.fromAction {
                    // Once the timer successfully expires, reset the state
                    doEmit.set(true)
                }).toFlowable())
            }
        }
    }
}
</code>```

Then it is simply a matter of applying the transformer: source.compose(ReduceThrottle(10, TimeUnit.SECONDS)).

Body:
I want to transform my source Flowable in such a way that events only go though if they are the first item within a specified period.

That is, I want the first item to go through and then drop all subsequent items until there was a period of, say, 10 seconds, in which no upstream event arrived.

Note that is this neither

debounce: This would emit each item iff it was not followed by another one for 10 seconds - but this will force a 10 second delay on even the first item. I want to emit the first item right away.

throttleFirst: This would emit the first item and then drop all subsequent items for 10 seconds after that first one. I want to have the blocking period reset after each upstream item.

I've now solved it like this:

source
  .flatMap { Flowable.just(1).concatWith(Flowable.just(-1).delay(10, TimeUnit.SECONDS)) }
  .scan(0, { x, y -> x + y })
  .map { it > 0 }
  .distinctUntilChanged()
  .filter { it }

NOTE: I don't care about the actual items in source, only that they occur - but, of course, I could just wrap the items in a Pair along with 1 or -1).

Is there a simpler way to use built-in RxJava(2) Operators to achieve the same goal?

Body:
It is possible by using the fact that switchMap only subscribes to one Flowable at once and using a boolean to check if it has to emit:

class ReduceThrottle<T>(val period: Long, val unit: TimeUnit) : FlowableTransformer<T, T> {
    override fun apply(upstream: Flowable<T>): Publisher<T> {
        return Flowable.defer {
            val doEmit = AtomicBoolean(true)

            upstream.switchMap { item ->
                val ret = if (doEmit.compareAndSet(true, false)) {
                    // We haven't emitted in the last 10 seconds, do the emission
                    Flowable.just(item)
                } else {
                    Flowable.empty()
                }

                ret.concatWith(Completable.timer(period, unit).andThen(Completable.fromAction {
                    // Once the timer successfully expires, reset the state
                    doEmit.set(true)
                }).toFlowable())
            }
        }
    }
}

Then it is simply a matter of applying the transformer: source.compose(ReduceThrottle(10, TimeUnit.SECONDS)).


问:
PHP get XML rootNode content as String
How can i get the content of an XML as string?
I have a xml like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
</code>```

and i want the content of section as a string like this:

```<code>  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</code>```

every doc i read so far only explains how to get  the content of a subnode but not of the root node.

答:
It can be achieved using DOMDocument (Press here  to See it in action)</p>

```<code>$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
';

$xml = new DOMDocument();
$xml->loadXML($xmlStr);
if($xml->childNodes->length > 0) {
  foreach($xml->childNodes->item(0)->childNodes as $rootChildNode){
      echo $xml->saveXML($rootChildNode);
    }
}
</code>```

Title: PHP get XML rootNode content as String

Body:
How can i get the content of an XML as string?
I have a xml like this:

<?xml version="1.0" encoding="utf-8"?>

  <paragraph>some content</paragraph>
  <custom>some more content</custom>

and i want the content of section as a string like this:

  <paragraph>some content</paragraph>
  <custom>some more content</custom>

every doc i read so far only explains how to get  the content of a subnode but not of the root node.

Body:
It can be achieved using DOMDocument (Press here  to See it in action)

$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
';

$xml = new DOMDocument();
$xml->loadXML($xmlStr);
if($xml->childNodes->length > 0) {
  foreach($xml->childNodes->item(0)->childNodes as $rootChildNode){
      echo $xml->saveXML($rootChildNode);
    }
}


问:
Sending multiple files to a servlet with a single connection
I'm writing a Java desktop  client which will send multiple files over the wire to a servlet using a post request. In the servlet I'm getting the input stream from the request to receive the files. The servlet will write the files to disk, one by one as they're read from the stream.

The implementation has a couple of requirements:

Only one HTTP request must be used to the server (so only a single stream)

The servlet must use a reasonable fixed amount of memory, no matter what the size of the files.

I had considered inserting markers into the stream so I know when one file ends and the next one begins. I'd then write some code to parse the stream in the servlet, and start writing the next file as appropriate.

Here's the thing... surely there's a library to do that. I've looked through apache commons and found nothing. Commons File Upload is interesting but since the upload comes from a Java app, not a browser it only solves the receiving end, not the sending.

Any ideas for a library which easily allows multiple file transfers across a single stream with fixed memory expectations even for very large files?

Thanks.

答:
Just use HTTP multipart/form-data encoding on the POST request body. It's described in RFC-2388 and a standard way of uploading (multiple) files by HTTP.

You can do it with just java.net.URLConnection as described in this mini-tutorial, although it would generate lot of boilerplate code. A more convenienced approach would be using Apache Commons HttpClient.

In the servlet side you can then just use Apache Commons Fileupload to process the uploaded files the usual HTTP way (or when you're already on Servlet 3.0, the HttpServletRequest#getParts(), see also this answer for examples).


问:
How to enable CustomerOrderNbr field in Sales Order screen?
In Sales Order screen, I'm trying to enable the CustomerOrderNbr field if the status is completed

```<code>protected void SOOrder_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{

  SOOrder doc = e.Row as SOOrder;
  if (doc == null)
  {
    return;
  }

  if (doc.Completed == true )
    {
      PXUIFieldAttribute.SetEnabled(cache, doc , true);
      PXUIFieldAttribute.SetEnabled<SOOrder.customerOrderNbr>(cache, doc, true);
    }

}
</code>```

however, it remains disabled and not doing what it's supposed to do. So what am I doing wrong ? Am I on the right event to override at all ?

Or is the screen really locked in once the Sales Order is Completed ?

Thanks for any answers.

答:
Since Sales Orders screen is heavily driven by Automation Steps, in addition to extended RowSelected handler for the SOOrder DAC, it's an absolute must to modify automation steps for Completed orders that disable entire SOOrder :

In addition to the automation step change shown above, you should keep SOOrder_RowSelected handler:

```<code>public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
    public void SOOrder_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
    {
        SOOrder order = e.Row as SOOrder;
        if (order == null) return;

        if (order.Completed == true)
        {
            PXUIFieldAttribute.SetEnabled<SOOrder.customerOrderNbr>(sender, order, true);
        }
    }
}
</code>```

With those 2 changes in place, Customer Order will stay enabled for SO Orders with Completed status:

Body:
In Sales Order screen, I'm trying to enable the CustomerOrderNbr field if the status is completed

protected void SOOrder_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{

  SOOrder doc = e.Row as SOOrder;
  if (doc == null)
  {
    return;
  }

  if (doc.Completed == true )
    {
      PXUIFieldAttribute.SetEnabled(cache, doc , true);
      PXUIFieldAttribute.SetEnabled<SOOrder.customerOrderNbr>(cache, doc, true);
    }

}

however, it remains disabled and not doing what it's supposed to do. So what am I doing wrong ? Am I on the right event to override at all ?

Or is the screen really locked in once the Sales Order is Completed ?

Thanks for any answers.

Body:
Since Sales Orders screen is heavily driven by Automation Steps, in addition to extended RowSelected handler for the SOOrder DAC, it's an absolute must to modify automation steps for Completed orders that disable entire SOOrder :

In addition to the automation step change shown above, you should keep SOOrder_RowSelected handler:

public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
    public void SOOrder_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
    {
        SOOrder order = e.Row as SOOrder;
        if (order == null) return;

        if (order.Completed == true)
        {
            PXUIFieldAttribute.SetEnabled<SOOrder.customerOrderNbr>(sender, order, true);
        }
    }
}

With those 2 changes in place, Customer Order will stay enabled for SO Orders with Completed status:


问:
Getting Compile time error "AssociatedObject" not found
I implemented Popup control in Wpf.
I want to make popup drag able and found some code written below.
But I am getting compile time error "AssociatedObject" not found, Behavior Not Found.
Here is my code:</p>

```<code>class class MouseDragPopupBehavior : Behavior<Popup>
{
    private bool mouseDown;
    private Point oldMousePosition;

    protected override void OnAttached()
    {
        AssociatedObject.MouseLeftButtonDown += (s, e) =>
        {
            mouseDown = true;
            oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
            AssociatedObject.Child.CaptureMouse();
        };
        AssociatedObject.MouseMove += (s, e) =>
        {
            if (!mouseDown) return;
            var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
            var offset = newMousePosition - oldMousePosition;
            oldMousePosition = newMousePosition;
            AssociatedObject.HorizontalOffset += offset.X;
            AssociatedObject.VerticalOffset += offset.Y;
        };
        AssociatedObject.MouseLeftButtonUp += (s, e) =>
        {
            mouseDown = false;
            AssociatedObject.Child.ReleaseMouseCapture();
        };
    }
}
</code>```

答:
You're missing a reference to System.Windows.Interactivity

Put using System.Windows.Interactivity; at the top of your class. You also need to add this as a reference in your project.

Also, you'll need to fix your class declaration, currently it is:

class class ...

It should be

public class ...

Body:
I implemented Popup control in Wpf.
I want to make popup drag able and found some code written below.
But I am getting compile time error "AssociatedObject" not found, Behavior Not Found.
Here is my code:

class class MouseDragPopupBehavior : Behavior<Popup>
{
    private bool mouseDown;
    private Point oldMousePosition;

    protected override void OnAttached()
    {
        AssociatedObject.MouseLeftButtonDown += (s, e) =>
        {
            mouseDown = true;
            oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
            AssociatedObject.Child.CaptureMouse();
        };
        AssociatedObject.MouseMove += (s, e) =>
        {
            if (!mouseDown) return;
            var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
            var offset = newMousePosition - oldMousePosition;
            oldMousePosition = newMousePosition;
            AssociatedObject.HorizontalOffset += offset.X;
            AssociatedObject.VerticalOffset += offset.Y;
        };
        AssociatedObject.MouseLeftButtonUp += (s, e) =>
        {
            mouseDown = false;
            AssociatedObject.Child.ReleaseMouseCapture();
        };
    }
}