问:
Cannot convert content scheme uri to file path
I put .jpg , .pdf , .docx , .xlx , .mp3 , .mp4  type of fine on same location of sd-card (External memory card)

When i try to choose file then i able to choose only .jpg , .pdf file other type of file not choosen

Chosen file :->

```<code> 1.path : `/storage/emulated/0/123.pdf`  (from this path i successfully attached file)
 2. path : `/storage/emulated/0/Program.docx`
 3. path : `/storage/emulated/0/ApiCalling.mp4`
</code>```

Error is :

file are not exists.. when i get 2. and 3. number of path

Code is :

```<code> public static void showFileChooser(Context context) {
    PICK_IMAGE_REQUEST = 2;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        ((Activity) context).startActivityForResult(
                Intent.createChooser(intent, context.getResources().getString(R.string.select_file_msg)),
                PICK_IMAGE_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
       e.print();
    }
}
</code>```

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
         try {
                String path = Utility.getRealPathFromURI(this, uri);
                Log.e("path -> ",path);
                File f = new File(path);
                if (f.exists()) {
                }
                else
                {
                    Log.e("err -> ","file not exists");
                }
            }
    }
</code>```

```<code>public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (uri != null) {
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    }

    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}
</code>```

答:
Try this

```<code>Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("*/*"); //set mime type as per requirement
startActivityForResult(mediaIntent,REQUESTCODE_PICK_FILE);
</code>```

Then you can get path in onActivityResult

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUESTCODE_PICK_FILE
            && resultCode == Activity.RESULT_OK) {
        Uri videoUri = data.getData();
        Log.d("", "Video URI= " + videoUri);

    }
}
</code>```

Body:
I put .jpg , .pdf , .docx , .xlx , .mp3 , .mp4  type of fine on same location of sd-card (External memory card)

When i try to choose file then i able to choose only .jpg , .pdf file other type of file not choosen

Chosen file :->

 1.path : `/storage/emulated/0/123.pdf`  (from this path i successfully attached file)
 2. path : `/storage/emulated/0/Program.docx`
 3. path : `/storage/emulated/0/ApiCalling.mp4`

Error is :

file are not exists.. when i get 2. and 3. number of path

Code is :

 public static void showFileChooser(Context context) {
    PICK_IMAGE_REQUEST = 2;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        ((Activity) context).startActivityForResult(
                Intent.createChooser(intent, context.getResources().getString(R.string.select_file_msg)),
                PICK_IMAGE_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
       e.print();
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
         try {
                String path = Utility.getRealPathFromURI(this, uri);
                Log.e("path -> ",path);
                File f = new File(path);
                if (f.exists()) {
                }
                else
                {
                    Log.e("err -> ","file not exists");
                }
            }
    }

public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (uri != null) {
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    }

    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

Body:
Try this

Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("*/*"); //set mime type as per requirement
startActivityForResult(mediaIntent,REQUESTCODE_PICK_FILE);

Then you can get path in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUESTCODE_PICK_FILE
            && resultCode == Activity.RESULT_OK) {
        Uri videoUri = data.getData();
        Log.d("", "Video URI= " + videoUri);

    }
}


来源: stackexchange

问:
How to fix the div while scrolling using jQuery?
I am facing problem to fix a div when scrolling, actually I have the fix the div at right of the page below header content, it is fixed but when we scroll up it is placed above the header content.

jQuery(function($) {
  function fixDiv() {
    var $cache = $('#getFixed');
    if ($(window).scrollTop() > 100)
      $cache.css({
        'position': 'fixed',
        'top': '0'
      });
    else
      $cache.css({
        'position': 'static'
      });
  }

  $(window).scroll(fixDiv);
  fixDiv();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#getFixed {
  position: fixed;
  top: 0;
  width: 5%;
}</code>```

rerkjehglrjgnb

        Upgradasfddddddddddddddddddddd
 Starting at just $15

        Viewplans

```

答:
Try this:

```<code>#getFixed{
  position: fixed;
}
</code>```

Working Fiddle

ContentLicense: CC BY-SA 3.0

Body:
I am facing problem to fix a div when scrolling, actually I have the fix the div at right of the page below header content, it is fixed but when we scroll up it is placed above the header content.

jQuery(function($) {
  function fixDiv() {
    var $cache = $('#getFixed');
    if ($(window).scrollTop() > 100)
      $cache.css({
        'position': 'fixed',
        'top': '0'
      });
    else
      $cache.css({
        'position': 'static'
      });
  }

  $(window).scroll(fixDiv);
  fixDiv();
});

#getFixed {
  position: fixed;
  top: 0;
  width: 5%;
}

rerkjehglrjgnb

        Upgradasfddddddddddddddddddddd
 Starting at just $15

        Viewplans

Body:
Try this:

#getFixed{
  position: fixed;
}

Working Fiddle


问:
Why does the input value in EditText swaps its position while scrolling in a RecyclerView?
After putting an input in the EditText, if a scroll up or down very fast the input values swaps its position in another EditText in a RecyclerView.

Before scrolling the data was in the first EditText.

After scrolling up and down the value of the first EditText changed its postion to the 4th one and the swapping is random. Is there any work around to steady the data.

Here is a sample screenshot

Here is the Model Class:

```<code>public class Product {
    public int pId;
    public String pName;
    public double unit_price;
    public double discount;
}
</code>```

Here is the adapter Class:

```<code>public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductListHolder> {
Context context;
List<Product> productList;

public ProductAdapter(Context c, List<Product> lp){
    this.context = c;
    this.productList = lp;
}

public class ProductListHolder extends RecyclerView.ViewHolder{
    TextView tvName;
    TextView tvPrice;
    TextView tvDiscount;
    TextView tvTotal;
    EditText etQuantity;
    public ProductListHolder(View itemView) {
        super(itemView);
        tvName = (TextView) itemView.findViewById(R.id.tvName);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        tvDiscount = (TextView) itemView.findViewById(R.id.tvDiscount);
        tvTotal = (TextView) itemView.findViewById(R.id.tvTotal);
        etQuantity = (EditText) itemView.findViewById(R.id.etQuantity);
    }
}

@Override
public ProductListHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_row, viewGroup, false);
    ProductListHolder ph = new ProductListHolder(v);
    return  ph;
}

@Override
public void onBindViewHolder(final ProductListHolder productListHolder, final int i) {
    productListHolder.tvName.setText(productList.get(i).pName);
    productListHolder.tvPrice.setText(String.valueOf(productList.get(i).unit_price));
    productListHolder.tvDiscount.setText(String.valueOf(productList.get(i).discount));

    productListHolder.etQuantity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals("")){
                double totalPrice = (productList.get(i).unit_price-productList.get(i).discount)* (Double.valueOf(s.toString()));
                productListHolder.tvTotal.setText(String.valueOf(totalPrice));
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

@Override
public int getItemCount() {
    return productList.size();
}
</code>```

}

Here is the MainActivity:

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

List<Product> productList;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;

String[] names = {"A", "B", "C","D"};
double[] prices = {1000, 2000, 3000, 100};
double[] discounts = {10, 20, 30, 2};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initRecyclerView(); // Initializing Recycler View
    new MyTask().execute();
}

public void initRecyclerView(){
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}

private class MyTask extends AsyncTask<Void, Void, List<Product>> {

    @Override
    protected List<Product> doInBackground(Void... params) {
        int sz = 24;
        productList = new ArrayList<Product>();
        for(int i=0; i<sz; i++){
            Product p = new Product();
            p.pId = i%4;
            p.pName = names[i%4];
            p.unit_price = prices[i%4];
            p.discount = discounts[i%4];
            productList.add(p);
        }

        return productList;
    }

    @Override
    protected void onPostExecute(List<Product> products) {
        super.onPostExecute(products);
        mAdapter = new ProductAdapter(MainActivity.this, productList);
        recyclerView.setAdapter(mAdapter);
    }
  }
}
</code>```

答:
Simple fix:

Replace mFieldAdapter.notifyDataSetChanged(); with:

```<code>for (int i = 0; i < mFieldAdapter.getItemCount(); i++) {
    // update each item itself
    mFieldAdapter.notifyItemChanged(i, fields.get(i));
}
</code>```

Demo: https://youtu.be/4JpzuLggBV0

Body:
After putting an input in the EditText, if a scroll up or down very fast the input values swaps its position in another EditText in a RecyclerView.

Before scrolling the data was in the first EditText.

After scrolling up and down the value of the first EditText changed its postion to the 4th one and the swapping is random. Is there any work around to steady the data.

Here is a sample screenshot

Here is the Model Class:

public class Product {
    public int pId;
    public String pName;
    public double unit_price;
    public double discount;
}

Here is the adapter Class:

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductListHolder> {
Context context;
List<Product> productList;

public ProductAdapter(Context c, List<Product> lp){
    this.context = c;
    this.productList = lp;
}

public class ProductListHolder extends RecyclerView.ViewHolder{
    TextView tvName;
    TextView tvPrice;
    TextView tvDiscount;
    TextView tvTotal;
    EditText etQuantity;
    public ProductListHolder(View itemView) {
        super(itemView);
        tvName = (TextView) itemView.findViewById(R.id.tvName);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        tvDiscount = (TextView) itemView.findViewById(R.id.tvDiscount);
        tvTotal = (TextView) itemView.findViewById(R.id.tvTotal);
        etQuantity = (EditText) itemView.findViewById(R.id.etQuantity);
    }
}

@Override
public ProductListHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_row, viewGroup, false);
    ProductListHolder ph = new ProductListHolder(v);
    return  ph;
}

@Override
public void onBindViewHolder(final ProductListHolder productListHolder, final int i) {
    productListHolder.tvName.setText(productList.get(i).pName);
    productListHolder.tvPrice.setText(String.valueOf(productList.get(i).unit_price));
    productListHolder.tvDiscount.setText(String.valueOf(productList.get(i).discount));

    productListHolder.etQuantity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals("")){
                double totalPrice = (productList.get(i).unit_price-productList.get(i).discount)* (Double.valueOf(s.toString()));
                productListHolder.tvTotal.setText(String.valueOf(totalPrice));
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

@Override
public int getItemCount() {
    return productList.size();
}

}

Here is the MainActivity:

public class MainActivity extends AppCompatActivity {

List<Product> productList;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;

String[] names = {"A", "B", "C","D"};
double[] prices = {1000, 2000, 3000, 100};
double[] discounts = {10, 20, 30, 2};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initRecyclerView(); // Initializing Recycler View
    new MyTask().execute();
}

public void initRecyclerView(){
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}

private class MyTask extends AsyncTask<Void, Void, List<Product>> {

    @Override
    protected List<Product> doInBackground(Void... params) {
        int sz = 24;
        productList = new ArrayList<Product>();
        for(int i=0; i<sz; i++){
            Product p = new Product();
            p.pId = i%4;
            p.pName = names[i%4];
            p.unit_price = prices[i%4];
            p.discount = discounts[i%4];
            productList.add(p);
        }

        return productList;
    }

    @Override
    protected void onPostExecute(List<Product> products) {
        super.onPostExecute(products);
        mAdapter = new ProductAdapter(MainActivity.this, productList);
        recyclerView.setAdapter(mAdapter);
    }
  }
}

Body:
Simple fix:

Replace mFieldAdapter.notifyDataSetChanged(); with:

for (int i = 0; i < mFieldAdapter.getItemCount(); i++) {
    // update each item itself
    mFieldAdapter.notifyItemChanged(i, fields.get(i));
}

Demo: https://youtu.be/4JpzuLggBV0


问:
How do I bind context to event handler so event and a few more arguments passed to handler function
I have a function:

```<code>function clickButton(event, someArgument) {...}
</code>```

And I need to pass it as event handler in my React component. I'm trying to do something like this:

```<code>onClick={clickButton.bind(this, event, someArgument)}
</code>```

But event is not defined that is predictable.

There should be some trivial solution.

答:
Just write onClick={clickButton.bind(this)}, the event will be passed as argument to clickButton

See React synthetic event

Body:
I have a function:

function clickButton(event, someArgument) {...}

And I need to pass it as event handler in my React component. I'm trying to do something like this:

onClick={clickButton.bind(this, event, someArgument)}

But event is not defined that is predictable.

There should be some trivial solution.


问:
String.toUpperCase may strip accents or not
I have to apply toUpperCase on a name that may contain accents ("é", "à", etc.).

Problem:

with JUnit, "é".toUpperCase converts to "E", the accent is removed

in my application (a Spring REST API), "é".toUpperCase converts to "É". The input comes from an Ember frontend, but the encoding is the same (UTF-8)

JUnit tests and Spring application use the same characters set (UTF-8) and the locale is French. Both running on Oracle Java 8, on the same machine (Jenkins CI on Debian, but I can reproduce this behavior on my computer: Windows 7).

I tried to specify the locale toUpperCase(Locale.FRANCE), but it doesn't solve my problem.

Are you aware of something that may explain this difference?

答:
I had the same problem once and it was fixed for me by setting the default Locale:</p>

```<code>Locale.setDefault(new Locale("fr_FR"));
</code>```

Body:
I had the same problem once and it was fixed for me by setting the default Locale:

Locale.setDefault(new Locale("fr_FR"));


问:
Material changes from editor script are lost on save
I am changing a material texture in an editor script. Once run, I can see the changes in the editor window, but when I save my scene or hit play, the changes are lost.

Here is my code:

```<code>var mySkyBox = Resources.Load<Material>("Materials/MySkyBox");
Undo.RecordObject(mySkyBox, "setting mySkyBox texture");
var texture = new Texture2D(2, 2);
texture.LoadImage(File.ReadAllBytes("texturePath"));
mySkyBox.SetTexture("_UpTex", texture);
EditorUtility.SetDirty(mySkyBox);
</code>```

I have also tried using LoadMainAssetAtPath to load the material but that does not work either.

I am using Unity 5.3.7f1

How I can correctly edit a material in an editor script and have the changes persist?

答:
```<code>Material tempSkyBox = Resources.Load<Material>("Materials/MySkyBox");
// this will make a copy from the loaded material

tempSkyBox.SetTexture("_MainTex",(Texture2D) AssetDatabase.LoadAssetAtPath("texturePath", typeof(Texture2D)));
// Sets the main texture on the copy of the material that you just made
// Make sure that the image file is located somewhere in the unityproject folder

AssetDatabase.CreateAsset(tempSkyBox, "materialPath" + "/mySkybox.mat");
// Saves the copy of the material to the disk

AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// force the editor to update the AssetsFolder

myCamera.GetComponentInChildren<Skybox>().material = tempSkyBox;
// Sets the reference
</code>```

this method worked for me in one of my projects
Good luck ^^

Body:
I am changing a material texture in an editor script. Once run, I can see the changes in the editor window, but when I save my scene or hit play, the changes are lost.

Here is my code:

var mySkyBox = Resources.Load<Material>("Materials/MySkyBox");
Undo.RecordObject(mySkyBox, "setting mySkyBox texture");
var texture = new Texture2D(2, 2);
texture.LoadImage(File.ReadAllBytes("texturePath"));
mySkyBox.SetTexture("_UpTex", texture);
EditorUtility.SetDirty(mySkyBox);

I have also tried using LoadMainAssetAtPath to load the material but that does not work either.

I am using Unity 5.3.7f1

How I can correctly edit a material in an editor script and have the changes persist?

Body:
Material tempSkyBox = Resources.Load<Material>("Materials/MySkyBox");
// this will make a copy from the loaded material

tempSkyBox.SetTexture("_MainTex",(Texture2D) AssetDatabase.LoadAssetAtPath("texturePath", typeof(Texture2D)));
// Sets the main texture on the copy of the material that you just made
// Make sure that the image file is located somewhere in the unityproject folder

AssetDatabase.CreateAsset(tempSkyBox, "materialPath" + "/mySkybox.mat");
// Saves the copy of the material to the disk

AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// force the editor to update the AssetsFolder

myCamera.GetComponentInChildren<Skybox>().material = tempSkyBox;
// Sets the reference

this method worked for me in one of my projects
Good luck ^^


问:
SQL - extracting all pairs only once
Problem statement:

a table with N columns, K out of which are used in a criterion to determine pairs of rows

such a criterion involving the K columns can simply be if columns c_1, c2, .. c_k are equal for the two different rows part of a pair (the criterion itself is not relevant, only the fact that it must be used)

the requirement is to extract all potential pairs, but only once. This means that if for a row there are more than 2 potential other rows that can form a pair given the above criterion, then only one pair must be extracted

Simple example:

Input table:

```
A | B | C
x | y | z
w | y | z
u | y | z
u | v | z
v | v | z
```

Criterion: B and C columns must be the same for two rows to be part of a pair.

Output:

```
x | y | z
w | y | z
u | v | z
v | v | z
```

What hints do you have for solving the problem in pure SQL (or in the Oracle dialect, if specific features help)?

答:
Use the COUNT() analytic function partitioning on those rows you want to match as pairs:

```<code>SELECT A, B, C
FROM   (
  SELECT t.*,
         COUNT(*) OVER (
             PARTITION BY B, C
             ORDER BY A
             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
         ) AS current_rn,
         COUNT(*) OVER (
             PARTITION BY B, C
             ORDER BY A
             ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING
         ) AS next_rn
  FROM   table_name t
)
WHERE  MOD( current_rn, 2 ) = 0
OR     MOD( next_rn, 2 ) = 0;
</code>```

Output:

```<code>A B C
- - -
u y z
w y z
u v z
v v z
</code>```

Title: SQL - extracting all pairs only once

Body:
Problem statement:

a table with N columns, K out of which are used in a criterion to determine pairs of rows

such a criterion involving the K columns can simply be if columns c_1, c2, .. c_k are equal for the two different rows part of a pair (the criterion itself is not relevant, only the fact that it must be used)

the requirement is to extract all potential pairs, but only once. This means that if for a row there are more than 2 potential other rows that can form a pair given the above criterion, then only one pair must be extracted

Simple example:

Input table:

A | B | C
x | y | z
w | y | z
u | y | z
u | v | z
v | v | z

Criterion: B and C columns must be the same for two rows to be part of a pair.

Output:

x | y | z
w | y | z
u | v | z
v | v | z

What hints do you have for solving the problem in pure SQL (or in the Oracle dialect, if specific features help)?

Body:
Use the COUNT() analytic function partitioning on those rows you want to match as pairs:

SELECT A, B, C
FROM   (
  SELECT t.*,
         COUNT(*) OVER (
             PARTITION BY B, C
             ORDER BY A
             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
         ) AS current_rn,
         COUNT(*) OVER (
             PARTITION BY B, C
             ORDER BY A
             ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING
         ) AS next_rn
  FROM   table_name t
)
WHERE  MOD( current_rn, 2 ) = 0
OR     MOD( next_rn, 2 ) = 0;

Output:

A B C
- - -
u y z
w y z
u v z
v v z


问:
Convert physical standby to standalone database
I have a standard primary / physical-standby configuration (one primary, one standby), and would like to completely break the connection between primary and standby; converting physical standby to development database that is dissociated from primary/production system.

This seems like it should be fairly trivial, but doesn't really follow any documented procedures that I can find (most of which focus on switching over to standby for recovery purposes).

My gameplan is to activate the standby database by "simulating" a failover (without the primary actually failing, of course), following instructions here:

8.2.2 Performing a Failover to a Physical Standby Database
http://docs.oracle.com/cd/E11882_01/server.112/e41134/role_management.htm#SBYDB5176

This would entail running following on primary:

```<code>SQL> SHUTDOWN IMMEDIATE;
SQL> STARTUP MOUNT;
SQL> ALTER SYSTEM FLUSH REDO TO target_db_name;
</code>```

And then, if no errors, running this on standby:

```<code>SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;

SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE;
     (confirm result is TO PRIMARY or SESSIONS ACTIVE)

SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;
</code>```

Then, on both primary and standby, bring up in OPEN mode and disable further replication:

```<code>SQL> ALTER DATABASE OPEN;
SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='';
</code>```

I have 3 problems/questions with this approach:

 As a general statement, this feels a little overly complex - is there a more direct way to do this?  For example, I'd like to be able to do this without having to shutdown primary database (which is required in order to run ALTER SYSTEM FLUSH REDO TO target_db_name;).

 Current output of SELECT SWITCHOVER_STATUS FROM V$DATABASE; on standby is "NOT ALLOWED".  I assume this status will change with the ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH; but would like confirmation of this, as I don't want to find myself in trouble-shooting mode.

 Is ALTER SYSTEM SET LOG_ARCHIVE_DEST_2=''; the clean way to shutdown replication?  Should I instead ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2='disable'?

答:
We did this yesterday: Turn two Oracle 11 databases that were primary / physical-standby into standalone / standalone. There are many ways to set up an Oracle physical standby system: With or without broker, data guard manager, in different modes e.t.c. pp. This is what worked for us.

On your three questions:

The former primary kept running, no shutdown needed. We also felt
that the procedure was more complicated and less well documented than
it should be.

you are probably right. We didn't switch over, but convinced the standby DB that the primary was lost and it has to take over, i.e. only switched the standby to primary ("ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;"). But when I tried this without "ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;", it refused ("ORA-16139: media recovery required")

I'm not sure. To shutdown replication, we used the data guard manager. I expect you need at least an additional "alter database recover managed standby database cancel;"

preparation:

```<code>create spfile from pfile='standalone.ora';
alter database backup controlfile to trace;
</code>```

in dgmgrl:

```<code>REMOVE DATABASE
REMOVE CONFIGURATION
</code>```

on standby:

```<code>alter database recover managed standby database finish;
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;
</code>```

(now this database is PRIMARY)

```<code>shutdown immediate;
startup
</code>```

And that was it.

For cleanup, we modified the pfile:
  dg_broker_start=false
and removed
  dg_broker_config_file1
  dg_broker_config_file2
  fal_server
  standby_file_management

and in sqlplus / in the database, we dropped the standby redo logs

```<code>alter database drop standby logfile group 30;
</code>```

Body:
I have a standard primary / physical-standby configuration (one primary, one standby), and would like to completely break the connection between primary and standby; converting physical standby to development database that is dissociated from primary/production system.

This seems like it should be fairly trivial, but doesn't really follow any documented procedures that I can find (most of which focus on switching over to standby for recovery purposes).

My gameplan is to activate the standby database by "simulating" a failover (without the primary actually failing, of course), following instructions here:

8.2.2 Performing a Failover to a Physical Standby Database
http://docs.oracle.com/cd/E11882_01/server.112/e41134/role_management.htm#SBYDB5176

This would entail running following on primary:

SQL> SHUTDOWN IMMEDIATE;
SQL> STARTUP MOUNT;
SQL> ALTER SYSTEM FLUSH REDO TO target_db_name;

And then, if no errors, running this on standby:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;

SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE;
     (confirm result is TO PRIMARY or SESSIONS ACTIVE)

SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;

Then, on both primary and standby, bring up in OPEN mode and disable further replication:

SQL> ALTER DATABASE OPEN;
SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='';

I have 3 problems/questions with this approach:

 As a general statement, this feels a little overly complex - is there a more direct way to do this?  For example, I'd like to be able to do this without having to shutdown primary database (which is required in order to run ALTER SYSTEM FLUSH REDO TO target_db_name;).

 Current output of SELECT SWITCHOVER_STATUS FROM V$DATABASE; on standby is "NOT ALLOWED".  I assume this status will change with the ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH; but would like confirmation of this, as I don't want to find myself in trouble-shooting mode.

 Is ALTER SYSTEM SET LOG_ARCHIVE_DEST_2=''; the clean way to shutdown replication?  Should I instead ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2='disable'?

Body:
We did this yesterday: Turn two Oracle 11 databases that were primary / physical-standby into standalone / standalone. There are many ways to set up an Oracle physical standby system: With or without broker, data guard manager, in different modes e.t.c. pp. This is what worked for us.

On your three questions:

The former primary kept running, no shutdown needed. We also felt
that the procedure was more complicated and less well documented than
it should be.

you are probably right. We didn't switch over, but convinced the standby DB that the primary was lost and it has to take over, i.e. only switched the standby to primary ("ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;"). But when I tried this without "ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;", it refused ("ORA-16139: media recovery required")

I'm not sure. To shutdown replication, we used the data guard manager. I expect you need at least an additional "alter database recover managed standby database cancel;"

preparation:

create spfile from pfile='standalone.ora';
alter database backup controlfile to trace;

in dgmgrl:

REMOVE DATABASE
REMOVE CONFIGURATION

on standby:

alter database recover managed standby database finish;
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;

(now this database is PRIMARY)

shutdown immediate;
startup

And that was it.

For cleanup, we modified the pfile:
  dg_broker_start=false
and removed
  dg_broker_config_file1
  dg_broker_config_file2
  fal_server
  standby_file_management

and in sqlplus / in the database, we dropped the standby redo logs

alter database drop standby logfile group 30;


问:
RxSwift Binding to UITable from a Variable
In RxSwift, do you know why I am not getting any values in this tableView?

Note: allTable is the UITableView

```<code>    var strList: Variable<[String]>?

    let disposeBag: DisposeBag = DisposeBag()

    strList?.value.append("111")
    strList?.value.append("222")
    strList?.value.append("333")

    strList?.asObservable()
        .bindTo(
            allTable.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)
        ){  (row, item, cell) in
            cell.textLabel?.text = item
        }
        .addDisposableTo(disposeBag)
</code>```

答:
You need to move the creating of disposeBag outside of the function

```<code>let disposeBag: DisposeBag = DisposeBag()

var strList: Variable<[String]>?

func subscribeToStrList() {
    strList?.value.append("111")
    strList?.value.append("222")
    strList?.value.append("333")

    strList?.asObservable()
        .bindTo(
            allTable.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)
        ){  (row, item, cell) in
            cell.textLabel?.text = item
        }
        .addDisposableTo(disposeBag)
}
</code>```

Otherwise, when the function exits, the subscription is disposed of.

Body:
In RxSwift, do you know why I am not getting any values in this tableView?

Note: allTable is the UITableView

    var strList: Variable<[String]>?

    let disposeBag: DisposeBag = DisposeBag()

    strList?.value.append("111")
    strList?.value.append("222")
    strList?.value.append("333")

    strList?.asObservable()
        .bindTo(
            allTable.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)
        ){  (row, item, cell) in
            cell.textLabel?.text = item
        }
        .addDisposableTo(disposeBag)

Body:
You need to move the creating of disposeBag outside of the function

let disposeBag: DisposeBag = DisposeBag()

var strList: Variable<[String]>?

func subscribeToStrList() {
    strList?.value.append("111")
    strList?.value.append("222")
    strList?.value.append("333")

    strList?.asObservable()
        .bindTo(
            allTable.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)
        ){  (row, item, cell) in
            cell.textLabel?.text = item
        }
        .addDisposableTo(disposeBag)
}

Otherwise, when the function exits, the subscription is disposed of.


问:
No route matches {:action=>"destroy", :controller=>"users"}
I'm getting a error when I try to acces users#show page trough a named route (http://localhost:3000/profile/) ... otherwise I have no error when I try to access it with the standard url (http://localhost:3000/users/current).  If I rake routes I routes seems right and since it works with standard url, I really have no clue why I get No route matchs error. When why trying to find route match for action 'destroy' when I'm not even trying to access it?

```<code>Starcast::Application.routes.draw do

  match "login" => 'user_sessions#new', :as => :login
  match "logout" => 'user_sessions#destroy', :as => :logout
  resources :user_sessions

  match "profile" => 'users#show'
  resources :users

  resources :casters
  resources :casts
  resources :orders

  root :to => "home#index"

end
</code>```

Error I get:

```<code>ActionView::Template::Error (No route matches {:action=>"edit", :controller=>"users"}):
    1: <% title "Welcome #{@user.username}" %>
    2:
    3: <%= link_to "Edit your profil", edit_user_path %>
    4:
    5: <% has_role? :caster do %>
    6: <% if @user.caster %>
  app/views/users/show.html.erb:3:in `_app_views_users_show_html_erb___2116234531537545622_2170017780__3613739707062673465'
</code>```

答: Edit/show/destroy/update paths require an id parameter ... i.e. edit_user_path(current_user.id) ... If you don't want to do it that way you'll need to make your routes use resource :user (instead of resources :user) which will cause lots of headache later down the road if you don't do it right.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm getting a error when I try to acces users#show page trough a named route (http://localhost:3000/profile/) ... otherwise I have no error when I try to access it with the standard url (http://localhost:3000/users/current).  If I rake routes I routes seems right and since it works with standard url, I really have no clue why I get No route matchs error. When why trying to find route match for action 'destroy' when I'm not even trying to access it?

Starcast::Application.routes.draw do

  match "login" => 'user_sessions#new', :as => :login
  match "logout" => 'user_sessions#destroy', :as => :logout
  resources :user_sessions

  match "profile" => 'users#show'
  resources :users

  resources :casters
  resources :casts
  resources :orders

  root :to => "home#index"

end

Error I get:

ActionView::Template::Error (No route matches {:action=>"edit", :controller=>"users"}):
    1: <% title "Welcome #{@user.username}" %>
    2:
    3: <%= link_to "Edit your profil", edit_user_path %>
    4:
    5: <% has_role? :caster do %>
    6: <% if @user.caster %>
  app/views/users/show.html.erb:3:in `_app_views_users_show_html_erb___2116234531537545622_2170017780__3613739707062673465'


问:
Selecting only 1 node in ansible group
I have an ansible inventory file that looks like:

```<code>[database]
172.29.225.95 is_master=true
172.29.225.93 is_master=false
172.29.225.94 is_master=false
</code>```

I want to run my playbook ONLY on the master node which is 172.29.225.95 but is there a way in Ansible to simply select one node that I want to run the playbook on ?

There is a dirty hack that Ive tried. Its simply to add a new entry in my inventory file and use that group only.

```<code>[database-master]
172.29.225.95
</code>```

and then

```<code>- name: Perform Health Checks.
  hosts: database-master
  tasks:
    - name: Check Postgres cluster status.
      shell: /usr/efm-2.0/bin/efm cluster-status efm
      register: output
</code>```

But I feel this is just a work around and not a solid solution. So working ONLY with [database] group, can I make Ansible just run the playbook only on 172.29.225.95 ?

答: I suppose you could use the --limit option of ansible-playbook executable as described in documentation</p>

Title: Selecting only 1 node in ansible group

Body:
I have an ansible inventory file that looks like:

[database]
172.29.225.95 is_master=true
172.29.225.93 is_master=false
172.29.225.94 is_master=false

I want to run my playbook ONLY on the master node which is 172.29.225.95 but is there a way in Ansible to simply select one node that I want to run the playbook on ?

There is a dirty hack that Ive tried. Its simply to add a new entry in my inventory file and use that group only.

[database-master]
172.29.225.95

and then

- name: Perform Health Checks.
  hosts: database-master
  tasks:
    - name: Check Postgres cluster status.
      shell: /usr/efm-2.0/bin/efm cluster-status efm
      register: output

But I feel this is just a work around and not a solid solution. So working ONLY with [database] group, can I make Ansible just run the playbook only on 172.29.225.95 ?


问:
nwjs How to distribute app on linux?
I'm using nwjs 0.14.7, and ubuntu 32bit.
I recently updated from 0.12.2, and now the build process seems to be different or doesn't work.

I've added my files to package.nw and then appended to nw via:

cat nw app.nw > app && chmod +x app

Then in the docs it says "On Linux, you need to create proper .desktop file."
But there aren't any directions specific for this case, If I try running nw, it says "There is no application installed for "shared library" files. Do you want to search for an application to open this file?"

So I'm assuming the .desktop file would fix this? It says you can create it via a text editor, but I have no idea what I should put inside it. For 0.12.2 the .desktop step wasn't necessary so I'm a bit lost now.

答:
I know I am using ubuntu 14.04 and what I did worked for me so this is how I did it.

Create a .desktop file for your app by:

1.press right click on mouse then 'New Document => Empty Document'.

2.inside the document insert the following text:

[Desktop Entry]

Version=1.0 (this is the version of the .desktop file and not your app version)

Type=Application

Terminal=false

Exec=/home/artechs/projects/copa-linux-x64/nw (this is the full path for the executable file)

Name=copa (this will show up on the menu)

Comment=secure sharing files application (this will show up if you right click on the app)

Icon=/home/artechs/projects/copa-linux-x64/package.nw/app/styles/COPA LOGO RGB-01.png (for the icon of this file and also the icon that will show up on the share applications)

Categories=Utility;Application;

3.press on the menu bar 'File => Save As...' and give it a name with .desktop extension for example copa.desktop

4.go to Terminal and to your app folder where this file is located and type: chmod +x <nameOFDesktopFile>.desktop

5.now you need to copy this file to share applications folder by type: cp <nameOFDesktopFile>.desktop /usr/share/applications

After doing this steps I could run my app through this desktop file or through the search by searching the name of my app.

Hope it will work for you as it worked for me.

Title: nwjs How to distribute app on linux?


答: Use z-index in CSS to solve this problem. For example: if you wanna show header on top then use z-index: 2; for header  and z-index: 1; for that div. for more: https://www.w3schools.com/cssref/pr_pos_z-index.asp

Title: How to fix the div while scrolling using jQuery?


问:
How to use variable defined inside setOnAction outside it?
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

```<code>//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
</code>```

答:
You can make it a field of your class to use it in method and in scope of class. You can see this article Scope of Variables In Java </p>

```<code>class Rezultat{
    Button rezultat = new Button("Pogledajte Vas rezultat");
    int poeni;//The scope of poeni starts form here
    rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            poeni = 0;

            if(odgovor1_1.isSelected()) poeni++;
            if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
            if(odgovor3_2.isSelected()) poeni++;
        }
    });
    Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
  }//You can use variable to here
</code>```

Body:
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);

Body:
You can make it a field of your class to use it in method and in scope of class. You can see this article Scope of Variables In Java

class Rezultat{
    Button rezultat = new Button("Pogledajte Vas rezultat");
    int poeni;//The scope of poeni starts form here
    rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            poeni = 0;

            if(odgovor1_1.isSelected()) poeni++;
            if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
            if(odgovor3_2.isSelected()) poeni++;
        }
    });
    Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
  }//You can use variable to here


问:
How to check not in array element
I am trying to check if an element is not in array than want to redirect page:
My code is as below:

```<code>$id = $access_data['Privilege']['id'];

if(!in_array($id,$user_access_arr))
{
    $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
    return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}
</code>```

I am confused how to check if element is not in array.
As we can check element exist or not in array using in_array function of PHP.
I am trying to check it using (!in_array) but I did not got result.

答:
you can check using php in_array() built in function

```<code><?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 }
 if (in_array("mac", $os)) {
  echo "Got mac";
}
?>
</code>```

and you can also check using this

```<code><?php
  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
   }
   ?>
</code>```

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

```<code>$data = array(
0 => 'Key1',
1 => 'Key2'
);

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';
}
</code>```

for more details
http://php.net/manual/en/function.in-array.php

ContentLicense: CC BY-SA 4.0

Title: How to check not in array element

Body:
I am trying to check if an element is not in array than want to redirect page:
My code is as below:

$id = $access_data['Privilege']['id'];

if(!in_array($id,$user_access_arr))
{
    $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
    return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}

I am confused how to check if element is not in array.
As we can check element exist or not in array using in_array function of PHP.
I am trying to check it using (!in_array) but I did not got result.

Body:
you can check using php in_array() built in function

<?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 }
 if (in_array("mac", $os)) {
  echo "Got mac";
}
?>

and you can also check using this

<?php
  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
   }
   ?>

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = array(
0 => 'Key1',
1 => 'Key2'
);

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';
}

for more details
http://php.net/manual/en/function.in-array.php


问:
Is there a YAML test suite?
A comprehensive test suite would be a valuable tool to have, especially when evaluating all of the variant parsers out there.  Does such a beast exist?

In a perfect world, I imagine it would have different sections for different versions of the YAML spec...

答:
There is currently one in the making, see here.

We also generate a result matrix for YAML implementations which

we know of

are written in a language we know so we can implement adapter code to validate the test suite against it

Full disclosure: I am the author of NimYAML and some of the test cases and adapters.

Title: Is there a YAML test suite?


问:
ReactJs failing to bind data object
I'm new to ReactJs and I'm trying to bind a http response to the DOM, but I can't get it to work. Im using componentDidMount to execute the api call. Any help will be much appreciated, please see code below.

```<code>var testStuff="First State";
var Test = React.createClass({
    loadTestData: function () {
        $.ajax({
            url: "http://localhost:64443/api/articles/apitest",
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (response) {
                console.log(response);
                testStuff= response;
            },
            error: function (error) {
                alert(error);
            }
        });

    },
    componentDidMount() {
        this.loadTestData();
    },

    render() {
        console.log(this.testStuff);
        return (
          <div onClick={this.loadTestData}>
        {testStuff}
      </div>
    );
}
});
ReactDOM.render(
  <Test />,
  document.getElementById('content')
);
</code>```

The onClick seems to be working, but its almost like the componentDidMount only gets executed after the page is rendered.

答:
You need to properly update the component state in the AJAX success handler: this.setState({ testStuff: data })

Then you will be able to access it in render using this.state.testStuff.

componentDidMount indeed only runs after component has been mounted. You will also need to represent the UI state where the requests is still ongoing (this.state.testStuff will be undefined at that point).

Title: ReactJs failing to bind data object

Body:
I'm new to ReactJs and I'm trying to bind a http response to the DOM, but I can't get it to work. Im using componentDidMount to execute the api call. Any help will be much appreciated, please see code below.

var testStuff="First State";
var Test = React.createClass({
    loadTestData: function () {
        $.ajax({
            url: "http://localhost:64443/api/articles/apitest",
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (response) {
                console.log(response);
                testStuff= response;
            },
            error: function (error) {
                alert(error);
            }
        });

    },
    componentDidMount() {
        this.loadTestData();
    },

    render() {
        console.log(this.testStuff);
        return (

        {testStuff}

    );
}
});
ReactDOM.render(
  <Test />,
  document.getElementById('content')
);

The onClick seems to be working, but its almost like the componentDidMount only gets executed after the page is rendered.


问:
access to external resources in the vert.x project
I have a project in vert.x 3.4.1 that I compile in .jar and I want to access from that .jar to an image in the same path:

-- myProject

-------- project.jar

-------- config.json

-------- logo.png

in my project.jar i have some html pages, from this pages I want to access to logo.png, I don't wanna to set it into .jar

I tried to set a route special for that but not works

答:
If you use a StaticHandler, by default it looks for files in a webroot directory. Change your directory structure to:

```<code>myProject/
    project.jar
    config.json
    webroot/
        logo.png
</code>```

Otherwise you can setup the static handler to something other than the default web root.

Body:
If you use a StaticHandler, by default it looks for files in a webroot directory. Change your directory structure to:

myProject/
    project.jar
    config.json
    webroot/
        logo.png

Otherwise you can setup the static handler to something other than the default web root.


问:
Remove production APNs
I have accidentally uploaded my development environment APN where I wanted my production APN .p12 file in Firebase. However I cannot remove it now. There are a button that says "Upload new", which I have tried, but afterwards there are still the old development APN .p12 file.

I have as well tried to delete the iOS app and then install it again, but the keys are still stored under "Cloud Messaging".

How am I able to delete an APN key?

答:
This same problem happened to me.

However the following workaround does the trick for me:

I have found a workaround to the problem. You try generating a new certificate with a different private key and then try to overwrite the old certificate using that new certificate at Firebase settings.

Title: Remove production APNs


问:
Android: problem in getText method of EditText
In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.

In the first class I wrote this code but it seems has problem.

```<code>public String getTextMessage()
{
    return textMessage.getText().toString();
}
</code>```

because in second class when I want to get it, program crashes.

```<code>message = encode.getTextMessage();
</code>```

What is your suggestion?

答: Access the text by getText() from edit text and store it in an string. when you move to second activity sent string variable to second class via bundel. Extract the bundel in second class and use it.</p>

Body:
In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.

In the first class I wrote this code but it seems has problem.

public String getTextMessage()
{
    return textMessage.getText().toString();
}

because in second class when I want to get it, program crashes.

message = encode.getTextMessage();

What is your suggestion?


问:
SQL Name search with apostrophe, hyphen, Double uppercase
There is a search filter with alphabet.

I would like the filter to work if I click 'D' it then displays all artist's names like:

```
David McDonald
Alice Duncan
Daniel O'Neill
Beth Douglas-Bain
```

The artist table has a column 'name' which contains first, middle and surname, including apostrophes, hyphens, and double uppercase.

I tried

```<code>SELECT * FROM `artist` WHERE `name` REGEXP BINARY 'D[a-z]'
</code>```

however, that didn't work properly.

I can only use the query from 'WHERE clause' so I cannot use the query from SELECT.

Some problem examples are:

Click 'O' but O'Neill not showing up

Click 'B' then Douglas-Bain showing up, should be 'D', McDonald has same problem too.

The surname of McDonald, O'neill, Douglas-Bain, those makes the query not working well as McDonald and Douglas-Bain have two uppercases, so it appears when I hit 'D'. O'Neill has an apostrophe and double uppercase and I cannot figure it out.

I would really appreciate it if some SQL expert can help me.

答:
Try this:</p>

```<code>select * from artist where name like '%D%' or name like '%d%';
</code>```

Body:
There is a search filter with alphabet.

I would like the filter to work if I click 'D' it then displays all artist's names like:

David McDonald
Alice Duncan
Daniel O'Neill
Beth Douglas-Bain

The artist table has a column 'name' which contains first, middle and surname, including apostrophes, hyphens, and double uppercase.

I tried

SELECT * FROM `artist` WHERE `name` REGEXP BINARY 'D[a-z]'

however, that didn't work properly.

I can only use the query from 'WHERE clause' so I cannot use the query from SELECT.

Some problem examples are:

Click 'O' but O'Neill not showing up

Click 'B' then Douglas-Bain showing up, should be 'D', McDonald has same problem too.

The surname of McDonald, O'neill, Douglas-Bain, those makes the query not working well as McDonald and Douglas-Bain have two uppercases, so it appears when I hit 'D'. O'Neill has an apostrophe and double uppercase and I cannot figure it out.

I would really appreciate it if some SQL expert can help me.

Body:
Try this:

select * from artist where name like '%D%' or name like '%d%';


问:
using filters in component binding html attribute in angularjs (causing $digest() errors)
I'm trying to filter an array of objects using an AngularJS filter filter : {completed:true} inside an html attribute that is in fact a binding itself. Is this possible, or should I do this in another way? More examples and code below.

How to reproduce

See plnkr with the failing code at http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

One can also see code snippets & link to original repo below

UPDATE 30/03/2017:

Found a possible solution with introducing an extra binding, check answer https://stackoverflow.com/a/43112663/1155847 below for a possible solution. Open to any other suggestions.

BUT using a filter expression like <todo-list todo-items="$ctrl.todoItems | filter:{completed:true}"></todo-list> still causes $digest() cycle errors. I've created a branch in my repo to reproduce: https://github.com/aredfox/todo-angularjs-typescript/tree/filter-inside-attribute-digest-errors.
=> git clone https://github.com/aredfox/todo-angularjs-typescript + cd to repo dir and then git checkout filter-inside-attribute-digest-errors + npm install && npm run

Code Snippets & Usage

Below I have a TL;DR view of the code that's the most important to my question, for the full repo, you can look at this commit which holds all the source files in detail.

todo-list directive HTML declaration & usage

Normal usage of the directive: <todo-list todo-items="$ctrl.todoItems"></todo-list> - this works fine and lists out the title of each TodoItem as programmed inside the todo-list.

things I tried:

What I tried to do with a filter, which is not working: <todo-list todo-items="$ctrl.todoItems | filter : {completed:true}"></todo-list>. But this gave me the following error: Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!.

todo-list component definition

typescript
    class TodoList implements angular.IComponentOptions {
        template: string;
        bindings: any;

```<code>    constructor() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<'
        };
    }
}
</code>```

js

```<code>var TodoList = (function () {
    function TodoList() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<'
        };
    }
    return TodoList;
}());
</code>```

TodoItem model

The model I'm using is an array of TodoItems. The definition (typescript / js) below:

typescript

```<code>class TodoItem {
    constructor(
        public title: string,
        public completed: boolean
    ) { }
}
</code>```

js

```<code>var TodoItem = (function () {
    function TodoItem(title, completed) {
        this.title = title;
        this.completed = completed;
    }
    return TodoItem;
}());
</code>```

答:
I found a working solution for me, by doing the following:

1. todo-list.component.ts

Here I add another binding where the filter will act on (filterBy, which we can use in the todo-list as filter-by)

```<code>class TodoList implements angular.IComponentOptions {
    template: string;
    bindings: any;

    constructor() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<',
            filterBy: '<'
        };
    }
}
</code>```

the template looks like this:

```<code><div ng-repeat="todoItem in $ctrl.todoItems | filter:$ctrl.filterBy">
    <span>{{ todoItem.title }}</span>
</div>
</code>```

2. using todo-list

<todo-list todo-items="$ctrl.todoItems"></todo-list> then results in showing all todoItems

<todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list> shows the items that have the property completed set to true

Body:
I'm trying to filter an array of objects using an AngularJS filter filter : {completed:true} inside an html attribute that is in fact a binding itself. Is this possible, or should I do this in another way? More examples and code below.

How to reproduce

See plnkr with the failing code at http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

One can also see code snippets & link to original repo below

UPDATE 30/03/2017:

Found a possible solution with introducing an extra binding, check answer https://stackoverflow.com/a/43112663/1155847 below for a possible solution. Open to any other suggestions.

BUT using a filter expression like <todo-list todo-items="$ctrl.todoItems | filter:{completed:true}"></todo-list> still causes $digest() cycle errors. I've created a branch in my repo to reproduce: https://github.com/aredfox/todo-angularjs-typescript/tree/filter-inside-attribute-digest-errors.
=> git clone https://github.com/aredfox/todo-angularjs-typescript + cd to repo dir and then git checkout filter-inside-attribute-digest-errors + npm install && npm run

Code Snippets & Usage

Below I have a TL;DR view of the code that's the most important to my question, for the full repo, you can look at this commit which holds all the source files in detail.

todo-list directive HTML declaration & usage

Normal usage of the directive: <todo-list todo-items="$ctrl.todoItems"></todo-list> - this works fine and lists out the title of each TodoItem as programmed inside the todo-list.

things I tried:

What I tried to do with a filter, which is not working: <todo-list todo-items="$ctrl.todoItems | filter : {completed:true}"></todo-list>. But this gave me the following error: Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!.

todo-list component definition

typescript
    class TodoList implements angular.IComponentOptions {
        template: string;
        bindings: any;

    constructor() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<'
        };
    }
}

js

var TodoList = (function () {
    function TodoList() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<'
        };
    }
    return TodoList;
}());

TodoItem model

The model I'm using is an array of TodoItems. The definition (typescript / js) below:

typescript

class TodoItem {
    constructor(
        public title: string,
        public completed: boolean
    ) { }
}

js

var TodoItem = (function () {
    function TodoItem(title, completed) {
        this.title = title;
        this.completed = completed;
    }
    return TodoItem;
}());

Body:
I found a working solution for me, by doing the following:

1. todo-list.component.ts

Here I add another binding where the filter will act on (filterBy, which we can use in the todo-list as filter-by)

class TodoList implements angular.IComponentOptions {
    template: string;
    bindings: any;

    constructor() {
        this.template = require('./todo-list.component.html');
        this.bindings = {
            todoItems: '<',
            filterBy: '<'
        };
    }
}

the template looks like this:

<div ng-repeat="todoItem in $ctrl.todoItems | filter:$ctrl.filterBy">
    <span>{{ todoItem.title }}</span>
</div>

2. using todo-list

<todo-list todo-items="$ctrl.todoItems"></todo-list> then results in showing all todoItems

<todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list> shows the items that have the property completed set to true


问:
Sharing variable globally
In my main controller I have a user service that returns the current user.

```<code>// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});
</code>```

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

```<code>// My other awesome controller
console.log(currUser.fullName);
</code>```

答:
You don't want you use controller injections? Use injector its the same like injections but also different :D ... like in this runnable fiddle demo. In that way you still can use services, factories, or components.

```<code>var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.name = angular.injector(['data']).get('user').currUser.username;
});

angular.module('data', []).factory('user', function () {
    return {
      currUser: {
        username: 'Alfred'
      }
    }
});
</code>```

Title: Sharing variable globally

Body:
In my main controller I have a user service that returns the current user.

// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

// My other awesome controller
console.log(currUser.fullName);

Body:
You don't want you use controller injections? Use injector its the same like injections but also different :D ... like in this runnable fiddle demo. In that way you still can use services, factories, or components.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.name = angular.injector(['data']).get('user').currUser.username;
});

angular.module('data', []).factory('user', function () {
    return {
      currUser: {
        username: 'Alfred'
      }
    }
});


问:
Codename one login with Linkedin
I am trying to use Linkedin for login purpose in Codename one, but whenever I am clicking on login button it display blank pop up dialog-box.

Below is my code

```<code>linked.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {

           Oauth2 auth2 = new Oauth2("https://www.linkedin.com/uas/oauth2/authorization",
            "XXXXXXXXXX",
            "https://www.codenameone.com","r_basicprofile",
            "https://www.linkedin.com/uas/oauth2/accessToken",
            "XXXXXXXXXX");
   Oauth2.setBackToParent(true);
   auth2.authenticate();
    auth2.createAuthComponent(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent evt) {
                    Log.p(evt.getSource().toString());

            if (evt.getSource() instanceof String) {
                 String token = (String) evt.getSource();
                String expires = Oauth2.getExpires();

                System.out.println("Token=" +token + "Expires in " +expires );
            }
             else {
                Exception err = (Exception) evt.getSource();
                err.printStackTrace();
                Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
            }
               }
           });

   }
    });
</code>```

答:
Here I got the solution of the above problem.

Working code:

```<code>linked.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

               Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization",
                "XXXXXXXXXXXXX",
                "https://www.codenameone.com","r_basicprofile",
                "https://www.linkedin.com/oauth/v2/accessToken",
                "XXXXXXXXXXXXX");

       //auth2.authenticate();
        auth2.showAuthentication(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent evt) {
                       AccessToken token = (AccessToken) evt.getSource();
                       JSONObject object = new JSONObject(token);
                       try {
                           TOKEN = object.getString("token");
                           Log.p(TOKEN);
                       } catch (JSONException ex) {
                           ex.printStackTrace();
                       }
                   }
               });
                Oauth2.setBackToParent(true);

       }
        });
</code>```

Above code successfully authenticate linked in user and in response we get token after successful login in TOKEN variable.

Title: Codename one login with Linkedin

Body:
I am trying to use Linkedin for login purpose in Codename one, but whenever I am clicking on login button it display blank pop up dialog-box.

Below is my code

linked.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {

           Oauth2 auth2 = new Oauth2("https://www.linkedin.com/uas/oauth2/authorization",
            "XXXXXXXXXX",
            "https://www.codenameone.com","r_basicprofile",
            "https://www.linkedin.com/uas/oauth2/accessToken",
            "XXXXXXXXXX");
   Oauth2.setBackToParent(true);
   auth2.authenticate();
    auth2.createAuthComponent(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent evt) {
                    Log.p(evt.getSource().toString());

            if (evt.getSource() instanceof String) {
                 String token = (String) evt.getSource();
                String expires = Oauth2.getExpires();

                System.out.println("Token=" +token + "Expires in " +expires );
            }
             else {
                Exception err = (Exception) evt.getSource();
                err.printStackTrace();
                Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
            }
               }
           });

   }
    });

Body:
Here I got the solution of the above problem.

Working code:

linked.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

               Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization",
                "XXXXXXXXXXXXX",
                "https://www.codenameone.com","r_basicprofile",
                "https://www.linkedin.com/oauth/v2/accessToken",
                "XXXXXXXXXXXXX");

       //auth2.authenticate();
        auth2.showAuthentication(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent evt) {
                       AccessToken token = (AccessToken) evt.getSource();
                       JSONObject object = new JSONObject(token);
                       try {
                           TOKEN = object.getString("token");
                           Log.p(TOKEN);
                       } catch (JSONException ex) {
                           ex.printStackTrace();
                       }
                   }
               });
                Oauth2.setBackToParent(true);

       }
        });

Above code successfully authenticate linked in user and in response we get token after successful login in TOKEN variable.


问:
CannotVerifyCopySource, extended message: The specified blob does not exist. in Azure Data Factory
While connecting from a Azure Data Factory  to My Azure Blob storage I am getting the following error.
Error: The remote server returned an error: (404) Not Found., HTTP status code: 404, HTTP status message The specified blob does not exist., extended status code: CannotVerifyCopySource, extended message: The specified blob does not exist. </p>

答:
The error information had shown the issue reason The specified blob does not exist., which be listed in Blob Service Error Codes as below.

My guess is that you were copying some blobs which have been also using by other process like HDInsight as your thread tag. When Azure Data Factory was ready for doing the copy operation, the specified blob as a temporary object had been deleted. Please check and make sure whether exists this case.


问:
Url contain special charectors
I am trying to establish a https connection but my URL contains some special characters, so creating the connection is throwing an Exception.  How do I avoid this problem?</p>

Title: Url contain special charectors

Body:
 You can encode like this,

public class URLUTF8Encoder
{
 final static String[] hex = {
"%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
"%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f",
"%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f",
"%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
"%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f",
"%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
"%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f",
"%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
"%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f",
"%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
"%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
"%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f",
"%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
"%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f",
"%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
"%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f",
"%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
"%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f",
"%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
"%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af",
"%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7",
"%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf",
"%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7",
"%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf",
"%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7",
"%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df",
"%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7",
"%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
"%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7",
"%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff"
};
 public static String encode(String s)
 {
 StringBuffer sbuf = new StringBuffer();
 int len = s.length();
for (int i = 0; i < len; i++) {
  int ch = s.charAt(i);
  if ('A' <= ch && ch <= 'Z') {     // 'A'..'Z'
    sbuf.append((char)ch);
  } else if ('a' <= ch && ch <= 'z') {  // 'a'..'z'
       sbuf.append((char)ch);
  } else if ('0' <= ch && ch <= '9') {  // '0'..'9'
       sbuf.append((char)ch);
  } else if (ch == ' ') {           // space
       sbuf.append('+');
  } else if (ch == '-' || ch == '_'     // unreserved
      || ch == '.' || ch == '!'
      || ch == '~' || ch == '*'
      || ch == '\'' || ch == '('
      || ch == ')') {
    sbuf.append((char)ch);
  } else if (ch <= 0x007f) {        // other ASCII
       sbuf.append(hex[ch]);
  } else if (ch <= 0x07FF) {        // non-ASCII <= 0x7FF
       sbuf.append(hex[0xc0 | (ch >> 6)]);
       sbuf.append(hex[0x80 | (ch & 0x3F)]);
  } else {                  // 0x7FF < ch <= 0xFFFF
       sbuf.append(hex[0xe0 | (ch >> 12)]);
       sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
       sbuf.append(hex[0x80 | (ch & 0x3F)]);
  }
}
return sbuf.toString();
}

}
referenced By
HTTP://WWW.W3.ORG/INTERNATIONAL/URLUTF8ENCODER.JAVA


问:
Android project cannot run why

I download the project from https://developer.android.com/training/implementing-navigation/nav-drawer.html Its name is NavigationDrawer.zip

答: Right click src directory and choose Mark Directory As -> Resources Root.

Title: Android project cannot run why


问:
how to split array in ajax?
```<code>var rows_selected = [];
var rowId = data[0]; // conten [24,25,26,27 etc]
var namaFile = data[4]; // content [foto1.JPG, foto2.JPG, foto3.JPG, foto4.JPG ]

//If checkbox is checked and row ID is not in list of selected row IDs
rows_selected.push(rowId,namaFile);

var dataId=[];
$.each(rows_selected, function(index, rowId, namaFile){
  dataId.push(rowId,namaFile);
});
</code>```

in ajax i sent dataId to controller

```<code>$.ajax({
   data: {"iddata": "[{"+dataId+"}]"},
});
</code>```

but in controller iddata receive just one array like this 24,6a5236ee48848e648553a35d64c4f64dJPG,25,a31ea31db31483506fbd95e463d4c8ffJPG,26,042fd1eee499e5bb9c93853c0299b42eJPG,27,e243845bcc0447324d449e37b271c9ebJPG,28,8f331fa2a713f5268ab71698a65185b6JPG

some code in controller

```<code>$iddata=array();
    $iddata=array($_GET['iddata']);
    $a=explode(",", $iddata[0]);
    $b=preg_replace('/[^A-Za-z0-9\-]/', '', $a);
    $jumlahdata=count($b)/2;
    for($i=0;$i<$jumlahdata;$i++)
    {
        //delete on database
       $data=array('id_perjal'=>$b[$i]);
       $this->M_perjal_terpasang->Delete_Foto($data);
        //and i want deleting foto with unlink
       unlink("assets/images/uploads/"$b[$i]);
    }
</code>```

答:
```<code>var rowId = [24,25,26,27];
var namaFile = ['foto1.JPG', 'foto2.JPG', 'foto3.JPG', 'foto4.JPG' ];
var rows_selected = {};
for (var i = 0; i < rowId.length; i++) {
   //or check with: if (b.length > i) { assignment }
   rows_selected[rowId[i]] = namaFile[i];
}

$.ajax({
  data: {"iddata": JSON.stringify(rows_selected)},
});
</code>```

It will return you {"id_21":"foto1.JPG","id_25":"foto2.JPG","id_26":"foto3.JPG","id_27":"foto4.JPG"}
So in ajax page you will get array like array("id_21" => "foto1.JPG","id_25" => "foto2.JPG","id_26" => "foto3.JPG","id_27" => "foto4.JPG");

Title: how to split array in ajax?

Body:
var rows_selected = [];
var rowId = data[0]; // conten [24,25,26,27 etc]
var namaFile = data[4]; // content [foto1.JPG, foto2.JPG, foto3.JPG, foto4.JPG ]

//If checkbox is checked and row ID is not in list of selected row IDs
rows_selected.push(rowId,namaFile);

var dataId=[];
$.each(rows_selected, function(index, rowId, namaFile){
  dataId.push(rowId,namaFile);
});

in ajax i sent dataId to controller

$.ajax({
   data: {"iddata": "[{"+dataId+"}]"},
});

but in controller iddata receive just one array like this 24,6a5236ee48848e648553a35d64c4f64dJPG,25,a31ea31db31483506fbd95e463d4c8ffJPG,26,042fd1eee499e5bb9c93853c0299b42eJPG,27,e243845bcc0447324d449e37b271c9ebJPG,28,8f331fa2a713f5268ab71698a65185b6JPG

some code in controller

$iddata=array();
    $iddata=array($_GET['iddata']);
    $a=explode(",", $iddata[0]);
    $b=preg_replace('/[^A-Za-z0-9\-]/', '', $a);
    $jumlahdata=count($b)/2;
    for($i=0;$i<$jumlahdata;$i++)
    {
        //delete on database
       $data=array('id_perjal'=>$b[$i]);
       $this->M_perjal_terpasang->Delete_Foto($data);
        //and i want deleting foto with unlink
       unlink("assets/images/uploads/"$b[$i]);
    }

Body:
var rowId = [24,25,26,27];
var namaFile = ['foto1.JPG', 'foto2.JPG', 'foto3.JPG', 'foto4.JPG' ];
var rows_selected = {};
for (var i = 0; i < rowId.length; i++) {
   //or check with: if (b.length > i) { assignment }
   rows_selected[rowId[i]] = namaFile[i];
}

$.ajax({
  data: {"iddata": JSON.stringify(rows_selected)},
});

It will return you {"id_21":"foto1.JPG","id_25":"foto2.JPG","id_26":"foto3.JPG","id_27":"foto4.JPG"}
So in ajax page you will get array like array("id_21" => "foto1.JPG","id_25" => "foto2.JPG","id_26" => "foto3.JPG","id_27" => "foto4.JPG");


问:
How to scale resize SVG contents proportionally, using only CSSs?
How can I scale or resize inline SVG vector artwork, using only CSS, so all artworks resize proportionally and fit fully into their defined width & height?

The original aspect-ratio should be respected.

In this case I would like the artwork contents to resize to 100x100px box as icons. The below snippet doesnt work, since it just seems to CROP the window instead of resizing the inner contents.

svg {
  width:  100px;
  height: 100px;
  fill:   blue;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg>
    <polygon points="100,0 30,200 200,70 0,70 170,200"/>
</svg>

<svg >
    <polygon points="0,0 200,140 110,200"/>
</svg>

<svg>
    <ellipse cx="200" cy="70" rx="200" ry="40" />
</svg></code>```

I'm gtting this: (looks more like a crop)

But I would like to get this: (proportionally scaled to the edge of the box)

答:
Add viewBox to keep the aspect ratio and set 100% height and width to fill the svg container.

svg{
  width:100px;
  height:100px;
  background-color: red;
}
svg * {
  width:  100%;
  height: 100%;
  fill:   blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewbox="0 0 200 200">
  <polygon points="100,0 30,200 200,70 0,70 170,200"/>
</svg>

<svg viewbox="0 0 200 200">
  <polygon points="0,0 200,140 110,200"/>
</svg>

<svg viewbox="0 0 400 70">
  <ellipse cx="200" cy="70" rx="200" ry="40" />
</svg></code>```

Body:
How can I scale or resize inline SVG vector artwork, using only CSS, so all artworks resize proportionally and fit fully into their defined width & height?

The original aspect-ratio should be respected.

In this case I would like the artwork contents to resize to 100x100px box as icons. The below snippet doesnt work, since it just seems to CROP the window instead of resizing the inner contents.

svg {
  width:  100px;
  height: 100px;
  fill:   blue;
  background-color: red;
}

<svg>
    <polygon points="100,0 30,200 200,70 0,70 170,200"/>
</svg>

<svg >
    <polygon points="0,0 200,140 110,200"/>
</svg>

<svg>
    <ellipse cx="200" cy="70" rx="200" ry="40" />
</svg>

I'm gtting this: (looks more like a crop)

But I would like to get this: (proportionally scaled to the edge of the box)

Body:
Add viewBox to keep the aspect ratio and set 100% height and width to fill the svg container.

svg{
  width:100px;
  height:100px;
  background-color: red;
}
svg * {
  width:  100%;
  height: 100%;
  fill:   blue;
}

<svg viewbox="0 0 200 200">
  <polygon points="100,0 30,200 200,70 0,70 170,200"/>
</svg>

<svg viewbox="0 0 200 200">
  <polygon points="0,0 200,140 110,200"/>
</svg>

<svg viewbox="0 0 400 70">
  <ellipse cx="200" cy="70" rx="200" ry="40" />
</svg>


问:
ImageMagick 2 pictures on top of 1
I'm using ImageMagick command-line options to create an animation out of several frames. I got it to work but I need to composite 2 pictures onto a third one. Is this possible? So far I have this code :

```<code>convert pic1.jpg pic2.jpg -geometry +x +y -composite  result.png
</code>```

This line puts pic2 on top of pic1, is it possible to put 2 pictures on pic1 similar to this:

```<code>convert pic1.jpg pic2.jpg -geometry +x +y -composite pic3.jpg +x +y -composite result.png
</code>```

Something like this if you get my logic

答:
Here's how that looks:

```<code>magick xc:blue[600x400\!]                           \
   xc:red[100x100\!]  -geometry +100+20  -composite \
   xc:lime[200x100\!] -geometry +300+200 -composite result.png
</code>```

Title: ImageMagick 2 pictures on top of 1

Body:
I'm using ImageMagick command-line options to create an animation out of several frames. I got it to work but I need to composite 2 pictures onto a third one. Is this possible? So far I have this code :

convert pic1.jpg pic2.jpg -geometry +x +y -composite  result.png

This line puts pic2 on top of pic1, is it possible to put 2 pictures on pic1 similar to this:

convert pic1.jpg pic2.jpg -geometry +x +y -composite pic3.jpg +x +y -composite result.png

Something like this if you get my logic

Body:
Here's how that looks:

magick xc:blue[600x400\!]                           \
   xc:red[100x100\!]  -geometry +100+20  -composite \
   xc:lime[200x100\!] -geometry +300+200 -composite result.png


问:
Dictionary: assign name of list to dictionary if string in list
Set up

I have the following list of lists of groups,

```<code>lofl=[A,B,...,N]
</code>```

where each group contains subgroups,

```<code>A=['A1','A2','A3',...,An]
B=['B1','B2','B3',...,Bn]
# ⋮           ⋮
N=['N1','N2','N3',...,Nn]
</code>```

Finally, I have a dictionary data.

Intention

I want to check if e.g. the subgroup An is in lofl, and if so, I want to assign its string name 'A' to data['group'] and assign An to data['subgroup'].

Note: in my actual data set, A,B,...,N and An,Bn,...,Nn are all names without numbers.

Current code

```<code>if x in lofl:
   if x in A:
      data['group']='A'
      data['subgroup']=x
   elif x in B:
      data['group']='B'
      data['subgroup']=x
   #     ⋮
   elif x in N:
      data['group']='N'
      data['subgroup']=x
   else:
      data['group']='unknown'
      data['subgroup']=x
</code>```

Problem

The code is a bit long. Moreover, I want to reuse the code on different datasets, for which the group names differ. I'd like to avoid to have to replace the names in the code for each dataset. Any suggestions?

答:
Avoid long lists of variable names that all point to the same kind of data. Use a dictionary instead:

```<code>subgroups = {
    'A': ['A1','A2','A3',...,An]
    'B': ['B1','B2','B3',...,Bn],
    # ⋮           ⋮
    'N': ['N1','N2','N3',...,Nn],
}
</code>```

Now you can replace your separate if..elif..else tree with a loop:

```<code>if x in lofl:
    data['subgroup'] = x
    for name, subgroup in subgroups.items():
        if x in subgroup:
            data['group'] = name
            break
    else:
        data['group'] = 'unknown'
</code>```

You may want to consider creating indices; looping over all those lists and testing each one is expensive (each in test must loop through the full list for instance). Consider using sets instead of lists (testing for set membership takes O(1) constant time rather than O(N) linear time) and/or an index (like a dictionary mapping values in the subgroups lists to the key they belong to, so all you have to do is use index.get(x, 'unknown') rather than a loop).

Body:
Set up

I have the following list of lists of groups,

lofl=[A,B,...,N]

where each group contains subgroups,

A=['A1','A2','A3',...,An]
B=['B1','B2','B3',...,Bn]
# ⋮           ⋮
N=['N1','N2','N3',...,Nn]

Finally, I have a dictionary data.

Intention

I want to check if e.g. the subgroup An is in lofl, and if so, I want to assign its string name 'A' to data['group'] and assign An to data['subgroup'].

Note: in my actual data set, A,B,...,N and An,Bn,...,Nn are all names without numbers.

Current code

if x in lofl:
   if x in A:
      data['group']='A'
      data['subgroup']=x
   elif x in B:
      data['group']='B'
      data['subgroup']=x
   #     ⋮
   elif x in N:
      data['group']='N'
      data['subgroup']=x
   else:
      data['group']='unknown'
      data['subgroup']=x

Problem

The code is a bit long. Moreover, I want to reuse the code on different datasets, for which the group names differ. I'd like to avoid to have to replace the names in the code for each dataset. Any suggestions?

Body:
Avoid long lists of variable names that all point to the same kind of data. Use a dictionary instead:

subgroups = {
    'A': ['A1','A2','A3',...,An]
    'B': ['B1','B2','B3',...,Bn],
    # ⋮           ⋮
    'N': ['N1','N2','N3',...,Nn],
}

Now you can replace your separate if..elif..else tree with a loop:

if x in lofl:
    data['subgroup'] = x
    for name, subgroup in subgroups.items():
        if x in subgroup:
            data['group'] = name
            break
    else:
        data['group'] = 'unknown'

You may want to consider creating indices; looping over all those lists and testing each one is expensive (each in test must loop through the full list for instance). Consider using sets instead of lists (testing for set membership takes O(1) constant time rather than O(N) linear time) and/or an index (like a dictionary mapping values in the subgroups lists to the key they belong to, so all you have to do is use index.get(x, 'unknown') rather than a loop).


问:
Low memory image resizing
I am looking for some advice on how to construct a very low memory image resizing program that will be run as a child process of my nodejs application in linux.

The solution I am looking for is a linux executable that will take a base64 string image (uploaded from a client) using stdin, resizing the photo to a specified size and then pumping the resulting image data back through stdout.

I've looked into image magick and it might be what I end up using, but I figured I would ask and see if anyone had a suggestion.

Suggestions of libraries or examples of pre compiled executables in C/C++ would be greatly appreciated. Also a helpful answer would include general strategies for low memory image resizing.

Thank you

答:
Depending on the image formats you want to support, it's almost surely possible to perform incremental decoding and scaling by decoding only a few lines at a time and discarding the data once you write the output. However it may require writing your own code or adapting an existing decoder library to support this kind of operation.

It's also worth noting that downsizing giant jpegs can be performed efficiently by simply skipping the high-frequency coefficients and using a smaller IDCT. For example, to decode at half width and half height, discard all but the upper-left quadrant of the coefficients (horizontal and vertical frequency < 4) and use a 4x4 IDCT on them instead of the usual 8x8. Both the libjpeg decoder and the libavcodec decoder support this operation for power-of-2 scalings (1/2, 1/4, or 1/8). This type of approach might make incremental decoding/scaling unnecessary.

You can try it out with djpeg -scale 1/4 < src.jpg | cjpeg > dest.jpg. If you want a fixed output size, you'll probably first scale by whichever of 1/2, 1/4, or 1/8 puts you closest to the desired size without going to low, then performing interpolation to go the final step, e.g. djpeg -scale 1/4 < src.jpg | convert pnm:- -scale 640x480 dest.jpg.

Title: Low memory image resizing


问:
Changing color of placeholder text in my <textarea> for my ionic 2 application

placeholder is red in color before i enter text into it , i want my placeholder to stay in default color

refering to this answer

HTML

```<code><textarea  #myInput id="myInput" rows="1"  placeholder="Enter Question here" maxLength="100" (keyup)="resize()"  [(ngModel)]="addQuestion">
    </textarea>
</code>```

SCSS file

```<code>#myInput {
width: calc(100% - 10px);
border: 0;
border-radius: 0;
background: transparent;
}
</code>```

ts file

```<code>  @ViewChild('myInput') myInput: ElementRef;
   resize() {
    this.myInput.nativeElement.style.height = this.myInput.nativeElement.scrollHeight + 'px';
}
</code>```

答:
Ionic uses autoprefixer in its build process.

you could use the psuedo-element ::placeholder. Try

```<code> #myInput::placeholder{
    color:red
 }
</code>```

Body:
placeholder is red in color before i enter text into it , i want my placeholder to stay in default color

refering to this answer

HTML

<textarea  #myInput id="myInput" rows="1"  placeholder="Enter Question here" maxLength="100" (keyup)="resize()"  [(ngModel)]="addQuestion">
    </textarea>

SCSS file

#myInput {
width: calc(100% - 10px);
border: 0;
border-radius: 0;
background: transparent;
}

ts file

  @ViewChild('myInput') myInput: ElementRef;
   resize() {
    this.myInput.nativeElement.style.height = this.myInput.nativeElement.scrollHeight + 'px';
}

Body:
Ionic uses autoprefixer in its build process.

you could use the psuedo-element ::placeholder. Try

 #myInput::placeholder{
    color:red
 }


问:
SQL - extracting all pairs only once
Problem statement:

a table with N columns, K out of which are used in a criterion to determine pairs of rows

such a criterion involving the K columns can simply be if columns c_1, c2, .. c_k are equal for the two different rows part of a pair (the criterion itself is not relevant, only the fact that it must be used)

the requirement is to extract all potential pairs, but only once. This means that if for a row there are more than 2 potential other rows that can form a pair given the above criterion, then only one pair must be extracted

Simple example:

Input table:

```
A | B | C
x | y | z
w | y | z
u | y | z
u | v | z
v | v | z
```

Criterion: B and C columns must be the same for two rows to be part of a pair.

Output:

```
x | y | z
w | y | z
u | v | z
v | v | z
```

What hints do you have for solving the problem in pure SQL (or in the Oracle dialect, if specific features help)?

答:
If you can use window analytic function:

```<code>CREATE TABLE TT1 (A VARCHAR(4), B VARCHAR(4), C VARCHAR(4))
INSERT INTO TT1 VALUES ('x','y','z')
INSERT INTO TT1 VALUES ('w','y','z')
INSERT INTO TT1 VALUES ('u','y','z')
INSERT INTO TT1 VALUES ('u','v','z')
INSERT INTO TT1 VALUES ('v','v','z')
INSERT INTO TT1 VALUES ('k','w','z')

SELECT A.A, A.B, A.C
FROM
(SELECT *, ROW_NUMBER() OVER (PARTITION BY B,C ORDER BY A DESC) RN, COUNT(*) OVER (PARTITION BY B,C ) RC
FROM TT1) A
WHERE A.RN <=2 AND RC>1
</code>```

Output:

```<code>A    B    C
---- ---- ----
v    v    z
u    v    z
x    y    z
w    y    z
</code>```

Title: SQL - extracting all pairs only once

Body:
Problem statement:

a table with N columns, K out of which are used in a criterion to determine pairs of rows

such a criterion involving the K columns can simply be if columns c_1, c2, .. c_k are equal for the two different rows part of a pair (the criterion itself is not relevant, only the fact that it must be used)

the requirement is to extract all potential pairs, but only once. This means that if for a row there are more than 2 potential other rows that can form a pair given the above criterion, then only one pair must be extracted

Simple example:

Input table:

A | B | C
x | y | z
w | y | z
u | y | z
u | v | z
v | v | z

Criterion: B and C columns must be the same for two rows to be part of a pair.

Output:

x | y | z
w | y | z
u | v | z
v | v | z

What hints do you have for solving the problem in pure SQL (or in the Oracle dialect, if specific features help)?

Body:
If you can use window analytic function:

CREATE TABLE TT1 (A VARCHAR(4), B VARCHAR(4), C VARCHAR(4))
INSERT INTO TT1 VALUES ('x','y','z')
INSERT INTO TT1 VALUES ('w','y','z')
INSERT INTO TT1 VALUES ('u','y','z')
INSERT INTO TT1 VALUES ('u','v','z')
INSERT INTO TT1 VALUES ('v','v','z')
INSERT INTO TT1 VALUES ('k','w','z')

SELECT A.A, A.B, A.C
FROM
(SELECT *, ROW_NUMBER() OVER (PARTITION BY B,C ORDER BY A DESC) RN, COUNT(*) OVER (PARTITION BY B,C ) RC
FROM TT1) A
WHERE A.RN <=2 AND RC>1

Output:

A    B    C
---- ---- ----
v    v    z
u    v    z
x    y    z
w    y    z