问:
required android.permission Read_External_storage, or grantUrlPermissions error
I think my permissions properly located on AndroidManifest.xml.

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

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

            </intent-filter>
        </activity>

        <activity android:name=".NextActivity"
            android:label="This is next_activity"/>
    </application>

</manifest>
</code>```

I have "android.permission.READ_EXTERNAL_STORAGE" and "android.permission.WRITE_EXTERNAL_STORAGE" right after manifest.

but the error is keep occured.

Caused by: java.lang.SecurityException: Permission Denial: reading
  com.android.providers.media.MediaProvider uri
  content://media/external/images/media/40 from pid=2473, uid=10073
  requires android.permission.READ_EXTERNAL_STORAGE, or
  grantUriPermission()

and this is my MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

public static final int IMAGE_GALLERY_REQUEST = 20;
Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   }

public void gallery_open(View view) {
    Intent galleryPickerIntent = new Intent(Intent.ACTION_PICK);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureDirectoryPath = pictureDirectory.getPath();
    Uri data = Uri.parse(pictureDirectoryPath);
    galleryPickerIntent.setDataAndType(data,"image/*");
    startActivityForResult(galleryPickerIntent, IMAGE_GALLERY_REQUEST);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode ==  IMAGE_GALLERY_REQUEST) {
            onSelectedFromGalleryResult(imageReturnedIntent);
        }
    }

}

private void onSelectedFromGalleryResult(Intent data){
    Bitmap bm  = null;
    if(data != null){
        try{
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        }catch(IOException e){
            e.printStackTrace();
        }
        //ivImage.setImageBitmap(bm);
        ImageView imgView = (ImageView)findViewById(R.id.ivImage);
        imgView.setImageBitmap(bm);

    }
}
</code>```

答:
You need to provide the run time permission for android marshmallow version

You can add this code in onCreate() or any click events, try this:

```<code>     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
            //    requestPermission();
            requestAppPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    R.string.app_name, REQUEST_PERMISSIONS);

            //this code will be executed on devices running ICS or later
        }
</code>```

also add this function for requesting the run time permission

```<code>   public void requestAppPermissions(final String[] requestedPermissions,
                                          final int stringId, final int requestCode) {
            mErrorString.put(requestCode, stringId);
            int permissionCheck = PackageManager.PERMISSION_GRANTED;
            boolean shouldShowRequestPermissionRationale = false;
            for (String permission : requestedPermissions) {
                permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
                shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
            }
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale) {
                    Snackbar.make(findViewById(android.R.id.content), stringId,
                            Snackbar.LENGTH_INDEFINITE).setAction("GRANT",
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ActivityCompat.requestPermissions(DashBoardActivity.this, requestedPermissions, requestCode);
                                }
                            }).show();
                } else {
                    ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
                }
            } else {
                onPermissionsGranted(requestCode);
            }
        }
</code>```

This function is called when the permission is granted and you can read the internal and external storage

```<code>public void onPermissionsGranted(final int requestCode) {
        Toast.makeText(this, "Permissions Received.", Toast.LENGTH_LONG).show();
    }
</code>```

The below code for checking the requested permission result

```<code>  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int permission : grantResults) {
            permissionCheck = permissionCheck + permission;
        }
        if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED) {
            onPermissionsGranted(requestCode);
        } else {
            Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

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

Body:
I think my permissions properly located on AndroidManifest.xml.

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

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

            </intent-filter>
        </activity>

        <activity android:name=".NextActivity"
            android:label="This is next_activity"/>
    </application>

</manifest>

I have "android.permission.READ_EXTERNAL_STORAGE" and "android.permission.WRITE_EXTERNAL_STORAGE" right after manifest.

but the error is keep occured.

Caused by: java.lang.SecurityException: Permission Denial: reading
  com.android.providers.media.MediaProvider uri
  content://media/external/images/media/40 from pid=2473, uid=10073
  requires android.permission.READ_EXTERNAL_STORAGE, or
  grantUriPermission()

and this is my MainActivity.java

public class MainActivity extends AppCompatActivity {

public static final int IMAGE_GALLERY_REQUEST = 20;
Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   }

public void gallery_open(View view) {
    Intent galleryPickerIntent = new Intent(Intent.ACTION_PICK);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String pictureDirectoryPath = pictureDirectory.getPath();
    Uri data = Uri.parse(pictureDirectoryPath);
    galleryPickerIntent.setDataAndType(data,"image/*");
    startActivityForResult(galleryPickerIntent, IMAGE_GALLERY_REQUEST);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode ==  IMAGE_GALLERY_REQUEST) {
            onSelectedFromGalleryResult(imageReturnedIntent);
        }
    }

}

private void onSelectedFromGalleryResult(Intent data){
    Bitmap bm  = null;
    if(data != null){
        try{
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        }catch(IOException e){
            e.printStackTrace();
        }
        //ivImage.setImageBitmap(bm);
        ImageView imgView = (ImageView)findViewById(R.id.ivImage);
        imgView.setImageBitmap(bm);

    }
}

Body:
You need to provide the run time permission for android marshmallow version

You can add this code in onCreate() or any click events, try this:

     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
            //    requestPermission();
            requestAppPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    R.string.app_name, REQUEST_PERMISSIONS);

            //this code will be executed on devices running ICS or later
        }

also add this function for requesting the run time permission

   public void requestAppPermissions(final String[] requestedPermissions,
                                          final int stringId, final int requestCode) {
            mErrorString.put(requestCode, stringId);
            int permissionCheck = PackageManager.PERMISSION_GRANTED;
            boolean shouldShowRequestPermissionRationale = false;
            for (String permission : requestedPermissions) {
                permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
                shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
            }
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale) {
                    Snackbar.make(findViewById(android.R.id.content), stringId,
                            Snackbar.LENGTH_INDEFINITE).setAction("GRANT",
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ActivityCompat.requestPermissions(DashBoardActivity.this, requestedPermissions, requestCode);
                                }
                            }).show();
                } else {
                    ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
                }
            } else {
                onPermissionsGranted(requestCode);
            }
        }

This function is called when the permission is granted and you can read the internal and external storage

public void onPermissionsGranted(final int requestCode) {
        Toast.makeText(this, "Permissions Received.", Toast.LENGTH_LONG).show();
    }

The below code for checking the requested permission result

  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int permission : grantResults) {
            permissionCheck = permissionCheck + permission;
        }
        if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED) {
            onPermissionsGranted(requestCode);
        } else {
            Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
        }
    }


来源: stackexchange

问:
How can I cover a div with a semi-transparent image?
I want to cover a
 so it looks like it has a semi-transparent block over it.

I am using jQuery but I do not know how to do it.

Any help thanks...

答:
If you have another div, you can just get the dimensions + position like

```<code>var $somediv = $('#some_div_element'),
    pos      = $.extend({
       width:    $somediv.outerWidth(),
       height:   $somediv.outerHeight()
    }, $somediv.position());
</code>```

and then use it while dynamically creating an overlay

```<code>$('<div>', {
    id:    'overlay',
    css:   {
        position:         'absolute',
        top:              pos.top,
        left:             pos.left,
        width:            pos.width,
        height:           pos.height,
        backgroundColor:  '#000',
        opacity:          0.50
    }
}).appendTo($somediv);
</code>```

Example: http://www.jsfiddle.net/GkFu4/1/

ContentLicense: CC BY-SA 2.5

Body:
If you have another div, you can just get the dimensions + position like

var $somediv = $('#some_div_element'),
    pos      = $.extend({
       width:    $somediv.outerWidth(),
       height:   $somediv.outerHeight()
    }, $somediv.position());

and then use it while dynamically creating an overlay

$('<div>', {
    id:    'overlay',
    css:   {
        position:         'absolute',
        top:              pos.top,
        left:             pos.left,
        width:            pos.width,
        height:           pos.height,
        backgroundColor:  '#000',
        opacity:          0.50
    }
}).appendTo($somediv);

Example: http://www.jsfiddle.net/GkFu4/1/


问:
Save the last letter when typing in a textField
I have this function in my application:

```<code>func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)
    }
}
</code>```

In viewDidLoad() I have written this:

```<code>textField.addTarget(self, action: #selector(typingName), for: .editingChanged)
</code>```

All works good, but I want to save only the letter typed by the user.

With this function if I write "hello" it prints:
"h"
"he"
"hel"
"hell"
"hello".

Instead, I want to have this:
"h"
"e"
"l"
"l"
"o".

答:
If you want to get last character which user entered with keyboard.

You can detect it with delegate method of UITextField as shown in below code:

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var tfName: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //Need to confirm delegate for textField here.
        tfName.delegate = self
    }

    //UITextField Delegate Method
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //This will print every single character entered by user.
        print(string)
        return true
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this function in my application:

func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)
    }
}

In viewDidLoad() I have written this:

textField.addTarget(self, action: #selector(typingName), for: .editingChanged)

All works good, but I want to save only the letter typed by the user.

With this function if I write "hello" it prints:
"h"
"he"
"hel"
"hell"
"hello".

Instead, I want to have this:
"h"
"e"
"l"
"l"
"o".

Body:
If you want to get last character which user entered with keyboard.

You can detect it with delegate method of UITextField as shown in below code:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var tfName: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //Need to confirm delegate for textField here.
        tfName.delegate = self
    }

    //UITextField Delegate Method
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //This will print every single character entered by user.
        print(string)
        return true
    }
}


问:
Removing divs without removing their content in plain Javascript
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

```<code><div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>
</code>```

Expected output would be like shown below.

```<code><p>some text
   <label> Test content </label>
</p>
<span>some text</span>
<label> Test content </label>
<a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a>
</code>```

答:
Using cutting edge technology such as iterable nodelists and replaceWith, it's really straightforward with the plain DOM API:

```<code>for (const div of document.querySelectorAll("div"))
// alternatively: Array.from(document.getElementsByTagName("div"))
    div.replaceWith(...div.childNodes);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

some text
     Test content

    some text

       Test content
      creepiness

Expected output would be like shown below.

some text
    Test content

some text
 Test content
creepiness

Body:
Using cutting edge technology such as iterable nodelists and replaceWith, it's really straightforward with the plain DOM API:

for (const div of document.querySelectorAll("div"))
// alternatively: Array.from(document.getElementsByTagName("div"))
    div.replaceWith(...div.childNodes);


问:
Angular 2 - moving embedded plugin to service
I am new to Angular 2, and am just learning how to include plugins. I am getting this error:

Uncaught Error: Can't resolve all parameters for SwitchClientComponent: ([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?, ?)

when implementing crypto-js.

I'm sure it's because I haven't properly installed and referenced it.

I have an app.module.ts file (snipped for brevity):

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
import { FormsModule } from '@angular/forms';
...
import { MomentModule } from 'angular2-moment';
import { CryptoJS } from "crypto-js";

@NgModule({
    declarations: [
        AppComponent,
        ...
        SwitchClientComponent
    ],
    imports: [
        BrowserModule,
        ...
        StoreModule.provideStore({ appState: appStateReducer }),
    ],providers: [
    { provide: AppConfig, useFactory: serviceConfigFactory },
    SiteService,
    AppContext,
    { provide: APP_INITIALIZER, useFactory: AppContextLoader, deps: [AppContext], multi: true },
    EmployeeService,
    EncryptionService
],
    ...

})
export class AppModule { }
</code>```

(I see an import line but no corresponding reference in the @NgModule...)

Here is where I'm trying to use it:

```<code>import { Injectable } from '@angular/core';
import { CryptoJS } from "crypto-js";

@Injectable()
export class EncryptionService {

    secretKey: string = "123";

    constructor() {
    }

    public setLocalStorage(storagePrefix : string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }
}
</code>```

Here is the actual switch-client-component that is trying to utilize the service:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SiteService } from '../../services/site.service';
import { CompanyRoutes } from '../../features/company/company.routes';
import { AppContext } from '../../services/app.context';
import { SiteConfig } from '../../models/site/site.config';
import { AuthService } from '../../services/auth/auth.service';
import { EncryptionService } from '../../services/encryption.service';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
    availableClients : any[] = [];
    filterString: string = '';
    frequentClients: any[] = [];
    maxFrequentClients: number = 6;
    storagePrefix = 'AbilitiConnect-FrequentClients';

    constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
    ) {}

    ngOnInit() {
        this.availableClients = this.siteService.getAvailableClientCodes();
        //redirect the user to main page if there is onlu one client.
        if (this.availableClients == null || this.availableClients.length <= 1) {
            this.router.navigate(['/']);
        }
        this.purgeFrequentClients();
        this.frequentClients = this.getFrequentClients();
    }

    switchClient(client) {
        this.updateFrequentClient(client);
        this.appContext.switchClient(client.ClientCode)
            .subscribe((siteConfig: SiteConfig) => {
                this.companyRoutes.resetCompanyRoutes(siteConfig.clientCode, "/");
                this.router.navigate(['/']);
            });
    };

    updateFrequentClient(client) {
        var tempClientArr = [];
        tempClientArr = this.getFrequentClients();
        tempClientArr = tempClientArr.filter(item => item.Name !== client.Name);
        tempClientArr.unshift(client);
        tempClientArr = tempClientArr.slice(0, this.maxFrequentClients);
        this.encryptionService.setLocalStorage(this.storagePrefix, tempClientArr);
    };

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
    purgeFrequentClients() {
        this.encryptionService.setLocalStorage(this.storagePrefix, []);
    };
}
</code>```

I don't know how to interpret that error.

答:
Install Cryto js usning npm

```<code>npm install crypto-js

typings install dt~crypto-js --global --save
</code>```

You can refer crypto js in below ways

```<code>import * as CryptoJS from 'crypto-js';
</code>```

Body:
I am new to Angular 2, and am just learning how to include plugins. I am getting this error:

Uncaught Error: Can't resolve all parameters for SwitchClientComponent: ([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?, ?)

when implementing crypto-js.

I'm sure it's because I haven't properly installed and referenced it.

I have an app.module.ts file (snipped for brevity):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
import { FormsModule } from '@angular/forms';
...
import { MomentModule } from 'angular2-moment';
import { CryptoJS } from "crypto-js";

@NgModule({
    declarations: [
        AppComponent,
        ...
        SwitchClientComponent
    ],
    imports: [
        BrowserModule,
        ...
        StoreModule.provideStore({ appState: appStateReducer }),
    ],providers: [
    { provide: AppConfig, useFactory: serviceConfigFactory },
    SiteService,
    AppContext,
    { provide: APP_INITIALIZER, useFactory: AppContextLoader, deps: [AppContext], multi: true },
    EmployeeService,
    EncryptionService
],
    ...

})
export class AppModule { }

(I see an import line but no corresponding reference in the @NgModule...)

Here is where I'm trying to use it:

import { Injectable } from '@angular/core';
import { CryptoJS } from "crypto-js";

@Injectable()
export class EncryptionService {

    secretKey: string = "123";

    constructor() {
    }

    public setLocalStorage(storagePrefix : string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }
}

Here is the actual switch-client-component that is trying to utilize the service:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SiteService } from '../../services/site.service';
import { CompanyRoutes } from '../../features/company/company.routes';
import { AppContext } from '../../services/app.context';
import { SiteConfig } from '../../models/site/site.config';
import { AuthService } from '../../services/auth/auth.service';
import { EncryptionService } from '../../services/encryption.service';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
    availableClients : any[] = [];
    filterString: string = '';
    frequentClients: any[] = [];
    maxFrequentClients: number = 6;
    storagePrefix = 'AbilitiConnect-FrequentClients';

    constructor(public auth: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private appContext: AppContext,
        private siteService: SiteService,
        private companyRoutes: CompanyRoutes,
        private encryptionService, EncryptionService
    ) {}

    ngOnInit() {
        this.availableClients = this.siteService.getAvailableClientCodes();
        //redirect the user to main page if there is onlu one client.
        if (this.availableClients == null || this.availableClients.length <= 1) {
            this.router.navigate(['/']);
        }
        this.purgeFrequentClients();
        this.frequentClients = this.getFrequentClients();
    }

    switchClient(client) {
        this.updateFrequentClient(client);
        this.appContext.switchClient(client.ClientCode)
            .subscribe((siteConfig: SiteConfig) => {
                this.companyRoutes.resetCompanyRoutes(siteConfig.clientCode, "/");
                this.router.navigate(['/']);
            });
    };

    updateFrequentClient(client) {
        var tempClientArr = [];
        tempClientArr = this.getFrequentClients();
        tempClientArr = tempClientArr.filter(item => item.Name !== client.Name);
        tempClientArr.unshift(client);
        tempClientArr = tempClientArr.slice(0, this.maxFrequentClients);
        this.encryptionService.setLocalStorage(this.storagePrefix, tempClientArr);
    };

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
    purgeFrequentClients() {
        this.encryptionService.setLocalStorage(this.storagePrefix, []);
    };
}

I don't know how to interpret that error.

Body:
Install Cryto js usning npm

npm install crypto-js

typings install dt~crypto-js --global --save

You can refer crypto js in below ways

import * as CryptoJS from 'crypto-js';


问:
Python - Strip line at either one point or another in the same string
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

```<code>        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())
</code>```

example on how the file with the strings looks

```<code>SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]
</code>```

Basically I want to extract the numbers

答:
This is a simple regex problem if your data is now how you have shown then you can solve this with regex pretty simply.

```<code>import re

numbers = re.compile("[\d|\w]{2}\s")
just_numbers = []
for line in data:
    just_numbers.append(" ".join([x.strip() for x in numbers.findall(line)]))

print(just_numbers)
</code>```

Output

```<code>['12 3F 56 7D', '3C 53 25 25', '32 12 H2 3G']
</code>```

In [\d|\w]{2}\s the [\d|\w] matches on characters that are either letters or numbers, so 0-9a-z-A-Z. Then the {2} after it means I want strings that are exactly two characters matching the previous pattern (aka [\d|\w]. Finally the \s matches whitespace characters. So overall pattern matches all strings of the form AA, 1A, 11 and so on. Note that there is a space after each of those.

Body:
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())

example on how the file with the strings looks

SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]

Basically I want to extract the numbers

Body:
This is a simple regex problem if your data is now how you have shown then you can solve this with regex pretty simply.

import re

numbers = re.compile("[\d|\w]{2}\s")
just_numbers = []
for line in data:
    just_numbers.append(" ".join([x.strip() for x in numbers.findall(line)]))

print(just_numbers)

Output

['12 3F 56 7D', '3C 53 25 25', '32 12 H2 3G']

In [\d|\w]{2}\s the [\d|\w] matches on characters that are either letters or numbers, so 0-9a-z-A-Z. Then the {2} after it means I want strings that are exactly two characters matching the previous pattern (aka [\d|\w]. Finally the \s matches whitespace characters. So overall pattern matches all strings of the form AA, 1A, 11 and so on. Note that there is a space after each of those.


问:
Open batch file php
Before everyone starts butting in with "security risks" "cant be done" stop there and read the ENTIRE post

I have a web server set up from a home laptop which is serving as a games web server im trying to create a GUI so its easier for us to maintain the server and im trying to use batch files to do the actions on the computer

So to put this into perspective I have my index file index.php

<form method="post">
  <input type="submit" name="startServer" value="Start Server">
</form>

<?
  if(isset($_POST['startServer'])){
    exec('batch/startServer.bat');
  }
?>
```

And my startServer.bat will run on the laptop running the server and will do all the actions nesscary to start our game server so there is another directory "Instance" containing an excutable "Server.exe" which the batch file will run

The issue im having is running the web server and testing this it doesnt work if I open the batch file directly it works but it seems the php code doesnt work

For clarification I am using apache and my browser is chrome

And just a quick question for anyone willing to answer the route im going is correct right? Using php would allow everything to run on the machine hosting the server so the end user will only see the GUI and the server would run the batch files and everything on the web server and not the local machine if that makes sense?

EDIT: To be more clear about what's going on the function exec runs but it just hangs like the application is loading I need a solution that will actually open the application are my host computer for example if I wanted to open up notepad I press a button on the Web server and notepad will open on the computer

EDIT 2: I would like to note that I dont exactly need to use the exec function and I have tried all the answers to date 7/19/2017:3:45pm none are working if I do something on the sorts echo exec('start text.bat'); I will get a This is a test to show your batch is working and simply just have echo ..... in the batch file the main issue I am having is the server is not physically showing the opened file like displaying the GUI lets just take notepad for example

I can open notepad and get some return value as long as my batch file closes notepad once its finished running however the GUI for notepad is never displayed and thats very important

I read in a few articles about using apache as a service which im pretty sure I am but I do know that xaammp has suffiecient priveleges and I have checked the box that says "Allow apache to interact with desktop" however no GUI is popping up thats the main point I guess im trying to get across is I need to display the GUI not just open the file as a background service.

If it makes answering easier I am open to switching programming languages if theres one that can do what I want easier

答:
Your theory is correct, it will run on the server however you may have issues running applications directly from php (with this method afaik it does not detach from the PHP, and the webapp "hangs" while the application is running).

Make sure: return values are printed / logged. Just an

```<code><?php
  if(isset($_POST['startServer'])){
   echo exec('batch/startServer.bat');
  }
?>
</code>```

Could point you to the right direction. The exec function may have been disabled in your distribution.

Using

```<code><?php
</code>```

instead of

```<code><?
</code>```

is highly advised, by default short_tags are not enabled in most distributions (wamp, xamp, etc).

Set debug mode and print everything to get information about the problem:

```<code><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(isset($_POST['startServer'])){
   echo exec('batch/startServer.bat');
}
?>
</code>```

If you don't have any response, try a simple batch file with a "hello world" to test if it works.

Be aware, the rights and limitations are comes from the php environment, the batch file inherits the same rights running the PHP code / Apache (in case of mod_php)

Title: Open batch file php

Body:
Before everyone starts butting in with "security risks" "cant be done" stop there and read the ENTIRE post

I have a web server set up from a home laptop which is serving as a games web server im trying to create a GUI so its easier for us to maintain the server and im trying to use batch files to do the actions on the computer

So to put this into perspective I have my index file index.php

<form method="post">
  <input type="submit" name="startServer" value="Start Server">
</form>

<?
  if(isset($_POST['startServer'])){
    exec('batch/startServer.bat');
  }
?>

And my startServer.bat will run on the laptop running the server and will do all the actions nesscary to start our game server so there is another directory "Instance" containing an excutable "Server.exe" which the batch file will run

The issue im having is running the web server and testing this it doesnt work if I open the batch file directly it works but it seems the php code doesnt work

For clarification I am using apache and my browser is chrome

And just a quick question for anyone willing to answer the route im going is correct right? Using php would allow everything to run on the machine hosting the server so the end user will only see the GUI and the server would run the batch files and everything on the web server and not the local machine if that makes sense?

EDIT: To be more clear about what's going on the function exec runs but it just hangs like the application is loading I need a solution that will actually open the application are my host computer for example if I wanted to open up notepad I press a button on the Web server and notepad will open on the computer

EDIT 2: I would like to note that I dont exactly need to use the exec function and I have tried all the answers to date 7/19/2017:3:45pm none are working if I do something on the sorts echo exec('start text.bat'); I will get a This is a test to show your batch is working and simply just have echo ..... in the batch file the main issue I am having is the server is not physically showing the opened file like displaying the GUI lets just take notepad for example

I can open notepad and get some return value as long as my batch file closes notepad once its finished running however the GUI for notepad is never displayed and thats very important

I read in a few articles about using apache as a service which im pretty sure I am but I do know that xaammp has suffiecient priveleges and I have checked the box that says "Allow apache to interact with desktop" however no GUI is popping up thats the main point I guess im trying to get across is I need to display the GUI not just open the file as a background service.

If it makes answering easier I am open to switching programming languages if theres one that can do what I want easier

Body:
Your theory is correct, it will run on the server however you may have issues running applications directly from php (with this method afaik it does not detach from the PHP, and the webapp "hangs" while the application is running).

Make sure: return values are printed / logged. Just an

<?php
  if(isset($_POST['startServer'])){
   echo exec('batch/startServer.bat');
  }
?>

Could point you to the right direction. The exec function may have been disabled in your distribution.

Using

<?php

instead of

<?

is highly advised, by default short_tags are not enabled in most distributions (wamp, xamp, etc).

Set debug mode and print everything to get information about the problem:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(isset($_POST['startServer'])){
   echo exec('batch/startServer.bat');
}
?>

If you don't have any response, try a simple batch file with a "hello world" to test if it works.

Be aware, the rights and limitations are comes from the php environment, the batch file inherits the same rights running the PHP code / Apache (in case of mod_php)


问:
Kube-dns does not resolve external hosts on kubeadm bare-metal cluster
I've got a k8n cluster setup on a bare-metal ubuntu 16.04 cluster using weave networking with kubeadm.  I'm having a variety of little problems, the most recent of which is that I realized that kube-dns does not resolve external addresses (e.g. google.com).  Any thoughts on why?  Using kube-adm did not give me a lot of insight into the details of that part of the setup.</p>

答:
I had the same issue on kubernetes v1.6 and it was not a firewall issue in my case.

The problem was that I have configured the DNS manually on the /etc/docker/daemon.json, and these parameters are not used by kube-dns. Instead it is needed to create a configmap for kubedns (pull request here and documentation here), as follows:

Solution

Create a yaml for the configmap, for example kubedns-configmap.yml

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-dns
  namespace: kube-system
data:
  upstreamNameservers: |
    ["<own-dns-ip>"]
</code>```

And simply, apply it on kubernetes with

```<code>kubectl apply -f kubedns-configmap.yml
</code>```

Test 1

On your kubernetes host node:

```<code>dig @10.96.0.10 google.com
</code>```

Test 2

To test it I use a busybox image with the following resource configuration (busybox.yml):

```<code>apiVersion: v1
kind: Pod
metadata:
    name: busybox
spec:
    containers:
    # for arm
    #- image: hypriot/armhf-busybox
    - image: busybox
      command:
          - sleep
          - "3600"
      imagePullPolicy: IfNotPresent
      name: busybox
    restartPolicy: Always
</code>```

Apply the resource with

```<code>kubectl apply -f busybox.yml
</code>```

And test it with the following:

```<code>kubectl exec -it busybox -- ping google.com
</code>```

Body:
I had the same issue on kubernetes v1.6 and it was not a firewall issue in my case.

The problem was that I have configured the DNS manually on the /etc/docker/daemon.json, and these parameters are not used by kube-dns. Instead it is needed to create a configmap for kubedns (pull request here and documentation here), as follows:

Solution

Create a yaml for the configmap, for example kubedns-configmap.yml

apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-dns
  namespace: kube-system
data:
  upstreamNameservers: |
    ["<own-dns-ip>"]

And simply, apply it on kubernetes with

kubectl apply -f kubedns-configmap.yml

Test 1

On your kubernetes host node:

dig @10.96.0.10 google.com

Test 2

To test it I use a busybox image with the following resource configuration (busybox.yml):

apiVersion: v1
kind: Pod
metadata:
    name: busybox
spec:
    containers:
    # for arm
    #- image: hypriot/armhf-busybox
    - image: busybox
      command:
          - sleep
          - "3600"
      imagePullPolicy: IfNotPresent
      name: busybox
    restartPolicy: Always

Apply the resource with

kubectl apply -f busybox.yml

And test it with the following:

kubectl exec -it busybox -- ping google.com


问:
java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex
I am not sure what this error means.

```<code>Execution failed for task ':excelSior:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: android/support/v4/util/TimeUtils.class
</code>```

I am currently using android-support-v4.jar for my libraries

```<code>dependencies {
    compile project(':addThisSDK')
    compile project(':centeredContentButton')
    compile project(':googleplayservices_lib')
    compile files('libs/adxtag2.4.6.jar')
    compile files('libs/android-support-v4.jar')
    compile files('libs/aws-android-sdk-1.7.1.1-debug.jar')
    compile files('libs/commons-lang-2.6.jar')
    compile files('libs/crittercism_v4_4_0_sdkonly.jar')
    compile files('libs/dd-plist.jar')
    compile files('libs/FiksuAndroidSDK_4.1.1.jar')
    compile files('libs/iqengines-sdk-barcode.jar')
    compile files('libs/irEventTracker-1.2.jar')
    compile files('libs/jolt-core-0.0.7.jar')
    compile files('libs/json-utils-0.0.7.jar')
    compile files('libs/jsoup-1.7.2.jar')
    compile files('libs/kooaba-api-v4-java.jar')
    compile 'com.android.support:multidex:1.0.0'
}
</code>```

Error does not show up during gradle sync. Just when I try to run the application

What could be the problem?

答:
This problem cost me one whole day. I finally downgraded the firebase-ui library version from 2.0.0 to 1.2.0 and added the following code inside Project level build.gradle file:</p>

```<code>allprojects {
    repositories {
        jcenter()

        // Add the following code to your project level build.gradle
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
I am not sure what this error means.

Execution failed for task ':excelSior:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: android/support/v4/util/TimeUtils.class

I am currently using android-support-v4.jar for my libraries

dependencies {
    compile project(':addThisSDK')
    compile project(':centeredContentButton')
    compile project(':googleplayservices_lib')
    compile files('libs/adxtag2.4.6.jar')
    compile files('libs/android-support-v4.jar')
    compile files('libs/aws-android-sdk-1.7.1.1-debug.jar')
    compile files('libs/commons-lang-2.6.jar')
    compile files('libs/crittercism_v4_4_0_sdkonly.jar')
    compile files('libs/dd-plist.jar')
    compile files('libs/FiksuAndroidSDK_4.1.1.jar')
    compile files('libs/iqengines-sdk-barcode.jar')
    compile files('libs/irEventTracker-1.2.jar')
    compile files('libs/jolt-core-0.0.7.jar')
    compile files('libs/json-utils-0.0.7.jar')
    compile files('libs/jsoup-1.7.2.jar')
    compile files('libs/kooaba-api-v4-java.jar')
    compile 'com.android.support:multidex:1.0.0'
}

Error does not show up during gradle sync. Just when I try to run the application

What could be the problem?

Body:
This problem cost me one whole day. I finally downgraded the firebase-ui library version from 2.0.0 to 1.2.0 and added the following code inside Project level build.gradle file:

allprojects {
    repositories {
        jcenter()

        // Add the following code to your project level build.gradle
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
How to Find All TRUE Conditions and Concatenate Corresponding Variables into New Variable?
```<code>a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}
</code>```

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

答:
Using numeric comparison operators as well as logical AND ("&&"), the following C code finds all true conditions while obviating the need for a new variable as it  efficiently uses text1, text2 and text3.  Note, the result avoids any duplicate output:

```<code>#include <stdio.h>
#include <string.h>

int main(void) {
int a = 4;
int b = 5;
int c = 7;

char text1[] = "a is high";
char text2[] = "b is high";
char text3[] = "c is high";

if ( a >= 4 && c < 6){
puts(text1);
}

if (b >= 8){
puts(text2);
}

if (c >= 6 && a < 4) {
puts(text3);
}

if( ( a >= 4 ) && ( c >= 6 ) ) {
strcat(text1," and ");
strcat(text1,text3);
puts(text1);
}

return 0;
}
</code>```

See demo

Body:
a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

Body:
Using numeric comparison operators as well as logical AND ("&&"), the following C code finds all true conditions while obviating the need for a new variable as it  efficiently uses text1, text2 and text3.  Note, the result avoids any duplicate output:

#include <stdio.h>
#include <string.h>

int main(void) {
int a = 4;
int b = 5;
int c = 7;

char text1[] = "a is high";
char text2[] = "b is high";
char text3[] = "c is high";

if ( a >= 4 && c < 6){
puts(text1);
}

if (b >= 8){
puts(text2);
}

if (c >= 6 && a < 4) {
puts(text3);
}

if( ( a >= 4 ) && ( c >= 6 ) ) {
strcat(text1," and ");
strcat(text1,text3);
puts(text1);
}

return 0;
}

See demo


问:
Sort by date ASC in qweb report odoo
I want sort data in my qweb report by date asc.

My example:

<t t-foreach="doc.line_ids" t-as="o">

</t>
```

答:
I've solved the problem with following code:

<t t-foreach="doc.line_ids.sorted(key=lambda x: x.date)" t-as="o">

</t>
```

Title: Sort by date ASC in qweb report odoo

Body:
I've solved the problem with following code:

<t t-foreach="doc.line_ids.sorted(key=lambda x: x.date)" t-as="o">
   <tr>
       <td class="text-right">
           <span t-field="o.date"/>
        </td>
   </tr>
</t>


问:
Search by title, abstract and author keywords boolean query
I try to search a general query in ieee search which is this ("data" AND "social media")

If I use this in the simple general search it works fine. However if I try to use specific criteria in order to search only in title or abstract or author keywords using this boolean query

```<code>("Publication Title":("data" AND "social media") OR "Abstract":("data" AND "social media") OR "Author Keywords":("data" AND "social media"))
</code>```

I can't take anything. Is there anything I make wrong in the process? How can I search in ieee search?

答:
I applied your query in the IEEE Digital Library and it returned me 17 research paper means your query is completely fine.

You query searches the word 'data' and 'social media' in publication title, Abstract and Author keywords.

There is also advance search in IEEE Xplore Digital Liberary in which you can perform search easily by searching it from either metadata or metadata and fulltext.

Body:
I try to search a general query in ieee search which is this ("data" AND "social media")

If I use this in the simple general search it works fine. However if I try to use specific criteria in order to search only in title or abstract or author keywords using this boolean query

("Publication Title":("data" AND "social media") OR "Abstract":("data" AND "social media") OR "Author Keywords":("data" AND "social media"))

I can't take anything. Is there anything I make wrong in the process? How can I search in ieee search?


问:
arrange data into special manner (3 in a row) with a show n fields button
I want to display my data coming from sql db to front end. I want it to be displayed in some special manner.

Lets assume I have 8 element in total. I want to display only 3 data field at first in a row, and below that a message saying 'show remaining 5'.
Once someone click that another three should load and below a message would show 'show remaining 1'.

I am not asking for a ..read more type option. I want to display remaining data into segments, but not all at once. If anyone can guide me, what can I use or if there is any useful plugin, I am already grateful.

Thanks in advance for anyone who put some effort.

答:
You need to provide more information, but im gonna answer according to what i understood.
First you need to put the data in a table using

.
Then you can hide the other 5 data fields using css, you can use visibility: hidden or display:none.

Then you can display a message using bootstrap alert class thats says 5 other fields remaining.

Body:
You need to provide more information, but im gonna answer according to what i understood.
First you need to put the data in a table using <table><tbody><tr></tr></tbody></table>.
Then you can hide the other 5 data fields using css, you can use visibility: hidden or display:none.

Then you can display a message using bootstrap alert class thats says 5 other fields remaining.


问:
How to cat two column (float) into a column quick and efficiency in pandas dataframe?
I want to get a new column by cat two column (float or int) as following shows,

So anyone have a better idea?

I think mine is something too complex

```<code>a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

答:
Use astype for convert to str:

```<code>#if need select columns by position with iloc
abc['new'] = abc.iloc[:,0].astype(str) + '::' + abc.iloc[:,1].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

```<code>#if need select by column names
abc['new'] = abc['a'].astype(str) + '::' + abc['b'].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

Solution with str.cat:

```<code>abc['new'] = abc['a'].astype(str).str.cat(abc['b'].astype(str), sep='::')
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

Body:
I want to get a new column by cat two column (float or int) as following shows,

So anyone have a better idea?

I think mine is something too complex

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

Body:
Use astype for convert to str:

#if need select columns by position with iloc
abc['new'] = abc.iloc[:,0].astype(str) + '::' + abc.iloc[:,1].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

#if need select by column names
abc['new'] = abc['a'].astype(str) + '::' + abc['b'].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

Solution with str.cat:

abc['new'] = abc['a'].astype(str).str.cat(abc['b'].astype(str), sep='::')
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10


问:
What are the best practices to encrypt passwords stored in MySql using PhP?
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

答:
Usually "salted" passwords (like with bcrypt) mean that not the password itself is stored, but only something like

```<code>   salt
   hash(salt with password appended)
</code>```

Now if the kiddie has your database (and of course, the code - there is no point in keeping the code secret), he/she can only guess passwords, calculate the salted hash, and compare. If the hash function is expensive (like bcrypt is), than guessing is expensive too.

Body:
Usually "salted" passwords (like with bcrypt) mean that not the password itself is stored, but only something like

   salt
   hash(salt with password appended)

Now if the kiddie has your database (and of course, the code - there is no point in keeping the code secret), he/she can only guess passwords, calculate the salted hash, and compare. If the hash function is expensive (like bcrypt is), than guessing is expensive too.


问:
Displaying Relation Links for @RestResource(exported = false)
I am using Spring Data Rest with Spring boot and I have somewhat odd situation.

We need our clients to be able to post one resource with all it's relations in one JSON object, so we made the relations as @RestResource( exported = false), this was the only solution we could find, the catch is we lose the links

We are now trying to create a projection of this resource with all its relations displayed as links

What we tried so far is to create a projection with the non-relation attributes added with getXXX() and then use a ResourceProcessor to handle the links as in this question, but we cannot seem to get it to work

Q: is this the best way to approach this? How can we add links to projections like normal resources?

UPDATE
so here is my Projection class

```<code>@Projection(name = "fullSP", types = {SP.class})
public interface FullSP {}
</code>```

and this is my Processor

```<code>@Component
public class FullSPResourceProcessor implements ResourceProcessor<Resource<FullSP>> {

private final EntityLinks entityLinks;

@Autowired
public FullSPResourceProcessor(EntityLinks entityLinks) {
    this.entityLinks = entityLinks;
}

@Override
public Resource<FullSP> process(Resource<FullSP> fullSPResource) {
    FullSP fullSP= fullSPResource.getId();
    fullSPResource.add(entityLinks.linkFor(Rate.class).withRel("rates"));
    return fullSPResource;
}
}
</code>```

but this doesn't work, this just adds a link to /rates as a resource not as a sub resource

答:
EntityLinks has no knowledge about the subresource link you want to generate - so you get the default top-level link.

I assume you do not have a custom controller for this subresource?! If you don't spring-data-rest will not expose a subresource in this case - because the target of the relation is not exported.

In this case, you would need a custom controller to expose this subresource. If you go this route you should use ControllerLinkBuilder to build this link. If you want to stick with EntityLinks you could do the following (for the link you would need the id - to get it it needs to be available on the projection):

```<code>fullSPResource.add(entityLinks.linkForSingleResource(SP.class, fullSPResource.getContent().getId()).slash("rates").withRel("rates"));
</code>```

Body:
I am using Spring Data Rest with Spring boot and I have somewhat odd situation.

We need our clients to be able to post one resource with all it's relations in one JSON object, so we made the relations as @RestResource( exported = false), this was the only solution we could find, the catch is we lose the links

We are now trying to create a projection of this resource with all its relations displayed as links

What we tried so far is to create a projection with the non-relation attributes added with getXXX() and then use a ResourceProcessor to handle the links as in this question, but we cannot seem to get it to work

Q: is this the best way to approach this? How can we add links to projections like normal resources?

UPDATE
so here is my Projection class

@Projection(name = "fullSP", types = {SP.class})
public interface FullSP {}

and this is my Processor

@Component
public class FullSPResourceProcessor implements ResourceProcessor<Resource<FullSP>> {

private final EntityLinks entityLinks;

@Autowired
public FullSPResourceProcessor(EntityLinks entityLinks) {
    this.entityLinks = entityLinks;
}

@Override
public Resource<FullSP> process(Resource<FullSP> fullSPResource) {
    FullSP fullSP= fullSPResource.getId();
    fullSPResource.add(entityLinks.linkFor(Rate.class).withRel("rates"));
    return fullSPResource;
}
}

but this doesn't work, this just adds a link to /rates as a resource not as a sub resource

Body:
EntityLinks has no knowledge about the subresource link you want to generate - so you get the default top-level link.

I assume you do not have a custom controller for this subresource?! If you don't spring-data-rest will not expose a subresource in this case - because the target of the relation is not exported.

In this case, you would need a custom controller to expose this subresource. If you go this route you should use ControllerLinkBuilder to build this link. If you want to stick with EntityLinks you could do the following (for the link you would need the id - to get it it needs to be available on the projection):

fullSPResource.add(entityLinks.linkForSingleResource(SP.class, fullSPResource.getContent().getId()).slash("rates").withRel("rates"));


问:
Giving wrong day of week in PHP
It is displaying Thursday but Wednesday output, please help me fix it.........

My code

```<code><?php
    date_default_timezone_set('Asia/Kolkata');
    $date = '2017/06/07';
    $weekday = date('l', strtotime($date));
    echo $weekday; //
?>
</code>```

Thanks in advance

答:
Try this:

```<code>date_default_timezone_set('Asia/Kolkata');
$date = '2017/06/07';
$date = str_replace('/','-', $date);
$weekday = date('l', strtotime($date));
echo $weekday;
// Output: Wednesday
</code>```

Phpfiddle link

Check the document here

Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking
  at the separator between the various components: if the separator is a
  slash (/), then the American m/d/y is assumed; whereas if the
  separator is a dash (-) or a dot (.), then the European d-m-y format
  is assumed. If, however, the year is given in a two digit format and
  the separator is a dash (-, the date string is parsed as y-m-d. To
  avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
  dates or DateTime::createFromFormat() when possible.

Title: Giving wrong day of week in PHP

Body:
It is displaying Thursday but Wednesday output, please help me fix it.........

My code

<?php
    date_default_timezone_set('Asia/Kolkata');
    $date = '2017/06/07';
    $weekday = date('l', strtotime($date));
    echo $weekday; //
?>

Thanks in advance

Body:
Try this:

date_default_timezone_set('Asia/Kolkata');
$date = '2017/06/07';
$date = str_replace('/','-', $date);
$weekday = date('l', strtotime($date));
echo $weekday;
// Output: Wednesday

Phpfiddle link

Check the document here

Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking
  at the separator between the various components: if the separator is a
  slash (/), then the American m/d/y is assumed; whereas if the
  separator is a dash (-) or a dot (.), then the European d-m-y format
  is assumed. If, however, the year is given in a two digit format and
  the separator is a dash (-, the date string is parsed as y-m-d. To
  avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
  dates or DateTime::createFromFormat() when possible.


问:
Layering canvas objects in Fabric.js
Is there a way to layer objects on a Fabric.js canvas via the official API? Right now the only way I have found to do it is to manually iterate through the canvas._objects and reorder them so that they get drawn in a specific order. Is there a better way to do this that doesn't (potentially) break the object?</p>

答:
If you want to set a specific ordering for all objects, instead of moving one object forward/backward, iterative calls to bring/send to front/back are slow.

You can use the code of bringToFront as inspiration to speed this use case up: https://github.com/kangax/fabric.js/blob/586e61dd282b22c1d50e15c0361875707e526fd8/src/static_canvas.class.js#L1468

And do this:

```<code>fabric.Canvas.prototype.orderObjects = function(compare) {
    this._objects.sort(compare);
    this.renderAll();
}
</code>```

Where compare defines the sorting, like:

```<code>function compare(x,y) {
    return x.getWidth() * x.getHeight() < y.getWidth() * y.getHeight();
}

some_canvas.orderObjects(compare)
</code>```

If you wish to bring smaller objects to the front.

Title: Layering canvas objects in Fabric.js

Body:
If you want to set a specific ordering for all objects, instead of moving one object forward/backward, iterative calls to bring/send to front/back are slow.

You can use the code of bringToFront as inspiration to speed this use case up: https://github.com/kangax/fabric.js/blob/586e61dd282b22c1d50e15c0361875707e526fd8/src/static_canvas.class.js#L1468

And do this:

fabric.Canvas.prototype.orderObjects = function(compare) {
    this._objects.sort(compare);
    this.renderAll();
}

Where compare defines the sorting, like:

function compare(x,y) {
    return x.getWidth() * x.getHeight() < y.getWidth() * y.getHeight();
}

some_canvas.orderObjects(compare)

If you wish to bring smaller objects to the front.


答:
You need to use date format "Y-m-d" to get the result you want.
 $date = '2017/06/07' means June 07, 2017.

If you want to get the day of July 06, 2017 then change

```<code>$date = '2017/06/07';
</code>```

To

```<code>$date = '2017/07/06';
</code>```

Title: Giving wrong day of week in PHP

Body:
You need to use date format "Y-m-d" to get the result you want.
 $date = '2017/06/07' means June 07, 2017.

If you want to get the day of July 06, 2017 then change

$date = '2017/06/07';

To

$date = '2017/07/06';


问:
How to add a toolbar at the bottom?
I'm trying to have my toolbar at the bottom. I already tried some tips but the toolbar rests at the top.

So: What do I have to change so my toolbar appears at the bottom?

If you need more code - there isn't much more - or other informations, just say so.

My XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

   <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</LinearLayout>
</code>```

And the .java:

```<code>package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    }

}
</code>```

Styles.xml:

```<code><resources>

    <!-- Base application theme. -->
    <!--<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!– Customize your theme here. –>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>-->

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar" />

</resources>
</code>```

Android Manifest:

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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <permission android:name="android.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=" API-Key (I removed mine)" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
</code>```

答:
You can use Relative layout like this,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/map"
              android:name="com.google.android.gms.maps.SupportMapFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_above="@+id/toolbar"
              tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

</RelativeLayout>
</code>```

Title: How to add a toolbar at the bottom?

Body:
I'm trying to have my toolbar at the bottom. I already tried some tips but the toolbar rests at the top.

So: What do I have to change so my toolbar appears at the bottom?

If you need more code - there isn't much more - or other informations, just say so.

My XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

   <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</LinearLayout>

And the .java:

package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    }

}

Styles.xml:

<resources>

Body:
You can use Relative layout like this,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/map"
              android:name="com.google.android.gms.maps.SupportMapFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_above="@+id/toolbar"
              tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

</RelativeLayout>


问:
GA: enhanced ecommerce checkout products
I m starting working on Enhanced Ecommerce Especially on the checkout process.
I am using this website as reference.

My question is in the checkout process, why we are obliged to send in every step the entire cart (all the products)?

答: The technical reason is that, if every step of your checkout is a different page, there is no persistence between pages, so it's your responsibility to push the products on each step. Google Analytics could have technically done this persistence on the server side, but that would mean more work (and memory) for GA servers. Also, sometimes you want to add extra info (in the form of custom dimensions or metrics) but only for specific checkout steps, so this wouldn't really be possible if GA just "remembered" the products for you.


问:
Prevent TYPO3 CMS from expanding added media relation per default
Is it possible to configure TYPO3 CMS to prevent it from expanding a media relation which is added to a page by default? Now each time a new media relation is added the detail view will be expanded.

I have checked the TSconfig docs and the install tool settings, but I did not find any related documentation or any similar question here on Stack Overflow.

答:
As far as I can see from the code there is no possibility to do that.
The options Riccardo mentioned in the comment only work when opening a record with existing relations.

Your case (creating new relation) is handled via typo3/sysext/backend/Classes/Controller/FormInlineAjaxController.php

in combination with

web/typo3/sysext/backend/Resources/Public/JavaScript/jsfunc.inline.js -> inline.domAddNewRecord

there are no options to prevent expansion - only collapsing all other elements is possible (via expandSingle TCA configuration).


问:
How to call ModelCheckpoint (or any callback) explicitly in Keras?
My ModelCheckpoint is intended to save model each epoch. Unfortunately, I don't use built-in epochs of Model.

How to call ModelCheckpoint not via callback, but explicitly, when my code ends epoch, so that it does all it's job?

I found method on_epoch_end, but can't figure out, where to pass model itself?

答: Each callback is derived from Callback abstract base class. It has set_model method which is used to pass the corresponding model. Check it in callbacks.py


问:
Query division returns 0
I am working on a query that devide 2 columns, I tried CAST and CONVERT but still returns 0. Will apperciate your help

```<code>SELECT a.Disposition,a.[Disposition Reason Breakdown],a.CSP,b.Total FROM
(
SELECT a.[Disposition],a.[Disposition Reason Breakdown],a.[CSP] FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
) a
)a
INNER JOIN
(
SELECT a.Disposition,SUM(a.CSP) as Total FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
)a
GROUP BY a.Disposition
)b ON a.Disposition = b.Disposition
</code>```

I am using sql

答: I solved it, it turns out that I just used the wrong data type which in my case is decimal I should've thought of REAL here is the final query a.CSP/CAST(b.Total as REAL)

Title: Query division returns 0

Body:
I am working on a query that devide 2 columns, I tried CAST and CONVERT but still returns 0. Will apperciate your help

SELECT a.Disposition,a.[Disposition Reason Breakdown],a.CSP,b.Total FROM
(
SELECT a.[Disposition],a.[Disposition Reason Breakdown],a.[CSP] FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
) a
)a
INNER JOIN
(
SELECT a.Disposition,SUM(a.CSP) as Total FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
)a
GROUP BY a.Disposition
)b ON a.Disposition = b.Disposition

I am using sql


问:
SectionList - Animate on Section Press
We were asked to implement a screen for our app where there would be some data in the form of a list and sections for each data category. When a Section header is pressed, the section data should be expanded or collapsed.

At first, i tried with Listview, and i was changing the datasource each time a header was pressed, but tbh it did not feel like the correct way of doing it.

Creating a custom view, an animating the view's height works ok, but because of the volume of the data, which is big, the initial rendering is a bit slow e.g. there is a noticeable delay when navigating to the screen.

After upgrading to RN 44.3 i was wondering if i could use Sectionlist in a better way than listview.

Generally what's the best way of approaching a requirement like this?

Thanks!

答:
You can animate the items in flatlist/SectionList.  A smaple code will look like below (Animates on removing items). You can use same logic for section list as well.

```<code>onRemove = () => {
  const { onRemove } = this.props;
  if (onRemove) {
    Animated.timing(this._animated, {
      toValue: 0,
      duration: ANIMATION_DURATION,
    }).start(() => onRemove());
  }
};
</code>```

Refer this link for more details.

Title: SectionList - Animate on Section Press

Body:
You can animate the items in flatlist/SectionList.  A smaple code will look like below (Animates on removing items). You can use same logic for section list as well.

onRemove = () => {
  const { onRemove } = this.props;
  if (onRemove) {
    Animated.timing(this._animated, {
      toValue: 0,
      duration: ANIMATION_DURATION,
    }).start(() => onRemove());
  }
};

Refer this link for more details.


答:
This sounds like something that would be done by JavaScript. This means building the whole table right away, but hiding all but the top 3 rows. Then hook a function to the "Show three more" button, that displays three more rows (until all is shown).

jQuery is a JavaScript library that is easy to get into and would help you get this kind of functionality going, but it is of course entirely possible to do without it.

If you are entirely new to web development with php, sql, html, and javascript I suggest looking at basic tutorials on how to accomplish the basics first, such as fetching data from a db, displaying that in html and how to modify the DOM with javascript.

Title: arrange data into special manner (3 in a row) with a show n fields button

Body:
I want to display my data coming from sql db to front end. I want it to be displayed in some special manner.

Lets assume I have 8 element in total. I want to display only 3 data field at first in a row, and below that a message saying 'show remaining 5'.
Once someone click that another three should load and below a message would show 'show remaining 1'.

I am not asking for a ..read more type option. I want to display remaining data into segments, but not all at once. If anyone can guide me, what can I use or if there is any useful plugin, I am already grateful.

Thanks in advance for anyone who put some effort.


答:
It's simple

```<code>store(sha256("somesalt" + password));
</code>```

And nobody will be able to reverse it :)

See also: https://stackoverflow.com/questions/3897434/password-security-sha1-sha256-or-sha512

Title: What are the best practices to encrypt passwords stored in MySql using PhP?

Body:
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

Body:
It's simple

store(sha256("somesalt" + password));

And nobody will be able to reverse it :)

See also: https://stackoverflow.com/questions/3897434/password-security-sha1-sha256-or-sha512


问:
WPF Image.Source does nothing
I've been trying to set the Image.Source in the code behind to a relative path like this:

```<code>IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));
</code>```

If I use a non existing path, the program crashes.

But this path exists and works just like that as a .Fill in a Rectangle.
Whats wrong here ?

答:
If the image files are located in a folder structure that is relative to the path of your application's executable assembly, you should load them by Content File Pack URIs like this:</p>

```<code>try
{
    IMG_3.Source = new BitmapImage(
        new Uri("pack://application:,,,/Sprites/Layout/image1.png"));
}
catch
{
    IMG_3.Source = fallbackImage;
}
</code>```

Title: WPF Image.Source does nothing

Body:
I've been trying to set the Image.Source in the code behind to a relative path like this:

IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));

If I use a non existing path, the program crashes.

But this path exists and works just like that as a .Fill in a Rectangle.
Whats wrong here ?

Body:
If the image files are located in a folder structure that is relative to the path of your application's executable assembly, you should load them by Content File Pack URIs like this:

try
{
    IMG_3.Source = new BitmapImage(
        new Uri("pack://application:,,,/Sprites/Layout/image1.png"));
}
catch
{
    IMG_3.Source = fallbackImage;
}


问:
TimePickerDialog and AM or PM
I have a TimePickerDialog  with is24Hour set to false since I want to present the end-user with the more familiar 12 hour format. When the hour, minute and AM PM indicator are set and the time is returned how can I identify whether the end-user has selected AM or PM?

This is what I have for the listener:

```<code>private TimePickerDialog.OnTimeSetListener mTimeSetListener =
      new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay,
      int minute) {
     mHour = hourOfDay;
     mMinute = minute;
    // mIsAM = WHERE CAN I GET THIS VALUE
    }
};
</code>```

答:
You can try my solution, I used "hh:mm a" format to set AM/PM time:

```<code>SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
String  formattedTime = formatter.format(myCalendar.getTime());
EditText.setText(formattedTime);
</code>```

Title: TimePickerDialog and AM or PM

Body:
I have a TimePickerDialog  with is24Hour set to false since I want to present the end-user with the more familiar 12 hour format. When the hour, minute and AM PM indicator are set and the time is returned how can I identify whether the end-user has selected AM or PM?

This is what I have for the listener:

private TimePickerDialog.OnTimeSetListener mTimeSetListener =
      new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay,
      int minute) {
     mHour = hourOfDay;
     mMinute = minute;
    // mIsAM = WHERE CAN I GET THIS VALUE
    }
};

Body:
You can try my solution, I used "hh:mm a" format to set AM/PM time:

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
String  formattedTime = formatter.format(myCalendar.getTime());
EditText.setText(formattedTime);


问:
Ruby query need to update
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

```<code>User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}
</code>```

Results as below:

```<code> [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]
</code>```

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

答:
You could join the simas model and the user model</p>

```<code>User.joins("JOIN simas ON simas.user_id = users.id")
    .where(primary_partner_id: 2, "simas.status": 'accepted')
    .map{|a| a.sima}
</code>```

Title: Ruby query need to update

Body:
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}

Results as below:

 [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

Body:
You could join the simas model and the user model

User.joins("JOIN simas ON simas.user_id = users.id")
    .where(primary_partner_id: 2, "simas.status": 'accepted')
    .map{|a| a.sima}


问:
How to use "Enter" key insted of "Tab" key in openerp 7 for one2many field
I am working in sale order line and currently by pressing "Enter" key in one2many field it is creating new line, but I want to do some changes so Enter key work as TAB key ,It means if I pressed Enter key then insted of creating new line it should focus on next field of one2many.

Example:

There are 4 fields in one line so when I pressed enter key it should switch to next field in same line insted of creating new line.

答:
I am giving answer to my question .. Actually I tried and found one solution from the following link:

From odoo forum

There are some issue which I found in that answer but didn't able to solve that :(

Issues are:

(1) I make change in base model of web in that "view_list_editable.js" as                              told in this link insted of my custom model.

(2) Also when any read-only fields is there in between One2Many visible fields then this solution is not working..


问:
How to remove duplicates from a comboBox
I'm reading strings from a text file to populate the options in a dialog box. The issue is that I need to remove duplicate values in the list. I'm working on Visual C++. I'm using Visual Studio 2008.</p>

答: When you read the items from the text file use a map. it will eliminate all the duplicate entries and add the map entries into the list</p>


问:
Assigning value to undefined in JavaScript
I was writing some code in JavaScript. When I accidentally came across this.

```<code>undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error
</code>```

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

答:
I quote directly from the MD Js docs.

While it is possible to use it as an identifier (variable name) in any
  scope other than the global scope (because undefined is not a reserved
  word), doing so is a very bad idea that will make your code difficult
  to maintain and debug.

```<code>//DON'T DO THIS

// logs "foo string"
(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();

// logs "foo string"
(function(undefined) { console.log(undefined, typeof undefined); })('foo');
</code>```

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined

Body:
I was writing some code in JavaScript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

Body:
I quote directly from the MD Js docs.

While it is possible to use it as an identifier (variable name) in any
  scope other than the global scope (because undefined is not a reserved
  word), doing so is a very bad idea that will make your code difficult
  to maintain and debug.

//DON'T DO THIS

// logs "foo string"
(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();

// logs "foo string"
(function(undefined) { console.log(undefined, typeof undefined); })('foo');

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined