问:
java.lang.ClassNotFoundException: com.android.packageinstaller.InstallFlowAnalytics
I have recently started using Android Studio instead of using Eclipse.
I used Android Studio to import and migrate the Eclipse project into Android Studio. If i build the project with AS and download it to a device it works fine.

The problem is if a device already has the previous version of the app installed on it (which was build by Eclipse), it will not install or even open up. I get the following Exception.

```<code>Class not found when unmarshalling: com.android.packageinstaller.InstallFlowAnalytics
                                         java.lang.ClassNotFoundException: com.android.packageinstaller.InstallFlowAnalytics
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.Class.forName(Class.java:324)
                                             at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
                                             at android.os.Parcel.readParcelable(Parcel.java:2358)
                                             at android.os.Parcel.readValue(Parcel.java:2264)
                                             at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
                                             at android.os.BaseBundle.unparcel(BaseBundle.java:221)
                                             at android.os.BaseBundle.getString(BaseBundle.java:920)
                                             at android.content.Intent.getStringExtra(Intent.java:6195)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2699)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2161)
                                             at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6318)
                                             at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6096)
                                             at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
                                             at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3986)
                                             at android.os.Binder.execTransact(Binder.java:453)
                                          Caused by: java.lang.ClassNotFoundException: com.android.packageinstaller.InstallFlowAnalytics
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                             at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                             at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.Class.forName(Class.java:324)
                                             at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
                                             at android.os.Parcel.readParcelable(Parcel.java:2358)
                                             at android.os.Parcel.readValue(Parcel.java:2264)
                                             at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
                                             at android.os.BaseBundle.unparcel(BaseBundle.java:221)
                                             at android.os.BaseBundle.getString(BaseBundle.java:920)
                                             at android.content.Intent.getStringExtra(Intent.java:6195)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2699)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2161)
                                             at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6318)
                                             at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6096)
                                             at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
                                             at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3986)
                                             at android.os.Binder.execTransact(Binder.java:453)
                                          Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
</code>```

.

The above exception seemed to happen after i updated Android Studio build and gradle. Everything worked ok until then.

The Eclipse set up was:
Android SDK Build-Tools 23.0.3

project target = Google Inc.:Google APIs:22

The Current Android Studio is:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion "24.0.3"

    useLibrary 'org.apache.http.legacy'

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }

    defaultConfig {
        applicationId "com.xxxxxxxxxx"
        minSdkVersion 11
        targetSdkVersion 21
        versionName "4.0.1"
        setProperty("archivesBaseName", "RR3v$versionName")
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:+'
    compile 'joda-time:joda-time:2.1'
    compile files('libs/activation.jar')
    compile files('libs/additionnal.jar')
    compile files('libs/core.jar')
    compile files('libs/ftp4j-1.7.2.jar')
    compile files('libs/mail.jar')
    compile files('libs/ndeftools-1.2.3.jar')
    compile files('libs/sqlcipher.jar')
    compile files('libs/gcm.jar')
}
</code>```

.

Does anyone know why the update will not install?
My apk update will not even open via the package installer.

Thanks in advance

答:
The problem could be that a version downgrade is attempted (which is not allowed). It seems that your Eclipse project set the version code differently than AndroidStudio does now.

Set the versionCode manually to the same or a higher number than your Eclipse build (you can check the old code in the AndroidManifest) by adding this to your build.gradle:

```<code>android {
    defaultConfig {
        versionCode 1234
    ...
    }
}
</code>```

Apart from that, you can always install with the "allow downgrade" flag using adb:

```<code>adb install -r -d myApk.apk
</code>```

-r allows to install an already existing app

-d allows a version downgrade

Body:
I have recently started using Android Studio instead of using Eclipse.
I used Android Studio to import and migrate the Eclipse project into Android Studio. If i build the project with AS and download it to a device it works fine.

The problem is if a device already has the previous version of the app installed on it (which was build by Eclipse), it will not install or even open up. I get the following Exception.

Class not found when unmarshalling: com.android.packageinstaller.InstallFlowAnalytics
                                         java.lang.ClassNotFoundException: com.android.packageinstaller.InstallFlowAnalytics
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.Class.forName(Class.java:324)
                                             at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
                                             at android.os.Parcel.readParcelable(Parcel.java:2358)
                                             at android.os.Parcel.readValue(Parcel.java:2264)
                                             at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
                                             at android.os.BaseBundle.unparcel(BaseBundle.java:221)
                                             at android.os.BaseBundle.getString(BaseBundle.java:920)
                                             at android.content.Intent.getStringExtra(Intent.java:6195)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2699)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2161)
                                             at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6318)
                                             at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6096)
                                             at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
                                             at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3986)
                                             at android.os.Binder.execTransact(Binder.java:453)
                                          Caused by: java.lang.ClassNotFoundException: com.android.packageinstaller.InstallFlowAnalytics
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                             at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                             at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                             at java.lang.Class.classForName(Native Method)
                                             at java.lang.Class.forName(Class.java:324)
                                             at android.os.Parcel.readParcelableCreator(Parcel.java:2404)
                                             at android.os.Parcel.readParcelable(Parcel.java:2358)
                                             at android.os.Parcel.readValue(Parcel.java:2264)
                                             at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
                                             at android.os.BaseBundle.unparcel(BaseBundle.java:221)
                                             at android.os.BaseBundle.getString(BaseBundle.java:920)
                                             at android.content.Intent.getStringExtra(Intent.java:6195)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:2699)
                                             at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:2161)
                                             at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:6318)
                                             at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:6096)
                                             at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:170)
                                             at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3986)
                                             at android.os.Binder.execTransact(Binder.java:453)
                                          Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

.

The above exception seemed to happen after i updated Android Studio build and gradle. Everything worked ok until then.

The Eclipse set up was:
Android SDK Build-Tools 23.0.3

project target = Google Inc.:Google APIs:22

The Current Android Studio is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion "24.0.3"

    useLibrary 'org.apache.http.legacy'

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }

    defaultConfig {
        applicationId "com.xxxxxxxxxx"
        minSdkVersion 11
        targetSdkVersion 21
        versionName "4.0.1"
        setProperty("archivesBaseName", "RR3v$versionName")
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:+'
    compile 'joda-time:joda-time:2.1'
    compile files('libs/activation.jar')
    compile files('libs/additionnal.jar')
    compile files('libs/core.jar')
    compile files('libs/ftp4j-1.7.2.jar')
    compile files('libs/mail.jar')
    compile files('libs/ndeftools-1.2.3.jar')
    compile files('libs/sqlcipher.jar')
    compile files('libs/gcm.jar')
}

.

Does anyone know why the update will not install?
My apk update will not even open via the package installer.

Thanks in advance

Body:
The problem could be that a version downgrade is attempted (which is not allowed). It seems that your Eclipse project set the version code differently than AndroidStudio does now.

Set the versionCode manually to the same or a higher number than your Eclipse build (you can check the old code in the AndroidManifest) by adding this to your build.gradle:

android {
    defaultConfig {
        versionCode 1234
    ...
    }
}

Apart from that, you can always install with the "allow downgrade" flag using adb:

adb install -r -d myApk.apk

-r allows to install an already existing app

-d allows a version downgrade


来源: stackexchange

问:
Regex that allows 3-20 digits and must end with 00
I have a regex ".*00$" which restricts that the input must be ending with 00. How can I improve this to add a max length of 20 also. So:

100 => valid,

00 = > invalid,

12345678900 => valid,

111111111111111111100 = > 21 digits - invalid.

答:
Based on your title and short description this should probably work for you:

```<code>^[0-9]{1,18}00$
</code>```

This will allow 3-20 digits in input that ends with 00

ContentLicense: CC BY-SA 3.0

Body:
Based on your title and short description this should probably work for you:

^[0-9]{1,18}00$

This will allow 3-20 digits in input that ends with 00


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
Let me suggest something really out of the zone here: build an ISAPI dll (or the Apache equivalent if that is your preference) from bare-metal C/C++ or even Delphi.  Why? If you have the time to do this you will learn an IMMENSE amount about the underlying architecture of web applications and it will open up an entirely new perspective on all of the frameworks that everyone is suggesting here.

I did this in Delphi back in 2000 and it was a tremendous learning experience.  Of course, this is predicated on the notion that you don't need to build anything quickly and that the primary purpose of the project is to learn about web development.  But, if that is your objective, you'd be hard-pressed to find a better approach.

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: Mark Brittingham


问:
Send MIDI events to a stand-alone sampler/synth
I'd like to develop a very simple program to map PC keyboard to a piano keyboard: each time the user press a key a MIDI event is generated and a stand-alone sampler/synth (such as SFZ+ or other) receives these events and plays a sound.

I am able to generate MIDI events (using midiOutShortMsg), but they are sent directly to the FM synth (and so played by it), I'd like to send them to an external software. The code must be in C/C++.

Could you help me?

Tnx.

答:
You must have used "midiOutOpen" to open the device.
What if you select another device id ?</p>


问:
If TRUE in one column, change value in other column
I have a character vector: (shortened version shown)

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
</code>```

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

```<code>"10e10" "10e11" "10e10" "10e11"
</code>```

I used startsWith() to create a TRUE/FALSE vector:

```<code>startsWith.e <- startsWith(Unit, "e")
</code>```

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

```<code>while(startsWith.e){
grep("e", "10e", Unit) }
</code>```

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

答:
Using startsWith and subsetting, you could do

```<code>Unit[startsWith(Unit, "e")] <- paste0("10", Unit[startsWith(Unit, "e")])
</code>```

which returns

```<code>Unit
[1] "10e10" "10e11" "10e10" "10e11"
</code>```

Body:
I have a character vector: (shortened version shown)

Unit <- c("e10", "e11", "10e10", "10e11")

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

"10e10" "10e11" "10e10" "10e11"

I used startsWith() to create a TRUE/FALSE vector:

startsWith.e <- startsWith(Unit, "e")

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

while(startsWith.e){
grep("e", "10e", Unit) }

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

Body:
Using startsWith and subsetting, you could do

Unit[startsWith(Unit, "e")] <- paste0("10", Unit[startsWith(Unit, "e")])

which returns

Unit
[1] "10e10" "10e11" "10e10" "10e11"


问:
How to default select2 in angularJS
Instead using ui-select, I'm using jQuery select2 in AngularJS. I created custom directive for select2, for ng-model. I get the value from ng-model. But when I update the select2 on default, it doesn't work. I'm using select2 v4.0.3.

Directive

```<code>App.directive('jsSelect2', function ($timeout) {
    return {
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function(){
                $timeout(function(){
                    element.trigger('change.select2');
                },100);
            });

        }
    };
});
</code>```

HTML

```<code><select id="update_created_by" data-js-select2="" name="update_created_by"
   data-placeholder="To Who" ng-model="anc.update_created_by"
   ng-options="c.name for c in anc_staffs"
   required="required" class="form-control">
</select>
</code>```

Controller

```<code>$scope.anc_staffs = [{id:1, name:'abel'},{id:2, name:'john'}];
jQuery("#update_created_by").val(1); // Doesn't work, show empty
jQuery("#update_created_by").val(1).trigger('change.select2'); // Doesn't work, show empty
</code>```

答:
The problem of model being out of sync is a typical problem that ours when 2 different  libraries don't  sync. jQuery select2 will need to trigger certain angular calls in order to ensure model values are committed. Since that is beyond the control of a user of a library we run into this sort of known problems among others. Unless you have select2.

When using AngularJS it is a best practice to use components natively written in AngularJS. Hence libraries like angular-ui, ui-select exists.

I am saying there is no clean way to solve this problem.

Try

var $element = $('select').select2();
// Use the following inside your $timeout
$element.trigger('change');

Title: How to default select2 in angularJS

Body:
Instead using ui-select, I'm using jQuery select2 in AngularJS. I created custom directive for select2, for ng-model. I get the value from ng-model. But when I update the select2 on default, it doesn't work. I'm using select2 v4.0.3.

Directive

App.directive('jsSelect2', function ($timeout) {
    return {
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function(){
                $timeout(function(){
                    element.trigger('change.select2');
                },100);
            });

        }
    };
});

HTML

<select id="update_created_by" data-js-select2="" name="update_created_by"
   data-placeholder="To Who" ng-model="anc.update_created_by"
   ng-options="c.name for c in anc_staffs"
   required="required" class="form-control">
</select>

Controller

$scope.anc_staffs = [{id:1, name:'abel'},{id:2, name:'john'}];
jQuery("#update_created_by").val(1); // Doesn't work, show empty
jQuery("#update_created_by").val(1).trigger('change.select2'); // Doesn't work, show empty


问:
Cancel imageLoader tasks on searching
My project has a search view with custom adapter,
adapter ViewHolder contain ImageView

I use 2 tasks: 1- search task 2- image load task

so when I start search task, on Post Execute I set data adapter and notif it
then image loader is execute as much as the number of results!

When I rerun the search task,I Should wait until the tasks of the image loader are finished

Finally how can I cancel ImageLoader tasks before rerun SearchTask??

adapter:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) activityReference.get().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_row1, parent, false);
        viewHolder.title = (TextView) convertView.findViewById(R.id.row_title);
        viewHolder.artist = (TextView) convertView.findViewById(R.id.row_artist);
        viewHolder.cover = (FadeInNetworkImageView) convertView.findViewById(R.id.cover);
        convertView.setTag(viewHolder);
    } else
        viewHolder = (ViewHolder) convertView.getTag();

    viewHolder.title.setText(songs[position].getArtist());
    viewHolder.artist.setText(songs[position].getTitle());

    new ImageLoader().execute(songs[position], this, this, viewHolder, Online.isConnectedWifi(context));

    return convertView;
}
</code>```

答:
In order to be able to cancel all the ImageLoaders in one swoop, you are going to have to keep reference to them in your adapter and, in your adapter, declare a public method that shall cancel them all:

```<code>public class MhadisAdapter extends SomeKindOfAdapter {
    private List<ImageLoader> imageLoaderTasks = new ArrayList<>();

    public void cancelImageLoaders() {
        for(ImageLoader task: imageLoaderTasks) {
            task.cancel(true);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
        ...
        ImageLoader imageLoader = new ImageLoader();
        imageLoaderTasks.add(imageLoader);
        imageLoader.execute(songs[position], this, this, viewHolder, Online.isConnectedWifi(context));

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

Now you can cancel all the image loaders before searching by calling cancelImageLoaders()

Title: Cancel imageLoader tasks on searching

Body:
My project has a search view with custom adapter,
adapter ViewHolder contain ImageView

I use 2 tasks: 1- search task 2- image load task

so when I start search task, on Post Execute I set data adapter and notif it
then image loader is execute as much as the number of results!

When I rerun the search task,I Should wait until the tasks of the image loader are finished

Finally how can I cancel ImageLoader tasks before rerun SearchTask??

adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) activityReference.get().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_row1, parent, false);
        viewHolder.title = (TextView) convertView.findViewById(R.id.row_title);
        viewHolder.artist = (TextView) convertView.findViewById(R.id.row_artist);
        viewHolder.cover = (FadeInNetworkImageView) convertView.findViewById(R.id.cover);
        convertView.setTag(viewHolder);
    } else
        viewHolder = (ViewHolder) convertView.getTag();

    viewHolder.title.setText(songs[position].getArtist());
    viewHolder.artist.setText(songs[position].getTitle());

    new ImageLoader().execute(songs[position], this, this, viewHolder, Online.isConnectedWifi(context));

    return convertView;
}

Body:
In order to be able to cancel all the ImageLoaders in one swoop, you are going to have to keep reference to them in your adapter and, in your adapter, declare a public method that shall cancel them all:

public class MhadisAdapter extends SomeKindOfAdapter {
    private List<ImageLoader> imageLoaderTasks = new ArrayList<>();

    public void cancelImageLoaders() {
        for(ImageLoader task: imageLoaderTasks) {
            task.cancel(true);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
        ...
        ImageLoader imageLoader = new ImageLoader();
        imageLoaderTasks.add(imageLoader);
        imageLoader.execute(songs[position], this, this, viewHolder, Online.isConnectedWifi(context));

        return convertView;
    }
}

Now you can cancel all the image loaders before searching by calling cancelImageLoaders()


问:
What is the difference between session resumption in TLS v1.1vs TLS v1.2?
Scenario: We are planning to implement Session resumption to reduce data usage to handle multiple reconnect issue.

Our Azure system is using tls v1.1 , I just checked Session resumption is available in tls v1.1. All these days I was in an assumption it is only available in tls v1.2.

Question:
Can someone tell me should I really want to upgrade towards tls v1.2 or I can stay with tls v1.1 itself to achieve the same ?

Reference: https://www.rfc-editor.org/rfc/rfc4346#appendix-F.1.4

Any suggestion guys ?

答:
There is no easy answer to this. There are several factors that have to be taken into account:

Do all of your client stacks support TLS 1.2?

Is the application functionality tested with TLS 1.2?

If answer to the above is yes, then you could enforce TLS 1.2. However, there might be other scenarios, that I might have taken into account. So you will have to do a run through of the scenarios that can possible exist.


问:
Domain Account keeping locking out with correct password every few minutes
I have user whos account is keeping locking out every 30 minutes. Done all the checks, remove any cache passwords, created new profile, delete password from IE.

It locks out even when user is using his account (he is logged in )

After checking 20 servers I found that they is service running which causing his account to lock I think.

```<code>675,AUDIT FAILURE,Security,Thu Dec 16 07:54:04 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  userid     User ID:  %{id}     Service Name:  krbtgt/DOMAIN     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  IP address
</code>```

Does anyone know what is this.

```<code>krbtgt/DOMAIN
Key Distribution Center Service Account
</code>```

Can some please explain this to me why this is happening and how i can fix this.

```<code>675,AUDIT FAILURE,Security,Fri Dec 24 09:13:01 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  172.16.5.1
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  172.16.5.102
644,AUDIT SUCCESS,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,User Account Locked Out:     Target Account Name: user_id    Target Account ID: %{id}     Caller Machine Name: UKNML3266     Caller User Name: LONDON$     Caller Domain: Domain     Caller Logon ID: (0x0,0x3E7)
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.102
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.102
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
c:\sc0472\LONDON-Security_LOG.txt contains 8 parsed events.
</code>```

答: I have seen this problem when the user had set up a scheduled task to run under his account.  He forgot to update the password on the task after he changed his account password.  The scheduled task was trying to logon with the old password and kept locking out his account.</p>

Body:
I have user whos account is keeping locking out every 30 minutes. Done all the checks, remove any cache passwords, created new profile, delete password from IE.

It locks out even when user is using his account (he is logged in )

After checking 20 servers I found that they is service running which causing his account to lock I think.

675,AUDIT FAILURE,Security,Thu Dec 16 07:54:04 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  userid     User ID:  %{id}     Service Name:  krbtgt/DOMAIN     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  IP address

Does anyone know what is this.

krbtgt/DOMAIN
Key Distribution Center Service Account

Can some please explain this to me why this is happening and how i can fix this.

675,AUDIT FAILURE,Security,Fri Dec 24 09:13:01 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  172.16.5.1
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x12     Client Address:  172.16.5.102
644,AUDIT SUCCESS,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,User Account Locked Out:     Target Account Name: user_id    Target Account ID: %{id}     Caller Machine Name: UKNML3266     Caller User Name: LONDON$     Caller Domain: Domain     Caller Logon ID: (0x0,0x3E7)
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.102
675,AUDIT FAILURE,Security,Fri Dec 24 08:49:06 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.102
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
675,AUDIT FAILURE,Security,Fri Dec 24 08:46:28 2010,NT AUTHORITY\SYSTEM,Pre-authentication failed:     User Name:  user_id    User ID:  %{id}     Service Name:  krbtgt/Domain     Pre-Authentication Type: 0x2     Failure Code:  0x18     Client Address:  172.16.5.8
c:\sc0472\LONDON-Security_LOG.txt contains 8 parsed events.


问:
Batch operation to all matrices stored in a n-dimensional numpy array
I have a numpy array of size (4, 4, 6890), which basically stores contains 6890 4x4 matrices. I need to invert all of them and I am currently doing in a loop, which I know is a bad practice

```<code>for i in range(0, T.shape[2]):
    T_inv[:,:,i] = np.linalg.inv(T[:,:,i])
</code>```

How can I do it with a single call?

答:
I'm not sure how to do it with numpy, but check this out:

```<code>[ A 0 0 ]   [ A^(-1)    0        0   ]   [ I 0 0 ]
[ 0 B 0 ] * [   0     B^(-1)     0   ] = [ 0 I 0 ]
[ 0 0 C ]   [   0       0     C^(-1) ]   [ 0 0 I ]
</code>```

A,B,C being matrices of the same size (for example 4x4), and A^(-1), B^(-1), C^(-1), being their inverses. I is a unity matrix.

So, what does this tell us? We can construct a large sparse block-diagonal matrix with all the sub-matrices (4x4) on diagonal, take the inverse of that large matrix, and just read-out the sub-matrices' inverses off diagonal blocks.

Body:
I have a numpy array of size (4, 4, 6890), which basically stores contains 6890 4x4 matrices. I need to invert all of them and I am currently doing in a loop, which I know is a bad practice

for i in range(0, T.shape[2]):
    T_inv[:,:,i] = np.linalg.inv(T[:,:,i])

How can I do it with a single call?

Body:
I'm not sure how to do it with numpy, but check this out:

[ A 0 0 ]   [ A^(-1)    0        0   ]   [ I 0 0 ]
[ 0 B 0 ] * [   0     B^(-1)     0   ] = [ 0 I 0 ]
[ 0 0 C ]   [   0       0     C^(-1) ]   [ 0 0 I ]

A,B,C being matrices of the same size (for example 4x4), and A^(-1), B^(-1), C^(-1), being their inverses. I is a unity matrix.

So, what does this tell us? We can construct a large sparse block-diagonal matrix with all the sub-matrices (4x4) on diagonal, take the inverse of that large matrix, and just read-out the sub-matrices' inverses off diagonal blocks.


问:
how to know when an action was performed and close automatically the modal
Let's consider the situation where we send, for example, a request and we are waiting a response.
While we are waiting a modal pops-up with a glyphicon, showing that the request is being processed. The result of this process is going to be an object, when it is null it means that the request was accepted with success, otherwise this object will come with an error message.
I would like to close the modal after receiving the notification, no matter if it was successful or not
can anyone give me an hint of java and wicket?</p>

答: Wicket gives you full control over ajax request life-cycle and you can implement your own listener as shown in the user guide </p>


问:
Getting duplicate keys in YAML using Python
We are in need of parsing YAML files which contain duplicate keys and all of these need to be parsed. It is not enough to skip duplicates. I know this is against the YAML spec and I would like to not have to do it, but a third-party tool used by us enables this usage and we need to deal with it.

File example:

```<code>build:
  step: 'step1'

build:
  step: 'step2'
</code>```

After parsing we should have a similar data structure to this:

```<code>yaml.load('file.yml')
# [('build', [('step', 'step1')]), ('build', [('step', 'step2')])]
</code>```

dict can no longer be used to represent the parsed contents.

I am looking for a solution in Python and I didn't find a library supporting this, have I missed anything?

Alternatively, I am happy to write my own thing but would like to make it as simple as possible. ruamel.yaml looks like the most advanced YAML parser in Python and it looks moderately extensible, can it be extended to support duplicate fields?

答:
PyYAML will just silently overwrite the first entry, ruamel.yaml¹  will give a DuplicateKeyFutureWarning if used with the legacy API, and raise a DuplicateKeyError with the new API.

If you don't want to create a full Constructor for all types, overwriting the mapping constructor in SafeConstructor should do the job:

```<code>import sys
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor

yaml_str = """\
build:
  step: 'step1'

build:
  step: 'step2'
"""

def construct_yaml_map(self, node):
    # test if there are duplicate node keys
    data = []
    yield data
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        val = self.construct_object(value_node, deep=True)
        data.append((key, val))

SafeConstructor.add_constructor(u'tag:yaml.org,2002:map', construct_yaml_map)
yaml = YAML(typ='safe')
data = yaml.load(yaml_str)
print(data)
</code>```

which gives:

```<code>[('build', [('step', 'step1')]), ('build', [('step', 'step2')])]
</code>```

However it doesn't seem necessary to make step: 'step1' into a list. The following will only create the list if there are duplicate items (could be optimised if necessary, by caching the result of the self.construct_object(key_node, deep=True)):

```<code>def construct_yaml_map(self, node):
    # test if there are duplicate node keys
    keys = set()
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        if key in keys:
            break
        keys.add(key)
    else:
        data = {}  # type: Dict[Any, Any]
        yield data
        value = self.construct_mapping(node)
        data.update(value)
        return
    data = []
    yield data
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        val = self.construct_object(value_node, deep=True)
        data.append((key, val))
</code>```

which gives:

```<code>[('build', {'step': 'step1'}), ('build', {'step': 'step2'})]
</code>```

Some points:

Probably needless to say, this will not work with YAML merge keys (<<: *xyz)

If you need ruamel.yaml's round-trip capabilities (yaml = YAML()) , that will require a more complex construct_yaml_map.

If you want to dump the output, you should instantiate a new YAML() instance for that, instead of re-using the "patched" one used for loading (it might work, this is just to be sure):

```<code>yaml_out = YAML(typ='safe')
yaml_out.dump(data, sys.stdout)
</code>```

which gives (with the first construct_yaml_map):

```<code>- - build
  - - [step, step1]
- - build
  - - [step, step2]
</code>```

What doesn't work in PyYAML nor ruamel.yaml is yaml.load('file.yml'). If you don't want to open() the file yourself you can do:

```<code>from pathlib import Path  # or: from ruamel.std.pathlib import Path
yaml = YAML(typ='safe')
yaml.load(Path('file.yml')
</code>```

¹ Disclaimer: I am the author of that package.

Body:
We are in need of parsing YAML files which contain duplicate keys and all of these need to be parsed. It is not enough to skip duplicates. I know this is against the YAML spec and I would like to not have to do it, but a third-party tool used by us enables this usage and we need to deal with it.

File example:

build:
  step: 'step1'

build:
  step: 'step2'

After parsing we should have a similar data structure to this:

yaml.load('file.yml')
# [('build', [('step', 'step1')]), ('build', [('step', 'step2')])]

dict can no longer be used to represent the parsed contents.

I am looking for a solution in Python and I didn't find a library supporting this, have I missed anything?

Alternatively, I am happy to write my own thing but would like to make it as simple as possible. ruamel.yaml looks like the most advanced YAML parser in Python and it looks moderately extensible, can it be extended to support duplicate fields?

Body:
PyYAML will just silently overwrite the first entry, ruamel.yaml¹  will give a DuplicateKeyFutureWarning if used with the legacy API, and raise a DuplicateKeyError with the new API.

If you don't want to create a full Constructor for all types, overwriting the mapping constructor in SafeConstructor should do the job:

import sys
from ruamel.yaml import YAML
from ruamel.yaml.constructor import SafeConstructor

yaml_str = """\
build:
  step: 'step1'

build:
  step: 'step2'
"""

def construct_yaml_map(self, node):
    # test if there are duplicate node keys
    data = []
    yield data
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        val = self.construct_object(value_node, deep=True)
        data.append((key, val))

SafeConstructor.add_constructor(u'tag:yaml.org,2002:map', construct_yaml_map)
yaml = YAML(typ='safe')
data = yaml.load(yaml_str)
print(data)

which gives:

[('build', [('step', 'step1')]), ('build', [('step', 'step2')])]

However it doesn't seem necessary to make step: 'step1' into a list. The following will only create the list if there are duplicate items (could be optimised if necessary, by caching the result of the self.construct_object(key_node, deep=True)):

def construct_yaml_map(self, node):
    # test if there are duplicate node keys
    keys = set()
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        if key in keys:
            break
        keys.add(key)
    else:
        data = {}  # type: Dict[Any, Any]
        yield data
        value = self.construct_mapping(node)
        data.update(value)
        return
    data = []
    yield data
    for key_node, value_node in node.value:
        key = self.construct_object(key_node, deep=True)
        val = self.construct_object(value_node, deep=True)
        data.append((key, val))

which gives:

[('build', {'step': 'step1'}), ('build', {'step': 'step2'})]

Some points:

Probably needless to say, this will not work with YAML merge keys (<<: *xyz)

If you need ruamel.yaml's round-trip capabilities (yaml = YAML()) , that will require a more complex construct_yaml_map.

If you want to dump the output, you should instantiate a new YAML() instance for that, instead of re-using the "patched" one used for loading (it might work, this is just to be sure):

yaml_out = YAML(typ='safe')
yaml_out.dump(data, sys.stdout)

which gives (with the first construct_yaml_map):

- - build
  - - [step, step1]
- - build
  - - [step, step2]

What doesn't work in PyYAML nor ruamel.yaml is yaml.load('file.yml'). If you don't want to open() the file yourself you can do:

from pathlib import Path  # or: from ruamel.std.pathlib import Path
yaml = YAML(typ='safe')
yaml.load(Path('file.yml')

¹ Disclaimer: I am the author of that package.


答:
This can be expressed almost literally as

```<code>/^[0-9]{1,18}00$/
</code>```

20 digits, the last two being zeros.

Title: Regex that allows 3-20 digits and must end with 00

Body:
I have a regex ".*00$" which restricts that the input must be ending with 00. How can I improve this to add a max length of 20 also. So:

100 => valid,

00 = > invalid,

12345678900 => valid,

111111111111111111100 = > 21 digits - invalid.

Body:
This can be expressed almost literally as

/^[0-9]{1,18}00$/

20 digits, the last two being zeros.


问:
Liferay Blade - java.lang.IllegalArgumentException: jpm4j is not installed. Missing registry key HKLM/Software/JPM4j/Home
i was trying to install Liferay Blade CLI using command Line,

```<code>'java -jar biz.aQute.jpm.run-latest.jar -g init'
</code>```

but i am getting an error as follows.

```<code>'java.lang.IllegalArgumentException: jpm4j is not installed. Missing
registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.readkey(Windows.java:56)
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:24)
    at aQute.jpm.platform.Platform.getPlatform(Platform.java:36)
    at aQute.jpm.lib.JustAnotherPackageManager.<init>(JustAnotherPackageMana
ger.java:114)
    at aQute.jpm.main.Main.run(Main.java:750)
    at aQute.jpm.main.Main.main(Main.java:83)
Exception in thread "main" java.lang.ExceptionInInitializerError
    at aQute.jpm.platform.Platform.getPlatform(Platform.java:36)
    at aQute.jpm.lib.JustAnotherPackageManager.<init>(JustAnotherPackageMana
ger.java:114)
    at aQute.jpm.main.Main.run(Main.java:750)
    at aQute.jpm.main.Main.main(Main.java:83)
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException:
jpm4j
 is not installed. Missing registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:37)
    ... 4 more
Caused by: java.lang.IllegalArgumentException: jpm4j is not installed.
Missing registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.readkey(Windows.java:56)
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:24)
    ... 4 more'
</code>```

Is there anything to be added/changed in the system files?
please help.
Thanks

答:
This issue is solved in this way.

downloaded JPM from  https://github.com/jpm4j/jpm4j.installers/blob/master/dist/biz.aQute.jpm.run.jar?raw=true

Go to the downloaded location and run
"java -jar biz.aQute.jpm.run.jar -g init"
in command prompt

Go bin directory of JPM in C, open command prompt and run,

```<code>"jpm platform path -a"
</code>```

open environmant variables, path->edit add ;C:\JPM4J\bin

To test,

```<code>test->jpm
</code>```

open the bin folder in command prompt, run

```<code> "jpm install -f https://releases.liferay.com/tools/blade-cli/latest/blade.jar"
</code>```

To test test->blade

Body:
i was trying to install Liferay Blade CLI using command Line,

'java -jar biz.aQute.jpm.run-latest.jar -g init'

but i am getting an error as follows.

'java.lang.IllegalArgumentException: jpm4j is not installed. Missing
registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.readkey(Windows.java:56)
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:24)
    at aQute.jpm.platform.Platform.getPlatform(Platform.java:36)
    at aQute.jpm.lib.JustAnotherPackageManager.<init>(JustAnotherPackageMana
ger.java:114)
    at aQute.jpm.main.Main.run(Main.java:750)
    at aQute.jpm.main.Main.main(Main.java:83)
Exception in thread "main" java.lang.ExceptionInInitializerError
    at aQute.jpm.platform.Platform.getPlatform(Platform.java:36)
    at aQute.jpm.lib.JustAnotherPackageManager.<init>(JustAnotherPackageMana
ger.java:114)
    at aQute.jpm.main.Main.run(Main.java:750)
    at aQute.jpm.main.Main.main(Main.java:83)
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException:
jpm4j
 is not installed. Missing registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:37)
    ... 4 more
Caused by: java.lang.IllegalArgumentException: jpm4j is not installed.
Missing registry key HKLM/Software/JPM4j/Home
    at aQute.jpm.platform.Windows.readkey(Windows.java:56)
    at aQute.jpm.platform.Windows.<clinit>(Windows.java:24)
    ... 4 more'

Is there anything to be added/changed in the system files?
please help.
Thanks

Body:
This issue is solved in this way.

downloaded JPM from  https://github.com/jpm4j/jpm4j.installers/blob/master/dist/biz.aQute.jpm.run.jar?raw=true

Go to the downloaded location and run
"java -jar biz.aQute.jpm.run.jar -g init"
in command prompt

Go bin directory of JPM in C, open command prompt and run,

"jpm platform path -a"

open environmant variables, path->edit add ;C:\JPM4J\bin

To test,

test->jpm

open the bin folder in command prompt, run

 "jpm install -f https://releases.liferay.com/tools/blade-cli/latest/blade.jar"

To test test->blade


问:
How to remove docker container even if root filesystem does not exists?
I have one container that is dead, but I can't remove it, as you can see below.

How can I remove it? Or how can I clean my system manually to remove it?

```<code>:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
78b0dcaffa89        ubuntu:latest       "bash -c 'while tr..."   30 hours ago        Dead                                    leo.1.bkbjt6w08vgeo39rt1nmi7ock

:~$ docker rm --force 78b0dcaffa89
Error response from daemon: driver "aufs" failed to remove root filesystem for 78b0dcaffa89ac1e532748d44c9b2f57b940def0e34f1f0d26bf7ea1a10c222b: no such file or directory
</code>```

答:
While browsing related issues, I found something similar "Driver aufs failed to remove root filesystem", "device or resource busy", and at around 80% below, there was a solution which said to use docker stop cadvisor; then docker rm [dead container]

Edit 1: docker stop cadvisor instead of docker stop deadContainerId

Body:
I have one container that is dead, but I can't remove it, as you can see below.

How can I remove it? Or how can I clean my system manually to remove it?

:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
78b0dcaffa89        ubuntu:latest       "bash -c 'while tr..."   30 hours ago        Dead                                    leo.1.bkbjt6w08vgeo39rt1nmi7ock

:~$ docker rm --force 78b0dcaffa89
Error response from daemon: driver "aufs" failed to remove root filesystem for 78b0dcaffa89ac1e532748d44c9b2f57b940def0e34f1f0d26bf7ea1a10c222b: no such file or directory


问:
Move values after comma to newline to text file
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

```<code>Monday
Tuesday
Wednesday
Thursday
Friday
</code>```

One below the other.

Hope this makes sense.

答:
Use something like this</p>

```<code>$colVal = $row['col-name'];
echo str_replace(",", "\r\n", $colVal);
</code>```

Body:
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

Monday
Tuesday
Wednesday
Thursday
Friday

One below the other.

Hope this makes sense.

Body:
Use something like this

$colVal = $row['col-name'];
echo str_replace(",", "\r\n", $colVal);


问:
Russian phone number gets formatted on dial
I'm currently facing a problem on iOS (I tried on iPhone 5/iOS 9 and iPhone 6 Plus/iOS 8). My goal is to open the phone application and dial a russian number.
The number is like

8 800 123 45 67

To be short, I'm just doing

```<code>[[UIApplication sharedApplication] openURL:@"tel:88001234567"]
</code>```

Whenever I'm trying to call, the phone number gets formatted and loses one 0 to become

+880 123 4567

And when I try to add the indicative which is 007, the phone number called loses one 8 to become

00 7 (800) 123-45-67

Last thing, when I try to use

```<code>[[UIApplication sharedApplication] openURL:@"telprompt:88001234567"]
</code>```

It correctly shows me

00 7 (8800) 123-45-67

But when I press "Call", the phone number called is

00 7 (800) 123-45-67

Did anyone already have this problem? Is this a normal behavior on iOS? On Android the dial application doesn't format the phone number.

Edit: Thanks to Pekka, when we check this page https://en.wikipedia.org/wiki/Telephone_numbers_in_Russia we can see:

Calls from outside Russia: +7 ABC xxx-xx-xx where ABC is the area code

Then the fact that one 8 drops when adding the country code is normal.

Other point, it seems that the first 8 is a long-distance prefix that might be not necessary. I'm gonna try to contact our customer to be sure about this.

Edit 2: Well, our customer told us that the first 8 is required, I'm gonna have to find a way around.

答:
lose the first 8 add +7 prefix:
+78001234567</p>

Body:
I'm currently facing a problem on iOS (I tried on iPhone 5/iOS 9 and iPhone 6 Plus/iOS 8). My goal is to open the phone application and dial a russian number.
The number is like

8 800 123 45 67

To be short, I'm just doing

[[UIApplication sharedApplication] openURL:@"tel:88001234567"]

Whenever I'm trying to call, the phone number gets formatted and loses one 0 to become

+880 123 4567

And when I try to add the indicative which is 007, the phone number called loses one 8 to become

00 7 (800) 123-45-67

Last thing, when I try to use

[[UIApplication sharedApplication] openURL:@"telprompt:88001234567"]

It correctly shows me

00 7 (8800) 123-45-67

But when I press "Call", the phone number called is

00 7 (800) 123-45-67

Did anyone already have this problem? Is this a normal behavior on iOS? On Android the dial application doesn't format the phone number.

Edit: Thanks to Pekka, when we check this page https://en.wikipedia.org/wiki/Telephone_numbers_in_Russia we can see:

Calls from outside Russia: +7 ABC xxx-xx-xx where ABC is the area code

Then the fact that one 8 drops when adding the country code is normal.

Other point, it seems that the first 8 is a long-distance prefix that might be not necessary. I'm gonna try to contact our customer to be sure about this.

Edit 2: Well, our customer told us that the first 8 is required, I'm gonna have to find a way around.


问:
First Website - Security Concerns
I have taught myself HTML/CSS and some JavaScript as a hobby, and have reached the point where I am comfortable building a clean simple website. The company I work for (we do nothing related to coding) has a website that is quite outdated so naturally I saw this as an opportunity for my first live site. I approached my Managers at work to take a look at my first mock up and they loved it and want me to revamp our current site.

The one concern they have with me being a rookie is the issue of web security.  Essentially they want to make sure that the website I build leaves no vulnerability for someone to hack through our server, start editing our website, etc.

There are no interactive components to the current website.  I plan to build this website with only HTML and CSS, and perhaps add some JavaScript later down the road once I progress in my learning a bit more.  There are no account logins or areas to enter personal information anywhere on the site.

My question comes down to this -- what can I do to ensure that the website I build is not leaving our company vulnerable? I have done a lot of searching around Stack Overflow and other websites but I am not confident I am finding the correct information.

Details that might make a difference:

Our company website is hosted through godaddy.com

Our website is currently on Wordpress, but I will probably not use Wordpress for the new website

I greatly appreciate all of your help!

答:
When you are concerning about just AJAX call, I would help you out for following suggestion regarding "Function access rule from AJAX".

By adding "_" as a prefix for Function name, we can prevent function to be called from The Web publicly. This is the best practice when we need some specific function to be accessed via AJAX only.

Kindly, refer my answer given in other question.
[Website Security: How to learn?

Title: First Website - Security Concerns


答:
You can use {} to specify a range of characters, so

```<code>".{1,18}00"
</code>```

would allow any 1-18 characters followed by 00.  If you want to restrict it further, you could use

```<code>"[1-9][0-9]{0,17}00"
</code>```

so that you ensure the first number is not 0, followed by 0-17 numbers and finally 00.

Body:
You can use {} to specify a range of characters, so

".{1,18}00"

would allow any 1-18 characters followed by 00.  If you want to restrict it further, you could use

"[1-9][0-9]{0,17}00"

so that you ensure the first number is not 0, followed by 0-17 numbers and finally 00.


问:
Error accessing ftp with getURL in R
I want access files on the internet, but I get the following error message:

```<code>Error in function (type, msg, asError = TRUE)  : Access denied: 530
In addition: Warning messages:
1: In strsplit(str, "\\\r\\\n") : input string 1 is invalid in this locale
</code>```

This is my code from this post:

```<code>library(RCurl)
url<'ftp://ftp.address'
    userpwd <- "user:password"
filenames <- getURL(url, userpwd = userpwd,
                    ftp.use.epsv=FALSE, dirlistonly = TRUE)
</code>```

Any idea how to solve this?

Thanks a lot for your help!

答:
Try:</p>

```<code>library(RCurl)
filenames <- getURL(url="ftp://user:password@ftp.address",ftp.use.epsv=FALSE, dirlistonly = FALSE)
</code>```

Title: Error accessing ftp with getURL in R

Body:
I want access files on the internet, but I get the following error message:

Error in function (type, msg, asError = TRUE)  : Access denied: 530
In addition: Warning messages:
1: In strsplit(str, "\\\r\\\n") : input string 1 is invalid in this locale

This is my code from this post:

library(RCurl)
url<'ftp://ftp.address'
    userpwd <- "user:password"
filenames <- getURL(url, userpwd = userpwd,
                    ftp.use.epsv=FALSE, dirlistonly = TRUE)

Any idea how to solve this?

Thanks a lot for your help!

Body:
Try:

library(RCurl)
filenames <- getURL(url="ftp://user:password@ftp.address",ftp.use.epsv=FALSE, dirlistonly = FALSE)


问:
How to get Average search volume AND Average CPC with same Google Adwords API service?
I am using the Google Adwords API to retrieve the Average search volume for a given keyword, using the TargetingIdeaService get function.
Now I would like to also retrieve the Average CPC for the same keyword.

All I could find so far is a way to do that with the TrafficEstimatorService, but that implies additional cost, I believe.

So my question is: is there any way to retrieve both:

the Average Search Volume,

the CPC data

using the same service (either TargetingIdeaService or TrafficEstimatorService, or other)?

答:
Unfortunately you'll need to use the TIS to get search volume and the TES to get CPC estimates.  There is no service that provides both.

P.S. - In case you aren't aware, there is an official AdWords API forum: http://code.google.com/apis/adwords/forum.html


问:
How to run war file on machine of client from another country without having error related to clock/ signature?
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

```<code>Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)
</code>```

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

```<code>@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }
</code>```

Method to create BlobSAS :

```<code>@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }
</code>```

Method to create shared access blob policy :

```<code>private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }
</code>```

What changes I should make here?

答:
Without the code it is hard to tell, however there is a chance that the times on the client or at the server are not in utc or wrongly converted.

Check the time and timezones of the machine. If they match, check your code if the utc time or local time is used.

Body:
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }

Method to create BlobSAS :

@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }

Method to create shared access blob policy :

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }

What changes I should make here?


问:
Can't resolve all parameters for [...]
Looks like a pretty common problem. I want to use Service1 in Service2 and I get the exception

Error: Can't resolve all parameters for ILIASRestProvider: (Http, ?).

even though in other Components Service2 seems to be injectable. And I think I have everything together:

@Injectable at the Service1 and Service2

tsconfig.json emitDecoratorMetadata set to true

Registered Service1 and Service2 in the Providers part of the ngModule

If it matters at all: I'm building an Ionic 2 RC0 Application. Here are the important files:

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import {AppConfig} from "../config/app-config";
import {ConnectionService} from "../services/ilias-app.service";
import {ILIASRestProvider} from "../providers/ilias-rest.provider";
import {MigrationsService} from "../services/migrations.service";
import {FooterToolbarService} from "../services/footer-toolbar.service";
import {ObjectListPage} from "../pages/object-list/object-list";
import {FavoritesPage} from "../pages/favorites/favorites";
import {NewObjectsPage} from "../pages/new-objects/new-objects";
import {SettingsPage} from "../pages/settings/settings";
import {InfoPage} from "../pages/info/info";
import {LogoutPage} from "../pages/logout/logout";
import {SynchronizationService} from "../services/synchronization.service";
import {DataProvider} from "../providers/data-provider.provider";
import {FileService} from "../services/file.service";
import {DataProviderFileObjectHandler} from "../providers/handlers/file-object-handler";
import {TranslatePipe} from "ionic-angular/index";
import {FileSizePipe} from "../pipes/fileSize.pipe";
import {HttpModule, Http} from '@angular/http';
import {TranslateModule} from 'ng2-translate/ng2-translate';
import {TranslateLoader} from "ng2-translate/src/translate.service";
import {TranslateStaticLoader} from "ng2-translate/src/translate.service";

@NgModule({
  declarations: [
    MyApp,
    ObjectListPage,
    FavoritesPage,
    NewObjectsPage,
    SettingsPage,
    InfoPage,
    LogoutPage,
    FileSizePipe,
    TranslatePipe
  ],
  imports: [
    HttpModule,
    IonicModule.forRoot(MyApp, {prodMode: window.hasOwnProperty('cordova')}),
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
      deps: [Http]
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ObjectListPage,
    FavoritesPage,
    NewObjectsPage,
    SettingsPage,
    InfoPage,
    LogoutPage
  ],
  providers: [
    AppConfig,
    ConnectionService, //<-----------------------
    MigrationsService,
    ILIASRestProvider, //<-------------------------
    FooterToolbarService,
    DataProvider,
    FileService,
    SynchronizationService,
    DataProviderFileObjectHandler
  ]
})
export class AppModule {}
</code>```

ilias-rest.provider.ts

```<code>@Injectable()
export class ILIASRestProvider {

    public constructor(private http:Http, public app:ConnectionService) {
    }
    ...
}
</code>```

ilias-app.service.ts

```<code>@Injectable()
export class ConnectionService {

    ...

    constructor(public _config:AppConfig) {
        this._database = SQLiteDatabaseService.instance();
    }

    ...
}
</code>```

app-config.ts

```<code>@Injectable()
export class AppConfig {

    protected data:any = {};

    constructor(public http:Http) {
    }

    ...
}
</code>```

ionic setup

```<code>Your system information:

Cordova CLI: 5.4.1
Ionic Framework Version: 2.0.0-rc.0
Ionic CLI Version: 2.1.0
Ionic App Lib Version: 2.1.0-beta.1
OS: Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS
Node Version: v6.6.0
</code>```

答:
Just had the same problem here at work. The problem was that we had a circular file dependency.

SignInComponent was being tested in a unit test

SignInComponent used AuthService

AuthService used Routes.ts

Routes.ts defined a route that had SignInComponent as its component

You can spot this is the problem when the injection system cannot give you the name of what it is unable to create an instance of, and simply gives the name as "?"

Title: Can't resolve all parameters for [...]

Body:
Looks like a pretty common problem. I want to use Service1 in Service2 and I get the exception

Error: Can't resolve all parameters for ILIASRestProvider: (Http, ?).

even though in other Components Service2 seems to be injectable. And I think I have everything together:

@Injectable at the Service1 and Service2

tsconfig.json emitDecoratorMetadata set to true

Registered Service1 and Service2 in the Providers part of the ngModule

If it matters at all: I'm building an Ionic 2 RC0 Application. Here are the important files:

app.module.ts

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import {AppConfig} from "../config/app-config";
import {ConnectionService} from "../services/ilias-app.service";
import {ILIASRestProvider} from "../providers/ilias-rest.provider";
import {MigrationsService} from "../services/migrations.service";
import {FooterToolbarService} from "../services/footer-toolbar.service";
import {ObjectListPage} from "../pages/object-list/object-list";
import {FavoritesPage} from "../pages/favorites/favorites";
import {NewObjectsPage} from "../pages/new-objects/new-objects";
import {SettingsPage} from "../pages/settings/settings";
import {InfoPage} from "../pages/info/info";
import {LogoutPage} from "../pages/logout/logout";
import {SynchronizationService} from "../services/synchronization.service";
import {DataProvider} from "../providers/data-provider.provider";
import {FileService} from "../services/file.service";
import {DataProviderFileObjectHandler} from "../providers/handlers/file-object-handler";
import {TranslatePipe} from "ionic-angular/index";
import {FileSizePipe} from "../pipes/fileSize.pipe";
import {HttpModule, Http} from '@angular/http';
import {TranslateModule} from 'ng2-translate/ng2-translate';
import {TranslateLoader} from "ng2-translate/src/translate.service";
import {TranslateStaticLoader} from "ng2-translate/src/translate.service";

@NgModule({
  declarations: [
    MyApp,
    ObjectListPage,
    FavoritesPage,
    NewObjectsPage,
    SettingsPage,
    InfoPage,
    LogoutPage,
    FileSizePipe,
    TranslatePipe
  ],
  imports: [
    HttpModule,
    IonicModule.forRoot(MyApp, {prodMode: window.hasOwnProperty('cordova')}),
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
      deps: [Http]
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ObjectListPage,
    FavoritesPage,
    NewObjectsPage,
    SettingsPage,
    InfoPage,
    LogoutPage
  ],
  providers: [
    AppConfig,
    ConnectionService, //<-----------------------
    MigrationsService,
    ILIASRestProvider, //<-------------------------
    FooterToolbarService,
    DataProvider,
    FileService,
    SynchronizationService,
    DataProviderFileObjectHandler
  ]
})
export class AppModule {}

ilias-rest.provider.ts

@Injectable()
export class ILIASRestProvider {

    public constructor(private http:Http, public app:ConnectionService) {
    }
    ...
}

ilias-app.service.ts

@Injectable()
export class ConnectionService {

    ...

    constructor(public _config:AppConfig) {
        this._database = SQLiteDatabaseService.instance();
    }

    ...
}

app-config.ts

@Injectable()
export class AppConfig {

    protected data:any = {};

    constructor(public http:Http) {
    }

    ...
}

ionic setup

Your system information:

Cordova CLI: 5.4.1
Ionic Framework Version: 2.0.0-rc.0
Ionic CLI Version: 2.1.0
Ionic App Lib Version: 2.1.0-beta.1
OS: Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS
Node Version: v6.6.0


问:
Creating default object from empty value in PHP?
I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

```<code>$res->success = false;
</code>```

Do I first need to declare my $res object?

答:
If you put "@" character begin of the line then PHP doesn't show any warning/notice for this line. For example:

```<code>$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value
</code>```

For preventing this warning for this line you must put "@" character begin of the line like this:

```<code>@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20
</code>```

I'm using this trick when developing. I don't like disable all warning messages becouse if you don't handle warnings correctly then they will become a big error in future.

Body:
I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

$res->success = false;

Do I first need to declare my $res object?

Body:
If you put "@" character begin of the line then PHP doesn't show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put "@" character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I'm using this trick when developing. I don't like disable all warning messages becouse if you don't handle warnings correctly then they will become a big error in future.