问:
Curious about how to specify the number of core for MPI in order to get the fastest scientific computation
I have been running several scientific program package in conjunction with MPI by using the following command

```<code>nohup mpirun -np N -x OMP_NUM_THREADS=M program.exe < input > output &
</code>```

where the value of N and M depend on the physical CPU cores of my machine. For example, my machine has the specification like this

```<code>Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                24
On-line CPU(s) list:   0-23
Thread(s) per core:    2
Core(s) per socket:    6
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 45
Model name:            Intel(R) Xeon(R) CPU E5-2440 0 @ 2.40GHz
Stepping:              7
</code>```

In this case, I first tried setting with N = 24 and M = 1, so the calculation ran very slowly. Then I changed N and M to 12 and 2 respectively. So I found that the latter had obviously provided me the fastest computation.

I was wondering that why did I set N & M are 12 and 2 provide more performance higher than the first case ?

答:
indeeed there is no absolute rule on how to run MPI+OpenMP application.
I agree with all Gilles said.
so I want to talk about the CPU in your case.

in the specification you give, it shows the system enables hyper-thread.
but this not always helps. your computer has 12 physical cores in fact.
so I advice you try some combinations that make M * N = 12 to 24,
like 12*1, 6*2, 6*3
which one is best, depends on how well your application.

Body:
I have been running several scientific program package in conjunction with MPI by using the following command

nohup mpirun -np N -x OMP_NUM_THREADS=M program.exe < input > output &

where the value of N and M depend on the physical CPU cores of my machine. For example, my machine has the specification like this

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                24
On-line CPU(s) list:   0-23
Thread(s) per core:    2
Core(s) per socket:    6
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 45
Model name:            Intel(R) Xeon(R) CPU E5-2440 0 @ 2.40GHz
Stepping:              7

In this case, I first tried setting with N = 24 and M = 1, so the calculation ran very slowly. Then I changed N and M to 12 and 2 respectively. So I found that the latter had obviously provided me the fastest computation.

I was wondering that why did I set N & M are 12 and 2 provide more performance higher than the first case ?


来源: stackexchange

问:
Apache2 hide port
ciao a tutti,
I have a public IP and a home router that allows me to port forward as many ports as I need.

For testing purposes I need to reach two internal IPs using HTTPS. the first site is a netscaler gateway that uses 443, and is working fine; for various reasons, I'd rather not change it.

the second IP is an apache2 raspbian-based website and should use 444 (or any other port for that matter) and here is where problems start.

I can easily reach the site from outside if I use the https://example.com:444 format; however I would like to hide the :444 at the end of the address.

I have checked several threads in this regards and all seem to offer two choices:

proxy reverse: proxypreservehost / proxypass / proxypassreverse

rewrite: rewritecond / rewriterule

I can't paste more than 2 links but these are the standard examples I found on this site.

I succesfully restart apache2 in both cases, which in my very limited knowledge means 'things are ok' but i still get the :444 at the end of the address.

hence my questions,

is it even possible to obtain what I'd like to have?

what am I doing wrong?

your input is very appreciated.

thanks

regards

leo

答:
If you only have 1 external IP address, you won't be able to configure your firewall to forward port 433 to different IP addresses.

One device will have to proxy (at some layer) to the other. It seems like a straightforward task in either server.

ContentLicense: CC BY-SA 3.0

Title: Apache2 hide port


问:
HTML blank screen
Why does this result in a blank screen?

01_using_javascript.html:

```<code><!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
      <script src="01_using_javascript.js"> </script>
    </head>

    <body>
        <p id="demo"></p>
    </body>
  </html>
</code>```

01_using_javascript.js:

```<code>document.getElementById("demo").innerHTML = Hi;
</code>```

答:
Add quotes to the string you want to insert:

document.getElementById("demo").innerHTML = "Hi";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
      <script src="01_using_javascript.js"> </script>
    </head>

    <body>
        <p id="demo"></p>
    </body>
  </html></code>```

Title: HTML blank screen

Body:
Why does this result in a blank screen?

01_using_javascript.html:

<!DOCTYPE html>

      <title> Test </title>

01_using_javascript.js:

document.getElementById("demo").innerHTML = Hi;

Body:
Add quotes to the string you want to insert:

document.getElementById("demo").innerHTML = "Hi";

<!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
      <script src="01_using_javascript.js"> </script>
    </head>

    <body>
        <p id="demo"></p>
    </body>
  </html>


问:
library not found for -lPayPalMPL
I have added and used PayPal MPL library. I can use the code but can't build the App. There is a linker error:
"ld: library not found for -lPayPalMPL
clang: error: linker command failed with exit code 1 (use -v to see invocation)"
Does anyone know any solution?</p>

答: That was due to a space in Library Search Path. Simple enclose your library search path in double quotes("search_path") and its Done.</p>

Title: library not found for -lPayPalMPL


问:
How to kill/stop a long SQL query immediately?
I am using SQL server 2008 and its management studio. I executed a query that yields many rows. I tried to cancel it via the red cancel button, but it has not stopped for the past 10 minutes. It usually stops within 3 minutes.

What could the reason be and how do I stop it immediately ?

答:
If you cancel and see that run

```<code> sp_who2 'active'
</code>```

(Activity Monitor won't be available on old sql server 2000   FYI  )

Spot the SPID you wish to kill   e.g.   81

```<code>Kill 81
</code>```

Run the   sp_who2 'active'  again and you will probably notice it is sleeping  ... rolling back

To get the STATUS run again the KILL

```<code>Kill 81
</code>```

Then you will get a message like this

```<code> SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.
</code>```

Body:
If you cancel and see that run

 sp_who2 'active'

(Activity Monitor won't be available on old sql server 2000   FYI  )

Spot the SPID you wish to kill   e.g.   81

Kill 81

Run the   sp_who2 'active'  again and you will probably notice it is sleeping  ... rolling back

To get the STATUS run again the KILL

Kill 81

Then you will get a message like this

 SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.

ContentLicense: CC BY-SA 4.0


问:
Can Windows Server 2016 EC2 mount EFS?
I am new to AWS. I have seen numerous definitive answers saying Windows and AWS EFS can't work with each other. Is it still the case with Windows Server 2016?</p>

答:
No. Windows servers cannot currently (as at June 2017) mount Amazon EFS volumes.

(I don't know if it will be available in future, but I inserted the date because it might be introduced in future.)

Title: Can Windows Server 2016 EC2 mount EFS?


问:
SQL Join Query with Character Length
Help!  I'm getting errors in the following query...

```<code>SELECT * FROM PARTFILES INNER JOIN PRODCODE ON PRODCODE.PRODCODE = PARTFILES.PARTNO WHERE (PRODCODE.PRODCODE = "SERVICE") AND (PARTFILES.PARTNO LENGTH(PARTFILES.PARTNO)<10 ) ORDER BY PARTFILES.PARTNO ;
</code>```

I'm totally green on SQL, but I know the jist of my problem is in this area:

```<code>...(PARTFILES.PARTNO LENGTH(PARTFILES.PARTNO)<10 )...
</code>```

Basically, I want all the parts from the PARTFILES table that have a PROD.CODE of "SERVICE", but I ONLY want those that are less then 10 characters long.

Right now I'm getting:

DAO OpenRecordset Error

Error #3705 (Syntax error (missing operator) in query expression...

P.S. - Please don't judge, lol... I'm really new to this :-)

答:
should be using LEN and proper coding on the condition

```<code>LEN(PARTFILES.PARTNO)<10
</code>```

full query below

```<code>SELECT *
FROM PARTFILES
INNER JOIN PRODCODE ON
     PRODCODE.PRODCODE = PARTFILES.PARTNO
 WHERE PRODCODE.PRODCODE = 'SERVICE'
 AND LEN(PARTFILES.PARTNO)<10
 ORDER BY PARTFILES.PARTNO
</code>```

Title: SQL Join Query with Character Length

Body:
Help!  I'm getting errors in the following query...

SELECT * FROM PARTFILES INNER JOIN PRODCODE ON PRODCODE.PRODCODE = PARTFILES.PARTNO WHERE (PRODCODE.PRODCODE = "SERVICE") AND (PARTFILES.PARTNO LENGTH(PARTFILES.PARTNO)<10 ) ORDER BY PARTFILES.PARTNO ;

I'm totally green on SQL, but I know the jist of my problem is in this area:

...(PARTFILES.PARTNO LENGTH(PARTFILES.PARTNO)<10 )...

Basically, I want all the parts from the PARTFILES table that have a PROD.CODE of "SERVICE", but I ONLY want those that are less then 10 characters long.

Right now I'm getting:

DAO OpenRecordset Error

Error #3705 (Syntax error (missing operator) in query expression...

P.S. - Please don't judge, lol... I'm really new to this :-)

Body:
should be using LEN and proper coding on the condition

LEN(PARTFILES.PARTNO)<10

full query below

SELECT *
FROM PARTFILES
INNER JOIN PRODCODE ON
     PRODCODE.PRODCODE = PARTFILES.PARTNO
 WHERE PRODCODE.PRODCODE = 'SERVICE'
 AND LEN(PARTFILES.PARTNO)<10
 ORDER BY PARTFILES.PARTNO


问:
error in fragment activity context
i have an error with my program about context,,,
i will combine navigation draw and list view, but any error with my code,

this is my fragment home activity

package com.marimuncak.mari_muncak;

import android.Manifest;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatCallback;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.marimuncak.mari_muncak.adapter.CustomListAdapter;
import com.marimuncak.mari_muncak.app.AppController;
import com.marimuncak.mari_muncak.module.Jarak;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by azoel on 6/8/2017.
 */
public class Home extends Fragment implements LocationListener,
        SwipeRefreshLayout.OnRefreshListener{

    private Context baseContext;

    public Home(){}
    RelativeLayout view;

    SwipeRefreshLayout swipe;
    ListView list;
    CustomListAdapter adapter;
    List<Jarak> itemList = new ArrayList<>();
    Double latitude, longitude;
    Criteria criteria;
    Location location;
    LocationManager locationManager;
    String provider;

    private static final String url = "https://marimuncak.000webhostapp.com/haversine.php?lat=";
    private static final String TAG = Home.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = (RelativeLayout) inflater.inflate(R.layout.home, container, false);

        list    = (ListView) view.findViewById(R.id.list);
        swipe   = (SwipeRefreshLayout) view.findViewById(R.id.swipe);

        CustomListAdapter adapter = new CustomListAdapter (getActivity(), itemList);
        list.setAdapter(adapter);

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();

        getActivity().setTitle("Home");

        return view;
    }

    @Override
    public void onRefresh(){
        lokasi();
    }

    // fungsi ngecek lokasi GPS device pengguna
    private void lokasi(){
        location = locationManager.getLastKnownLocation(provider);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // permintaan update lokasi device dalam waktu 10 detik
        locationManager.requestLocationUpdates(provider, 10000, 1, this);

        if(location!=null){
            onLocationChanged(location);
            callListVolley(latitude, longitude);
        }else{
            Toast.makeText(getBaseContext(), "Lokasi device pengguna tidak ditemukan.\nMohon hidupkan GPS.",
                    Toast.LENGTH_LONG).show();
           /* latitude longitude Alun-alun Demak sebagai default jika tidak ditemukan lokasi dari device pengguna */
            callListVolley(-6.894796, 110.638413);
        }
    }

    // untuk menampilkan lokasi wisata terdekat dari device pengguna
    private void callListVolley(double lat, double lng) {
        itemList.clear();
        adapter.notifyDataSetChanged();

        swipe.setRefreshing(true);

        JsonArrayRequest jArr = new JsonArrayRequest(url + lat +"&lng="+ lng,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Jarak j = new Jarak();
                                j.setNama(obj.getString("nama"));
                                j.setGambar(obj.getString("gambar"));

                                double jarak = Double.parseDouble(obj.getString("jarak"));

                                j.setJarak(""+round(jarak, 2));

                                itemList.add(j);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // memberitahu adapter jika ada perubahan data
                        adapter.notifyDataSetChanged();

                        swipe.setRefreshing(false);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                swipe.setRefreshing(false);
            }
        });

        // menambah permintaan ke queue
        AppController.getInstance().addToRequestQueue(jArr);
    }

    // untuk menyederhanakan angka dibelakan koma jarak
    public static double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

    // untuk menentukan lokasi gps dari device pengguna
    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        // untuk melihat latitude longitude posisi device pengguna pada logcat ditemukan atau tidak
        Log.d(TAG, " "+ latitude +", "+longitude);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    public Context getBaseContext() {

        return baseContext;
    }
}```
</div>
</div>
</p>

<p>this is a logchat</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\Home.java
Error:(94, 48) error: incompatible types: Home cannot be converted to Context
Error:(95, 89) error: incompatible types: Home cannot be converted to Context
D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\MainActivity.java
Error:(131, 5) error: method does not override or implement a method from a supertype
Note: D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1 mins 23.688 secs
Information:4 errors
Information:0 warnings
Information:See complete output in console</code>```

What should I do?
thanks a lot if you help me,,

答:
First, use android.support.v4.app.Fragment instead. you use android.app.Fragment

second at this line

```<code>if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
</code>```

change to

```<code>    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
</code>```

third, at line 131 make sure void onResponse(JSONArray response) exist at Response.Listener interface. i never use volley, so i don't know correct method.

Title: error in fragment activity context

Body:
i have an error with my program about context,,,
i will combine navigation draw and list view, but any error with my code,

this is my fragment home activity

package com.marimuncak.mari_muncak;

import android.Manifest;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatCallback;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.marimuncak.mari_muncak.adapter.CustomListAdapter;
import com.marimuncak.mari_muncak.app.AppController;
import com.marimuncak.mari_muncak.module.Jarak;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by azoel on 6/8/2017.
 */
public class Home extends Fragment implements LocationListener,
        SwipeRefreshLayout.OnRefreshListener{

    private Context baseContext;

    public Home(){}
    RelativeLayout view;

    SwipeRefreshLayout swipe;
    ListView list;
    CustomListAdapter adapter;
    List<Jarak> itemList = new ArrayList<>();
    Double latitude, longitude;
    Criteria criteria;
    Location location;
    LocationManager locationManager;
    String provider;

    private static final String url = "https://marimuncak.000webhostapp.com/haversine.php?lat=";
    private static final String TAG = Home.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = (RelativeLayout) inflater.inflate(R.layout.home, container, false);

        list    = (ListView) view.findViewById(R.id.list);
        swipe   = (SwipeRefreshLayout) view.findViewById(R.id.swipe);

        CustomListAdapter adapter = new CustomListAdapter (getActivity(), itemList);
        list.setAdapter(adapter);

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();

        getActivity().setTitle("Home");

        return view;
    }

    @Override
    public void onRefresh(){
        lokasi();
    }

    // fungsi ngecek lokasi GPS device pengguna
    private void lokasi(){
        location = locationManager.getLastKnownLocation(provider);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // permintaan update lokasi device dalam waktu 10 detik
        locationManager.requestLocationUpdates(provider, 10000, 1, this);

        if(location!=null){
            onLocationChanged(location);
            callListVolley(latitude, longitude);
        }else{
            Toast.makeText(getBaseContext(), "Lokasi device pengguna tidak ditemukan.\nMohon hidupkan GPS.",
                    Toast.LENGTH_LONG).show();
           /* latitude longitude Alun-alun Demak sebagai default jika tidak ditemukan lokasi dari device pengguna */
            callListVolley(-6.894796, 110.638413);
        }
    }

    // untuk menampilkan lokasi wisata terdekat dari device pengguna
    private void callListVolley(double lat, double lng) {
        itemList.clear();
        adapter.notifyDataSetChanged();

        swipe.setRefreshing(true);

        JsonArrayRequest jArr = new JsonArrayRequest(url + lat +"&lng="+ lng,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Jarak j = new Jarak();
                                j.setNama(obj.getString("nama"));
                                j.setGambar(obj.getString("gambar"));

                                double jarak = Double.parseDouble(obj.getString("jarak"));

                                j.setJarak(""+round(jarak, 2));

                                itemList.add(j);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // memberitahu adapter jika ada perubahan data
                        adapter.notifyDataSetChanged();

                        swipe.setRefreshing(false);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                swipe.setRefreshing(false);
            }
        });

        // menambah permintaan ke queue
        AppController.getInstance().addToRequestQueue(jArr);
    }

    // untuk menyederhanakan angka dibelakan koma jarak
    public static double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

    // untuk menentukan lokasi gps dari device pengguna
    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        // untuk melihat latitude longitude posisi device pengguna pada logcat ditemukan atau tidak
        Log.d(TAG, " "+ latitude +", "+longitude);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    public Context getBaseContext() {

        return baseContext;
    }
}

this is a logchat

:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\Home.java
Error:(94, 48) error: incompatible types: Home cannot be converted to Context
Error:(95, 89) error: incompatible types: Home cannot be converted to Context
D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\MainActivity.java
Error:(131, 5) error: method does not override or implement a method from a supertype
Note: D:\Users\azoel\AndroidStudioProjects\Mari_Muncak\app\src\main\java\com\marimuncak\mari_muncak\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1 mins 23.688 secs
Information:4 errors
Information:0 warnings
Information:See complete output in console

What should I do?
thanks a lot if you help me,,

Body:
First, use android.support.v4.app.Fragment instead. you use android.app.Fragment

second at this line

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)

change to

    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)

third, at line 131 make sure void onResponse(JSONArray response) exist at Response.Listener interface. i never use volley, so i don't know correct method.


答:
Not only do you have to wrap Hi with quotes but you also need to wait for the DOM to load the elements you want to modify. Either you put the script tag after the p element, or you use window.onload event, like so:

```<code>window.onload = function() {
  document.getElementById("demo").innerHTML = "Hi";
}
</code>```

Title: HTML blank screen

Body:
Not only do you have to wrap Hi with quotes but you also need to wait for the DOM to load the elements you want to modify. Either you put the script tag after the p element, or you use window.onload event, like so:

window.onload = function() {
  document.getElementById("demo").innerHTML = "Hi";
}


问:
C# Inheritance: How to invoke the base class constructor when i call the derived class constructor
I am trying to figure out how to invoke a base class constructor when I call the derived class constructor.

I have a class called "AdditionalAttachment" which is inherited from System.Net.Mail.Attachment.I have added 2 more properties to my new class so that i can have all the properties of existing Attachment class with my new properties

```<code>public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}
</code>```

Earlier i used to create constructor like

//objMs is a MemoryStream object

```<code>Attachment objAttachment = new Attachment(objMs, "somename.pdf")
</code>```

I am wondering how can I create the same kind of constructor to my class which will do the same thing as of the above constructor of the base class

答:
This will pass your parameters into the base class's constructor:</p>

```<code>public AdditionalAttachment(MemoryStream objMs, string displayName) : base(objMs, displayName)
{
   // and you can do anything you want additionally
   // here (the base class's constructor will have
   // already done its work by the time you get here)
}
</code>```

Body:
I am trying to figure out how to invoke a base class constructor when I call the derived class constructor.

I have a class called "AdditionalAttachment" which is inherited from System.Net.Mail.Attachment.I have added 2 more properties to my new class so that i can have all the properties of existing Attachment class with my new properties

public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}

Earlier i used to create constructor like

//objMs is a MemoryStream object

Attachment objAttachment = new Attachment(objMs, "somename.pdf")

I am wondering how can I create the same kind of constructor to my class which will do the same thing as of the above constructor of the base class

Body:
This will pass your parameters into the base class's constructor:

public AdditionalAttachment(MemoryStream objMs, string displayName) : base(objMs, displayName)
{
   // and you can do anything you want additionally
   // here (the base class's constructor will have
   // already done its work by the time you get here)
}

ContentLicense: CC BY-SA 2.5


问:
Unable to create a constant value of type. Only primitive types or enumeration types are supported in this context 3
```<code>readonly IDbSet<Company> _Companies;

_Companies = _uow.Set<Company>();

public IList<Company> GetAllByGroupNames(IList<CompanyGroupMappings> CompanyGroupMappings)
{
    return _Companies.Where(o => companyGroupMappings.Select(p => p.GroupName).Contains(o.GroupName)).ToList();
}
</code>```

This returns an error:

Unable to create a constant value of type 'CompanyGroupMappings'.
Only primitive types or enumeration types are supported in this context.
{System.Collections.ListDictionaryInternal}

How do I have to change it? Is it regarding the first list not being in the memory?

答:
Try the code as below:

```<code>return _Companies.Where(o => CompanyGroupMappings.Any(p => p.GroupName == o.GroupName)).ToList();
</code>```

Make sure to pass a List<CompanyGroupMappings> rather than IList<CompanyGroupMappings>

Body:
readonly IDbSet<Company> _Companies;

_Companies = _uow.Set<Company>();

public IList<Company> GetAllByGroupNames(IList<CompanyGroupMappings> CompanyGroupMappings)
{
    return _Companies.Where(o => companyGroupMappings.Select(p => p.GroupName).Contains(o.GroupName)).ToList();
}

This returns an error:

Unable to create a constant value of type 'CompanyGroupMappings'.
Only primitive types or enumeration types are supported in this context.
{System.Collections.ListDictionaryInternal}

How do I have to change it? Is it regarding the first list not being in the memory?

Body:
Try the code as below:

return _Companies.Where(o => CompanyGroupMappings.Any(p => p.GroupName == o.GroupName)).ToList();

Make sure to pass a List<CompanyGroupMappings> rather than IList<CompanyGroupMappings>


问:
Is there a way to get multiple Image Extensions, in a link?
```<code><img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="img-circle" width="60" <b class="hidden-xs">
</code>```

I am getting a User Image the Link is uploads/admin.jpg or also uploads/?php echo $_SESSION['username'];?>.jpg.

If they upload a .png how do I get it where it will choose the right extension for the Image so If it was a png instead of a JPG it would load the png image instead of the JPG? is there a way?

答:
```<code>if (file_exists('http://www.example.com/upload/'.$_SESSION['username'].'jpg'))
{
    $src = $_SESSION['username'].'jpg';
}
else
{
    $src = $_SESSION['username'].'png';
}

<img src="<?php echo $src; ?>" class="img-circle" width="60" <b class="hidden-xs">
</code>```

Body:
<img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="img-circle" width="60"

I am getting a User Image the Link is uploads/admin.jpg or also uploads/?php echo $_SESSION['username'];?>.jpg.

If they upload a .png how do I get it where it will choose the right extension for the Image so If it was a png instead of a JPG it would load the png image instead of the JPG? is there a way?


问:
Change default event sort order on FullCalendar month View
I have a fullcalendar working with multiple calendars displayed in the month view.  The different calendars are color coded.  I have the calendars sorted by name on all views, but when they are rendered in the FullCalendar display they are sorted by title of the event.

Is there anyway to override the default sort for the day?

答:
```<code>eventOrder: "eventProperty"
</code>```

More Information: https://fullcalendar.io/docs/event_rendering/eventOrder/

Body:
eventOrder: "eventProperty"

More Information: https://fullcalendar.io/docs/event_rendering/eventOrder/


问:
Does anyone know an applet showing an animation of the Johnson Algorithm?
Does anyone knows an applet showing an animation of the Johnson Algorithm?</p>

答: How about a step-by-step image for a small graph (see figure 25.6)</p>


问:
Angular2-App user-input changes in input-field changes input-fields in other browser-instances on other machines
Editing in the input-field in the browser for Angular2-App running on localhost, changes values of input-field in all other browsers running on other machines (tablet/smart-phone)

Should each device have an own instance of the Angular-Application, in its browser, don't interfering with each other?

workflow

I start the Angular2App with 'npm start' on lets say localhost(ip: 192.168.111.1:3000)

I connect from the same machine with a browser with http://localhost:3000

I connect from another device (e.g. Tablet, Smartphone) to Angular2App with http:/192.168.111.1:3000

The input-fields are displayed correct in all browsers on all devices

however editing in the input-field in the browser running on localhost changes values of input-field in all other browsers running on tablet/smart-phone

Code snippets:

login.component.ts

```<code>import {Component} from '@angular/core';

@Component({
  templateUrl: 'app/components/login/login.component.html',
  selector: 'login-comp'
    ,providers: []
    ,directives: []
})

export class LoginComponent {
  private userName: String;
  private userPw: String;
...
</code>```

login.component.html

```<code><div>
    <p>User: <input pInputText id="userName" (ngModel)="userName" /></p>
    <p>Password: <input pInputText id="userPw" (ngModel)="userPw" type="password"/></p>
    <p><button (click)="login()">login</button></p>
</div>
</code>```

答:
This is because you have "browser sync" installed.
To disable this, you must set the Node_modules\browser-sync\lib\default-config.js to false.

```<code>ghostMode: {
    clicks: false,
    scroll: false,
    location: false,
    forms: {
        submit: false,
        inputs: false,
        toggles: false
    }
}
</code>```

Body:
Editing in the input-field in the browser for Angular2-App running on localhost, changes values of input-field in all other browsers running on other machines (tablet/smart-phone)

Should each device have an own instance of the Angular-Application, in its browser, don't interfering with each other?

workflow

I start the Angular2App with 'npm start' on lets say localhost(ip: 192.168.111.1:3000)

I connect from the same machine with a browser with http://localhost:3000

I connect from another device (e.g. Tablet, Smartphone) to Angular2App with http:/192.168.111.1:3000

The input-fields are displayed correct in all browsers on all devices

however editing in the input-field in the browser running on localhost changes values of input-field in all other browsers running on tablet/smart-phone

Code snippets:

login.component.ts

import {Component} from '@angular/core';

@Component({
  templateUrl: 'app/components/login/login.component.html',
  selector: 'login-comp'
    ,providers: []
    ,directives: []
})

export class LoginComponent {
  private userName: String;
  private userPw: String;
...

login.component.html

User: <input pInputText id="userName" (ngModel)="userName" />

Password: <input pInputText id="userPw" (ngModel)="userPw" type="password"/>

<button (click)="login()">login</button>

Body:
This is because you have "browser sync" installed.
To disable this, you must set the Node_modules\browser-sync\lib\default-config.js to false.

ghostMode: {
    clicks: false,
    scroll: false,
    location: false,
    forms: {
        submit: false,
        inputs: false,
        toggles: false
    }
}


问:
How to call azure function with params
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:

```<code>var rp = require('request-promise');
var request = require('request');

module.exports = function (context //need to get the url) {
</code>```

and the function

```<code>{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 */1 * * *"
    }
  ],
  "disabled": false
}
</code>```

答:
Another possibility is if your parameters are stored somewhere in e.g. Azure Document DB (Cosmos).

You could still use a TimerTrigger to invoke the function, and include a DocumentDB input binding allowing you to query for the specific parameter values needed to execute the function.

Here's a C# example triggered by Timer, with a DocumentDB input binding. Note: I'm using the latest VS2017 Preview tooling for Azure functions.

```<code>[FunctionName("TimerTriggerCSharp")]
public static void Run(
   [TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log,
   [DocumentDB("test-db-dev", "TestingCollection", SqlQuery = "select * from c where c.doc = \"Test\"")] IEnumerable<dynamic> incomingDocuments)
 {..}
</code>```

With the following binding json:

```<code>{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    },
    {
      "type": "documentDB",
      "name": "incomingDocuments",
      "databaseName": "test-db-dev",
      "collectionName": "TestingCollection",
      "sqlQuery": "select * from c where c.docType = \"Test\"",
      "connection": "my-testing_DOCUMENTDB",
      "direction": "in"
    }
  ],
  "disabled": false
}
</code>```

Title: How to call azure function with params

Body:
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:

var rp = require('request-promise');
var request = require('request');

module.exports = function (context //need to get the url) {

and the function

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 */1 * * *"
    }
  ],
  "disabled": false
}

Body:
Another possibility is if your parameters are stored somewhere in e.g. Azure Document DB (Cosmos).

You could still use a TimerTrigger to invoke the function, and include a DocumentDB input binding allowing you to query for the specific parameter values needed to execute the function.

Here's a C# example triggered by Timer, with a DocumentDB input binding. Note: I'm using the latest VS2017 Preview tooling for Azure functions.

[FunctionName("TimerTriggerCSharp")]
public static void Run(
   [TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log,
   [DocumentDB("test-db-dev", "TestingCollection", SqlQuery = "select * from c where c.doc = \"Test\"")] IEnumerable<dynamic> incomingDocuments)
 {..}

With the following binding json:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    },
    {
      "type": "documentDB",
      "name": "incomingDocuments",
      "databaseName": "test-db-dev",
      "collectionName": "TestingCollection",
      "sqlQuery": "select * from c where c.docType = \"Test\"",
      "connection": "my-testing_DOCUMENTDB",
      "direction": "in"
    }
  ],
  "disabled": false
}


问:
Send email with embedded images through excel
Emails I send through excel do not display the embedded images on the receivers end. However the embedded images do display on my end. My guess is that the path is associated with my desktop.

How can I get the images to be displayed? Having trouble figuring out a fix. My code is below:

```<code>Sub EmailDailyFlow()
Dim mainWB As Workbook

Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook

With olMail
    .To = "email@gmail.com"
    .Cc = ""
    .Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
    .HTMLBody = "<html><body style='font-family: Times New Roman, Times, serif; font-size: 16px;'>" & _
            "<p>Please see below.</p>" & _
            "<p><u><b>Volatility:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MF.png'>" & _
            "<p><u><b>Muni:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MUNI.png'>" & _
            "<p><u><b>AFC:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFC.png'>" & _
            "<p><u><b>AFT:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFT.png'>" & _
            "<p><u><b>VIT:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\VIT.png'>" & _
            "<p>Thank you,</p>" & _
            "</body></html>"
.Send

End With
MsgBox ("Daily flow emails sent!")
End Sub`
</code>```

答:
Sub EmailDailyFlow()
    Dim oApp As Outlook.Application
    Dim oEmail As MailItem
    Dim colAttach As Outlook.Attachments
    Dim oAttach1 As Outlook.Attachment
    Dim oAttach2 As Outlook.Attachment
    Dim oAttach3 As Outlook.Attachment
    Dim oAttach4 As Outlook.Attachment
    Dim oAttach5 As Outlook.Attachment
    Dim olkPA As Outlook.PropertyAccessor
    Const PR_ATTACH_CONTENT_ID="http://schemas.microsoft.com/mapi/proptag/0x3712001F"

```<code>Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)

Set colAttach = oEmail.Attachments
Set oAttach1 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MF.png")
Set oAttach2 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\Muni.png")
Set oAttach3 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFC.png")
Set oAttach4 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFT.png")
Set oAttach5 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\VIT.png")
Set olkPA1 = oAttach1.PropertyAccessor
Set olkPA2 = oAttach2.PropertyAccessor
Set olkPA3 = oAttach3.PropertyAccessor
Set olkPA4 = oAttach4.PropertyAccessor
Set olkPA5 = oAttach5.PropertyAccessor

olkPA1.SetProperty PR_ATTACH_CONTENT_ID, "MF.png"
olkPA2.SetProperty PR_ATTACH_CONTENT_ID, "MUNI.png"
olkPA3.SetProperty PR_ATTACH_CONTENT_ID, "AFC.png"
olkPA4.SetProperty PR_ATTACH_CONTENT_ID, "AFT.png"
olkPA5.SetProperty PR_ATTACH_CONTENT_ID, "VIT.png"

oEmail.Close olSave

oEmail.HTMLBody = "<body style='font-family: Times New Roman, Times, serif; font-size: 16px;'><p>Please see below.</p>" & _
                    "<img src='cid:MF.png'>" & _
                    "<p><u><b>Muni:</u></b></p>" & _
                    "<img src='cid:MUNI.png'>" & _
                    "<p><u><b>afcCore:</u></b></p>" & _
                    "<img src='cid:AFC.png'>" & _
                    "<p><u><b>aft:</u></b></p>" & _
                    "<img src='cid:AFT.png'>" & _
                    "<p><u><b>VIT:</u></b></p>" & _
                    "<img src='cid:VIT.png'>" & _
                    "<p>Thank you,</p>" & _

                    "</body>"

oEmail.Save
oEmail.To = "email@email.com"
oEmail.CC = ""
oEmail.Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
oEmail.Send

Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing
</code>```

End Sub

Body:
Emails I send through excel do not display the embedded images on the receivers end. However the embedded images do display on my end. My guess is that the path is associated with my desktop.

How can I get the images to be displayed? Having trouble figuring out a fix. My code is below:

Sub EmailDailyFlow()
Dim mainWB As Workbook

Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook

With olMail
    .To = "email@gmail.com"
    .Cc = ""
    .Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
    .HTMLBody = "" & _
            "
Please see below.
" & _
            "
Volatility:
" & _
            "" & _
            "
Muni:
" & _
            "" & _
            "
AFC:
" & _
            "" & _
            "
AFT:
" & _
            "" & _
            "
VIT:
" & _
            "" & _
            "
Thank you,
" & _
            ""
.Send

End With
MsgBox ("Daily flow emails sent!")
End Sub`

Body:
Sub EmailDailyFlow()
    Dim oApp As Outlook.Application
    Dim oEmail As MailItem
    Dim colAttach As Outlook.Attachments
    Dim oAttach1 As Outlook.Attachment
    Dim oAttach2 As Outlook.Attachment
    Dim oAttach3 As Outlook.Attachment
    Dim oAttach4 As Outlook.Attachment
    Dim oAttach5 As Outlook.Attachment
    Dim olkPA As Outlook.PropertyAccessor
    Const PR_ATTACH_CONTENT_ID="http://schemas.microsoft.com/mapi/proptag/0x3712001F"

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)

Set colAttach = oEmail.Attachments
Set oAttach1 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MF.png")
Set oAttach2 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\Muni.png")
Set oAttach3 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFC.png")
Set oAttach4 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFT.png")
Set oAttach5 = colAttach.Add("C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\VIT.png")
Set olkPA1 = oAttach1.PropertyAccessor
Set olkPA2 = oAttach2.PropertyAccessor
Set olkPA3 = oAttach3.PropertyAccessor
Set olkPA4 = oAttach4.PropertyAccessor
Set olkPA5 = oAttach5.PropertyAccessor

olkPA1.SetProperty PR_ATTACH_CONTENT_ID, "MF.png"
olkPA2.SetProperty PR_ATTACH_CONTENT_ID, "MUNI.png"
olkPA3.SetProperty PR_ATTACH_CONTENT_ID, "AFC.png"
olkPA4.SetProperty PR_ATTACH_CONTENT_ID, "AFT.png"
olkPA5.SetProperty PR_ATTACH_CONTENT_ID, "VIT.png"

oEmail.Close olSave

oEmail.HTMLBody = "<body style='font-family: Times New Roman, Times, serif; font-size: 16px;'><p>Please see below.</p>" & _
                    "<img src='cid:MF.png'>" & _
                    "<p><u><b>Muni:</u></b></p>" & _
                    "<img src='cid:MUNI.png'>" & _
                    "<p><u><b>afcCore:</u></b></p>" & _
                    "<img src='cid:AFC.png'>" & _
                    "<p><u><b>aft:</u></b></p>" & _
                    "<img src='cid:AFT.png'>" & _
                    "<p><u><b>VIT:</u></b></p>" & _
                    "<img src='cid:VIT.png'>" & _
                    "<p>Thank you,</p>" & _

                    "</body>"

oEmail.Save
oEmail.To = "email@email.com"
oEmail.CC = ""
oEmail.Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
oEmail.Send

Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing

End Sub


问:
apache 2.4.25 Cipher Strength issue
I use Debian 8 and apache 2.4.25 from testing. I get a A+ from SSL labs. All field at 100% except Cipher Strength.

I tried lot of settings but my Cipher still contain "128", for example :  TLS_RSA_WITH_AES_128_CBC_SHA (0x2f)

I change Cipher into my ssl vhost conf and etc/apache2/mods-available/ssl.conf How can I use only the strongest cipger suite ?

Now my settings are : SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

答: Appending !SHA1 will knock out the weakest ones you have left.  If you wanted to be more surgical, you could append !AES128-SHA and follow the pattern from 'man ciphers' if something else stands out at you.</p>

Title: apache 2.4.25 Cipher Strength issue


问:
R: creating uneven levels of factor for a numeric variable
I have a set of values (100000 entries) ranging from -0.20 to +0.15, which are return percentages.

Bulk of the values lies between +3.5% and -3.5%

I am looking to convert this into a factor such that:

any return between -0.035 to +.035 are equally binned in 0.05 increments and

anything between -0.2 to -.035 is binned as one factor and

anything between 0.05 to .15 is binned as one factor variable.

Any thoughts on how I can achieve this in R? I did try cut, but it seems to bin only in equal increments.

答:
So I generated the vector that holds the values (out of uniform distribution)

```<code> library(data.table)
 set.seed(555)#in order to be reproducible
 N <- 100000#number of pseudonumbers to be generated
 min1=-0.035#arbitrary limits
 max1=0.035#idem

 samp <- runif(N,min = -0.2,max = 0.15)#create the vector

 level1 <- as.factor(ifelse(samp<=min1,paste0("(",min(samp),",",min1,"]"),NA))#create the first level
 level2 <- as.factor(ifelse(samp>=max1,paste0("[",max1,",",max(samp),")"),NA))#create the second level
 incr <- 0.005
 level3 <- cut(samp,seq(min1, max1, by = incr))#create the intermediate levels

 dt <- data.table(samp,level1,level2,level3)#put all together
 mylevels <- na.omit(unlist(matrix(t(dt[,-1]))))#the vector that contains in which range the samp belongs to
</code>```

For better visualization of results:

```<code>mylevels<-factor(mylevels,levels= unique(mylevels))
dt2<-dt[,.(samp,levels=mylevels)]
            samp                      levels
     1: -0.07023653 (-0.199996188434307,-0.035]
     2:  0.10889991   [0.035,0.149995080730878)
     3:  0.04246077   [0.035,0.149995080730878)
     4: -0.01193010              (-0.015,-0.01]
     5:  0.02607736                (0.025,0.03]
   ---
 99996: -0.04786692 (-0.199996188434307,-0.035]
 99997: -0.08700210 (-0.199996188434307,-0.035]
 99998:  0.09989973   [0.035,0.149995080730878)
 99999:  0.10095336   [0.035,0.149995080730878)
100000: -0.05555869 (-0.199996188434307,-0.035]
</code>```

Body:
So I generated the vector that holds the values (out of uniform distribution)

 library(data.table)
 set.seed(555)#in order to be reproducible
 N <- 100000#number of pseudonumbers to be generated
 min1=-0.035#arbitrary limits
 max1=0.035#idem

 samp <- runif(N,min = -0.2,max = 0.15)#create the vector

 level1 <- as.factor(ifelse(samp<=min1,paste0("(",min(samp),",",min1,"]"),NA))#create the first level
 level2 <- as.factor(ifelse(samp>=max1,paste0("[",max1,",",max(samp),")"),NA))#create the second level
 incr <- 0.005
 level3 <- cut(samp,seq(min1, max1, by = incr))#create the intermediate levels

 dt <- data.table(samp,level1,level2,level3)#put all together
 mylevels <- na.omit(unlist(matrix(t(dt[,-1]))))#the vector that contains in which range the samp belongs to

For better visualization of results:

mylevels<-factor(mylevels,levels= unique(mylevels))
dt2<-dt[,.(samp,levels=mylevels)]
            samp                      levels
     1: -0.07023653 (-0.199996188434307,-0.035]
     2:  0.10889991   [0.035,0.149995080730878)
     3:  0.04246077   [0.035,0.149995080730878)
     4: -0.01193010              (-0.015,-0.01]
     5:  0.02607736                (0.025,0.03]
   ---
 99996: -0.04786692 (-0.199996188434307,-0.035]
 99997: -0.08700210 (-0.199996188434307,-0.035]
 99998:  0.09989973   [0.035,0.149995080730878)
 99999:  0.10095336   [0.035,0.149995080730878)
100000: -0.05555869 (-0.199996188434307,-0.035]


问:
ClassNotFoundException on Galaxy Tab (only)
I have a working Android application. It works on more than 500 different devices. The manifest is

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.decamps.droid.photoid" android:versionCode="5"
android:versionName="1.4">
<application android:icon="@drawable/icon" android:label="@string/app_label"
    android:name="PhotoIDroid" android:description="@string/app_desc"
    android:debuggable="FALSE">
</code>```

But when it it launched from a Samsung Galaxy Tab, it doesn't start and crashes with:

java.lang.RuntimeException: Unable to
  instantiate application
  info.decamps.droid.photoid.PhotoIDroid:
  java.lang.ClassNotFoundException:
  info.decamps.droid.photoid.PhotoIDroid
  in loader
  dalvik.system.PathClassLoader[/data/app/info.decamps.droid.photoid-1.apk]
  at
  android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:670)
  at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:4483)
  at
  android.app.ActivityThread.access$3000(ActivityThread.java:135)
  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:2181)
  at
  android.os.Handler.dispatchMessage(Handler.java:99)
  at
  android.os.Looper.loop(Looper.java:144)
  at
  android.app.ActivityThread.main(ActivityThread.java:4937)
  at
  java.lang.reflect.Method.invokeNative(Native
  Method) at
  java.lang.reflect.Method.invoke(Method.java:521)
  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
  at
  dalvik.system.NativeStart.main(Native
  Method) Caused by:
  java.lang.ClassNotFoundException:
  info.decamps.droid.photoid.PhotoIDroid
  in loader
  dalvik.system.PathClassLoader[/data/app/info.decamps.droid.photoid-1.apk]
  at
  dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
  at
  java.lang.ClassLoader.loadClass(ClassLoader.java:573)
  at
  java.lang.ClassLoader.loadClass(ClassLoader.java:532)
  at
  android.app.Instrumentation.newApplication(Instrumentation.java:945)
  at
  android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:660)
  ... 11 more

How an the Samsung Galaxy not find the application class?
Any clue on how to resolve this?

I have been able to reproduce tis crash on the Samsung Galaxy emulator.

答: I have removed the android:name attribute declaration from the AndroidManifest.xml and it now works.

Body:
I have a working Android application. It works on more than 500 different devices. The manifest is

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.decamps.droid.photoid" android:versionCode="5"
android:versionName="1.4">
<application android:icon="@drawable/icon" android:label="@string/app_label"
    android:name="PhotoIDroid" android:description="@string/app_desc"
    android:debuggable="FALSE">

But when it it launched from a Samsung Galaxy Tab, it doesn't start and crashes with:

java.lang.RuntimeException: Unable to
  instantiate application
  info.decamps.droid.photoid.PhotoIDroid:
  java.lang.ClassNotFoundException:
  info.decamps.droid.photoid.PhotoIDroid
  in loader
  dalvik.system.PathClassLoader[/data/app/info.decamps.droid.photoid-1.apk]
  at
  android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:670)
  at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:4483)
  at
  android.app.ActivityThread.access$3000(ActivityThread.java:135)
  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:2181)
  at
  android.os.Handler.dispatchMessage(Handler.java:99)
  at
  android.os.Looper.loop(Looper.java:144)
  at
  android.app.ActivityThread.main(ActivityThread.java:4937)
  at
  java.lang.reflect.Method.invokeNative(Native
  Method) at
  java.lang.reflect.Method.invoke(Method.java:521)
  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
  at
  dalvik.system.NativeStart.main(Native
  Method) Caused by:
  java.lang.ClassNotFoundException:
  info.decamps.droid.photoid.PhotoIDroid
  in loader
  dalvik.system.PathClassLoader[/data/app/info.decamps.droid.photoid-1.apk]
  at
  dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
  at
  java.lang.ClassLoader.loadClass(ClassLoader.java:573)
  at
  java.lang.ClassLoader.loadClass(ClassLoader.java:532)
  at
  android.app.Instrumentation.newApplication(Instrumentation.java:945)
  at
  android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:660)
  ... 11 more

How an the Samsung Galaxy not find the application class?
Any clue on how to resolve this?

I have been able to reproduce tis crash on the Samsung Galaxy emulator.


问:
Google Cloud. Pub/Sub Android App
I'm try to send data throught pub/sub library to my topic in GoogleCloud

```<code>projects/navigator-cloud/topics/navigator-location
</code>```

Here is a project of a google map with a overlay image of a building, which I should use. I want to publish a JSON with some info like this: {"Username": "oscarhmg", "Location": "labproto", "Timestamp": "2016-12-04T15:29:05Z" }.

When the topic receive this info, in the building map appears a marker(This map shows in my application in a web view).  This functionality is already implemented, what I still do not understand at all is how to pass the message to publish on this topic through my android application. Any help would appreciate it

答:
Check out this Android Things tutorial that has the device directly publishing messages to Google Cloud Pub/Sub without going through a web server. The way to do the authentication is by building the .json credential into the Android app.

https://github.com/androidthings/weatherstation

Title: Google Cloud. Pub/Sub Android App

Body:
I'm try to send data throught pub/sub library to my topic in GoogleCloud

projects/navigator-cloud/topics/navigator-location

Here is a project of a google map with a overlay image of a building, which I should use. I want to publish a JSON with some info like this: {"Username": "oscarhmg", "Location": "labproto", "Timestamp": "2016-12-04T15:29:05Z" }.

When the topic receive this info, in the building map appears a marker(This map shows in my application in a web view).  This functionality is already implemented, what I still do not understand at all is how to pass the message to publish on this topic through my android application. Any help would appreciate it


问:
Way to use locust.io by supplying user list
I need to stress-test a system and http://locust.io seems like the best way to go about this. However, it looks like it is set up to use the same user every time. I need each spawn to log in as a different user. How do I go about setting that up? Alternatively, is there another system that would be good to use?</p>

答:
Piggy-backing on @heyman's answer here. The example code will work, but continuing to start / stop tests will eventually clear out the USER_CREDENTIALS list, and start to throw errors.

I ended up adding the following:

2023 Update

From v1.3.0 the events API has changed.

```<code>USER_CREDENTIALS = generate_users()

@events.spawning_complete.add_listener
def spawn_complete_handler(**kw):
    global USER_CREDENTIALS
    USER_CREDENTIALS = generate_users()

</code>```

Original answer

```<code>from locust import events # in addition to the other locust modules needed

def hatch_complete_handler(**kw):
    global USER_CREDENTIALS
    USER_CREDENTIALS = generate_users() # some function here to regenerate your list

events.hatch_complete += hatch_complete_handler
</code>```

This refreshes your user list once your swarm finishes hatching.

Also keep in mind that you'll need a list longer than the number of users you wish to spawn.

Body:
Piggy-backing on @heyman's answer here. The example code will work, but continuing to start / stop tests will eventually clear out the USER_CREDENTIALS list, and start to throw errors.

I ended up adding the following:

2023 Update

From v1.3.0 the events API has changed.

USER_CREDENTIALS = generate_users()

@events.spawning_complete.add_listener
def spawn_complete_handler(**kw):
    global USER_CREDENTIALS
    USER_CREDENTIALS = generate_users()

Original answer

from locust import events # in addition to the other locust modules needed

def hatch_complete_handler(**kw):
    global USER_CREDENTIALS
    USER_CREDENTIALS = generate_users() # some function here to regenerate your list

events.hatch_complete += hatch_complete_handler

This refreshes your user list once your swarm finishes hatching.

Also keep in mind that you'll need a list longer than the number of users you wish to spawn.


问:
Swift: Resize an AVPlayerLayer to match the bounds of its parent container
I have a local video playing using AVPlayer and AVPlayerLayer (Swift, iOS 8.2), and i need to resize the AVPlayerLayer (introPlayerLayer) when its parent view (introView) is resized, including on orientation change. So far nothing I have tried seems to work and the playerLayer has the wrong size and position.

The AVPlayer is set up using a local mp4 video, and the AVPlayerLayer is initialized using that player. The layer is then added as a sublayer to the parent view.

Here is my code:

```<code>func playIntro() {
    let path = NSBundle.mainBundle().pathForResource("intro", ofType: "mp4")
    let url  = NSURL.fileURLWithPath(path!)
    let introPlayer           = AVPlayer(URL: url)
    introPlayer.allowsExternalPlayback = false

    var introPlayerLayer = AVPlayerLayer(player: introPlayer)
    introView.layer.addSublayer(introPlayerLayer)
    introPlayerLayer.frame = introView.bounds

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: introPlayer.currentItem)

    introView.hidden = false
    introPlayer.play()
}
</code>```

Should I be adding the AVPlayerLayer as a sublayer of the UIView, or should I be subclassing the parent container (UIView) as shown in the "The Player View" section of https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html. If so, how would I write that PlayerView subclass (shown in Objective-C) in Swift?
Thank you in advance for any assistance.

答:
Swift 3.</p>

```<code>private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        var playerLayer: AVPlayerLayer?
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        playerLayer!.frame = self.view.frame
        self.view!.layer.addSublayer(playerLayer!)
        player.play()

    }
</code>```

Body:
I have a local video playing using AVPlayer and AVPlayerLayer (Swift, iOS 8.2), and i need to resize the AVPlayerLayer (introPlayerLayer) when its parent view (introView) is resized, including on orientation change. So far nothing I have tried seems to work and the playerLayer has the wrong size and position.

The AVPlayer is set up using a local mp4 video, and the AVPlayerLayer is initialized using that player. The layer is then added as a sublayer to the parent view.

Here is my code:

func playIntro() {
    let path = NSBundle.mainBundle().pathForResource("intro", ofType: "mp4")
    let url  = NSURL.fileURLWithPath(path!)
    let introPlayer           = AVPlayer(URL: url)
    introPlayer.allowsExternalPlayback = false

    var introPlayerLayer = AVPlayerLayer(player: introPlayer)
    introView.layer.addSublayer(introPlayerLayer)
    introPlayerLayer.frame = introView.bounds

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: introPlayer.currentItem)

    introView.hidden = false
    introPlayer.play()
}

Should I be adding the AVPlayerLayer as a sublayer of the UIView, or should I be subclassing the parent container (UIView) as shown in the "The Player View" section of https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html. If so, how would I write that PlayerView subclass (shown in Objective-C) in Swift?
Thank you in advance for any assistance.

Body:
Swift 3.

private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        var playerLayer: AVPlayerLayer?
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        playerLayer!.frame = self.view.frame
        self.view!.layer.addSublayer(playerLayer!)
        player.play()

    }


问:
Gocd pipeline linking to .git repository to generate artifact
I have a git repository and it contains maven project under it.For example

-repo-sample

    --sampleproject

        --src

        --pom.xml

so repo-sample as git repository and sampleproject under it which is a maven project.

Now in gocd pipeline,i want to trigger this project for every change and generate artifact.But unfortunately, i don't understand how will i give the path of my project.

It is easy for me to trigger it structure is like below.

repo-sample

     -src

     -pom.xml

I can give below command in go cd stages to trigger pipeline.
 - mvn clean deploy -Dbuild.number=${GO_PIPELINE_LABEL} --batch-mode
and Material will refer to - git@bitbucket.org:com/rep-sample.git
Above setup is working fine for me.
Now to refer it like this git@bitbucket.org:com/rep-sample.git/sampleproject
How will i give the setup.

答:
After you create your material it should look similar to this:

Because we haven't specified a Destination Directory, the material will be cloned to the current directory ./ and not inside repo-sample.

Inside your task where you'll be executing the mvn command, it should look something like this:

Taking note of the Working Directory. This will essentially cause GoCD to cd to the sampleproject folder. That's where the mvn clean package command will be executed from.


问:
C# Write image to ziparchive
I'm writing a C# .NET(v4.6.1) WinForms app that will save a file as a System.IO.Compression.ZipArchive. First, I open an image using a SaveFileDialog() method and then I assign it to variable of type System.Drawing.Image. Then I save the file, start with strings, integers and booleans going into a text file. Next, I try to save the image from the variable rather than from its original file path on the hard disk. Here's the code to save the file, text file followed by the image:

```<code>     public void SaveStd2Zip(string strfilepath, List<clsStandardQuestion> lstQuestions,
                               clsProjectInfo GameInfo, List<clsMedia> lstProjMed)
    {
        using (var ms = new MemoryStream())
        {
            using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                var projectInfo = archive.CreateEntry("ProjectInfo.txt");

                using (var entryStream = projectInfo.Open())
                using (var sw = new StreamWriter(entryStream))
                {
                    sw.WriteLine(GameInfo.strGameVersion);
                    sw.WriteLine(GameInfo.strProjectType);
                    sw.WriteLine(GameInfo.strGameTitle);
                    sw.WriteLine(GameInfo.strAuthor);
                    sw.WriteLine(GameInfo.strCreationDate);
                    sw.WriteLine(GameInfo.blTSImagePresent);
                    sw.WriteLine(GameInfo.blTSAudioPresent);
                    sw.WriteLine(GameInfo.blTSVideoPresent);
                    sw.WriteLine(GameInfo.blFSSImagePresent);
                    sw.WriteLine(GameInfo.blFSSAudioPresent);
                    sw.WriteLine(GameInfo.blFSSVideoPresent);
                    sw.WriteLine(GameInfo.intTotalQuestions);
                    sw.WriteLine(GameInfo.intTotalMediaItems);
                    sw.WriteLine(GameInfo.intTotalCategories);
                    sw.WriteLine(GameInfo.blTiebreakerPresent);

                    if (GameInfo.intTotalQuestions > 0)
                    {
                        for (int i = 0; i > lstQuestions.Count; i++)
                        {
                            sw.WriteLine(lstQuestions[i].blIsTiebreaker);
                            sw.WriteLine(lstQuestions[i].strQuestion);
                            sw.WriteLine(lstQuestions[i].intPoints);
                            sw.WriteLine(lstQuestions[i].intQuestionType);
                            sw.WriteLine(lstQuestions[i].blQuestionImagePresent);
                            sw.WriteLine(lstQuestions[i].blQuestionAudioPresent);
                            sw.WriteLine(lstQuestions[i].blQuestionVideoPresent);
                            sw.WriteLine(lstQuestions[i].blIncludeTimer);
                            sw.WriteLine(lstQuestions[i].intTimerTime);

                            // Multiple Choice variables...
                            sw.WriteLine(lstQuestions[i].blAIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerA);
                            sw.WriteLine(lstQuestions[i].blAIsCorrect);
                            sw.WriteLine(lstQuestions[i].blBIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerB);
                            sw.WriteLine(lstQuestions[i].blBIsCorrect);
                            sw.WriteLine(lstQuestions[i].blCIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerC);
                            sw.WriteLine(lstQuestions[i].blCIsCorrect);
                            sw.WriteLine(lstQuestions[i].blDIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerD);
                            sw.WriteLine(lstQuestions[i].blDIsCorrect);

                            // True Or False variables...
                            sw.WriteLine(lstQuestions[i].blTrueOrFalseAnswer);

                            // Fill-In-The-Blank variables...
                            sw.WriteLine(lstQuestions[i].strFIBAnswer);

                            // Answer Response variables...
                            sw.WriteLine(lstQuestions[i].strIAR);
                            sw.WriteLine(lstQuestions[i].strIAR);
                            sw.WriteLine(lstQuestions[i].blIARImagePresent);
                            sw.WriteLine(lstQuestions[i].blCARAudioPresent);
                            sw.WriteLine(lstQuestions[i].blCARVideoPresent);
                            sw.WriteLine(lstQuestions[i].blIARImagePresent);
                            sw.WriteLine(lstQuestions[i].blIARAudioPresent);
                            sw.WriteLine(lstQuestions[i].blIARVideoPresent);
                        }
                    }
                    sw.Close();
                }

                //Now write the image...
                if (GameInfo.blTSImagePresent == true)
                {
                    var TSImage = archive.CreateEntry("imgTSImage");

                    using (var entryStream = TSImage.Open())
                    using (var sw = new StreamWriter(entryStream))
                    {
                        clsMediaConverter MC = new clsMediaConverter();
                        sw.Write(GameInfo.imgTSImage.ToString());
                        sw.Close();
                    }
                }
             }
             using (var fileStream = new FileStream(strfilepath, FileMode.Create))
             {
                 ms.Seek(0, SeekOrigin.Begin);
                 ms.CopyTo(fileStream);
             }
          }
       }
</code>```

Problem: The image isn't saving. I open the resulting zip file in 7zip and try to open the image in a web browser and all I got was "System.Drawing.Image." Is it even possible to save an image to a zip archive this way? If not, how can I do it without writing the image file from its original location on the hard disk?

答:
You are using an streamwriter which writes only text, you need to save the image, not the class name:</p>

```<code>            //Now write the image...
            if (GameInfo.blTSImagePresent == true)
            {
                var TSImage = archive.CreateEntry("imgTSImage");

                using (var entryStream = TSImage.Open())
                {
                    GameInfo.imgTSImage.Save(entryStream, ImageFormat.Jpeg);
                }

            }
</code>```

Title: C# Write image to ziparchive

Body:
I'm writing a C# .NET(v4.6.1) WinForms app that will save a file as a System.IO.Compression.ZipArchive. First, I open an image using a SaveFileDialog() method and then I assign it to variable of type System.Drawing.Image. Then I save the file, start with strings, integers and booleans going into a text file. Next, I try to save the image from the variable rather than from its original file path on the hard disk. Here's the code to save the file, text file followed by the image:

     public void SaveStd2Zip(string strfilepath, List<clsStandardQuestion> lstQuestions,
                               clsProjectInfo GameInfo, List<clsMedia> lstProjMed)
    {
        using (var ms = new MemoryStream())
        {
            using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                var projectInfo = archive.CreateEntry("ProjectInfo.txt");

                using (var entryStream = projectInfo.Open())
                using (var sw = new StreamWriter(entryStream))
                {
                    sw.WriteLine(GameInfo.strGameVersion);
                    sw.WriteLine(GameInfo.strProjectType);
                    sw.WriteLine(GameInfo.strGameTitle);
                    sw.WriteLine(GameInfo.strAuthor);
                    sw.WriteLine(GameInfo.strCreationDate);
                    sw.WriteLine(GameInfo.blTSImagePresent);
                    sw.WriteLine(GameInfo.blTSAudioPresent);
                    sw.WriteLine(GameInfo.blTSVideoPresent);
                    sw.WriteLine(GameInfo.blFSSImagePresent);
                    sw.WriteLine(GameInfo.blFSSAudioPresent);
                    sw.WriteLine(GameInfo.blFSSVideoPresent);
                    sw.WriteLine(GameInfo.intTotalQuestions);
                    sw.WriteLine(GameInfo.intTotalMediaItems);
                    sw.WriteLine(GameInfo.intTotalCategories);
                    sw.WriteLine(GameInfo.blTiebreakerPresent);

                    if (GameInfo.intTotalQuestions > 0)
                    {
                        for (int i = 0; i > lstQuestions.Count; i++)
                        {
                            sw.WriteLine(lstQuestions[i].blIsTiebreaker);
                            sw.WriteLine(lstQuestions[i].strQuestion);
                            sw.WriteLine(lstQuestions[i].intPoints);
                            sw.WriteLine(lstQuestions[i].intQuestionType);
                            sw.WriteLine(lstQuestions[i].blQuestionImagePresent);
                            sw.WriteLine(lstQuestions[i].blQuestionAudioPresent);
                            sw.WriteLine(lstQuestions[i].blQuestionVideoPresent);
                            sw.WriteLine(lstQuestions[i].blIncludeTimer);
                            sw.WriteLine(lstQuestions[i].intTimerTime);

                            // Multiple Choice variables...
                            sw.WriteLine(lstQuestions[i].blAIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerA);
                            sw.WriteLine(lstQuestions[i].blAIsCorrect);
                            sw.WriteLine(lstQuestions[i].blBIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerB);
                            sw.WriteLine(lstQuestions[i].blBIsCorrect);
                            sw.WriteLine(lstQuestions[i].blCIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerC);
                            sw.WriteLine(lstQuestions[i].blCIsCorrect);
                            sw.WriteLine(lstQuestions[i].blDIsChecked);
                            sw.WriteLine(lstQuestions[i].strAnswerD);
                            sw.WriteLine(lstQuestions[i].blDIsCorrect);

                            // True Or False variables...
                            sw.WriteLine(lstQuestions[i].blTrueOrFalseAnswer);

                            // Fill-In-The-Blank variables...
                            sw.WriteLine(lstQuestions[i].strFIBAnswer);

                            // Answer Response variables...
                            sw.WriteLine(lstQuestions[i].strIAR);
                            sw.WriteLine(lstQuestions[i].strIAR);
                            sw.WriteLine(lstQuestions[i].blIARImagePresent);
                            sw.WriteLine(lstQuestions[i].blCARAudioPresent);
                            sw.WriteLine(lstQuestions[i].blCARVideoPresent);
                            sw.WriteLine(lstQuestions[i].blIARImagePresent);
                            sw.WriteLine(lstQuestions[i].blIARAudioPresent);
                            sw.WriteLine(lstQuestions[i].blIARVideoPresent);
                        }
                    }
                    sw.Close();
                }

                //Now write the image...
                if (GameInfo.blTSImagePresent == true)
                {
                    var TSImage = archive.CreateEntry("imgTSImage");

                    using (var entryStream = TSImage.Open())
                    using (var sw = new StreamWriter(entryStream))
                    {
                        clsMediaConverter MC = new clsMediaConverter();
                        sw.Write(GameInfo.imgTSImage.ToString());
                        sw.Close();
                    }
                }
             }
             using (var fileStream = new FileStream(strfilepath, FileMode.Create))
             {
                 ms.Seek(0, SeekOrigin.Begin);
                 ms.CopyTo(fileStream);
             }
          }
       }

Problem: The image isn't saving. I open the resulting zip file in 7zip and try to open the image in a web browser and all I got was "System.Drawing.Image." Is it even possible to save an image to a zip archive this way? If not, how can I do it without writing the image file from its original location on the hard disk?

Body:
You are using an streamwriter which writes only text, you need to save the image, not the class name:

            //Now write the image...
            if (GameInfo.blTSImagePresent == true)
            {
                var TSImage = archive.CreateEntry("imgTSImage");

                using (var entryStream = TSImage.Open())
                {
                    GameInfo.imgTSImage.Save(entryStream, ImageFormat.Jpeg);
                }

            }


答:
```<code>public class AdditionalAttachment: Attachment
{
   public AdditionalAttachment(param1, param2) : base(param1, param2){}
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}
</code>```

Title: C# Inheritance: How to invoke the base class constructor when i call the derived class constructor

Body:
I am trying to figure out how to invoke a base class constructor when I call the derived class constructor.

I have a class called "AdditionalAttachment" which is inherited from System.Net.Mail.Attachment.I have added 2 more properties to my new class so that i can have all the properties of existing Attachment class with my new properties

public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}

Earlier i used to create constructor like

//objMs is a MemoryStream object

Attachment objAttachment = new Attachment(objMs, "somename.pdf")

I am wondering how can I create the same kind of constructor to my class which will do the same thing as of the above constructor of the base class


问:
VSTS - Setting $(Rev:.r ) starting value
We are moving from TeamCity to VSTS for builds and one of the features of TeamCity we use is the build counter associated to a build definition that increments on every build as a part of our version number, e.g.

1.2.3.buildcounter

In VSTS I see I can use the $(Rev:.r) build property to get the build counter paradigm working, but I would like to be able to seed it at a given value so when we cut over from TeamCity we are sequentially at the next version.

答: You can't. If possible from a process perspective, just bump the version number to 1.2.4 and start fresh.</p>


问:
2-dimensional LSTM in Keras
I am new to Keras and LSTMs -- I want to train a model on 2-dimensional sequences (ie, movement in a grid-space), as opposed to 1-dimensional sequences (like characters of text).

As a test, I first tried just one dimension, and I am doing it successfully with the following setup:

```<code>model = Sequential()
model.add(LSTM(512, return_sequences=True, input_shape=X[0].shape, dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(512, return_sequences=False, dropout=0.2))
model.add(Dense(len(y[0]), activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer="rmsprop", metrics=['accuracy'])
model.fit(X, y, epochs=50)
</code>```

I'm formatting the data like this:

```<code>data = ## list of integers (1D)
inputs = []
outputs = []
for i in range(len(data) - SEQUENCE_LENGTH):
    inputs.append(data[i:i + SEQUENCE_LENGTH])
    outputs.append(data[i + SEQUENCE_LENGTH])
X = np.array([to_categorical(np.array(input), CATEGORY_LENGTH) for input in inputs])
y = to_categorical(np.array(outputs), CATEGORY_LENGTH)
</code>```

This is straightforward and converges quickly.

But if instead of a list of integers, my data consists of 2D tuples, I can no longer create categorical (one-hot) arrays to pass to the LSTM layers.

I've tried not using categorical arrays and simply passing the tuples to the model. In this case, I've changed my output layer to:

```<code>model.add(Dense(1, activation="linear"))
</code>```

But that does not converge, or at least moves incredibly slowly.

How can I adapt this code to handle input with additional dimensions?

答: This previous answer should apply to your question as well. The only difference is that you will have to convert your tuple to a data frame beforehand. </p>

Title: 2-dimensional LSTM in Keras

Body:
I am new to Keras and LSTMs -- I want to train a model on 2-dimensional sequences (ie, movement in a grid-space), as opposed to 1-dimensional sequences (like characters of text).

As a test, I first tried just one dimension, and I am doing it successfully with the following setup:

model = Sequential()
model.add(LSTM(512, return_sequences=True, input_shape=X[0].shape, dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(512, return_sequences=False, dropout=0.2))
model.add(Dense(len(y[0]), activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer="rmsprop", metrics=['accuracy'])
model.fit(X, y, epochs=50)

I'm formatting the data like this:

data = ## list of integers (1D)
inputs = []
outputs = []
for i in range(len(data) - SEQUENCE_LENGTH):
    inputs.append(data[i:i + SEQUENCE_LENGTH])
    outputs.append(data[i + SEQUENCE_LENGTH])
X = np.array([to_categorical(np.array(input), CATEGORY_LENGTH) for input in inputs])
y = to_categorical(np.array(outputs), CATEGORY_LENGTH)

This is straightforward and converges quickly.

But if instead of a list of integers, my data consists of 2D tuples, I can no longer create categorical (one-hot) arrays to pass to the LSTM layers.

I've tried not using categorical arrays and simply passing the tuples to the model. In this case, I've changed my output layer to:

model.add(Dense(1, activation="linear"))

But that does not converge, or at least moves incredibly slowly.

How can I adapt this code to handle input with additional dimensions?


问:
Run String in Text Box (containing Mid and InStrRev functions) as Code in VB NET
I have searched high and low and do not think this is a duplicate question as all the examples I found do not have functions (mid, InstrRev etc.) embedded in them.

I have a form containing 3 text boxes (tbFName, tbFNameExpression, tbFNameResult).

tbFName.Text contains an example filename and can be changed by the end user:

P05-158-4J-RM-001-REV-1.xlsx

tbFNameExpression.Text contains a string (which can be changed by the end user) I wish to run as code:

Mid(tbFName.Text , InStrRev(tbFName.Text , "-REV") + 1, 5)

This should populate tbFNameRev.Text with the Revision from the example document name.

REV-1

Obviously the text values can be changed by the end user, depending on what information is required in tbFNResult.

For example, if tbFNameExpression.Text = "Left(tbFName.Text,3)" then tbFNameResult should = "P05"

I have tried the following:

```<code>Dim strFNExpression As String = tbFNameExpression.Text
        tbFNameResult.Text = New DataTable().Compute(strFNExpression, Nothing)
</code>```

But this returns the error:
"The expression contains undefined function call Mid()."

I also tried a function using CodeDom to process an expression from here:
https://www.theswamp.org/index.php?topic=33503.0

答:
No easy way to do this. You can try regexes:</p>

```<code>tbFName.Text = "P05-158-4J-RM-001-REV-1.xlsx" 'Want to extract "REV-1"
tbFNameExpression.Text = "REV-."
tbFNameResult.Text = System.Text.RegularExpressions.Regex.Match(tbFName.Text, tbFNameExpression.Text).Value
</code>```

Body:
I have searched high and low and do not think this is a duplicate question as all the examples I found do not have functions (mid, InstrRev etc.) embedded in them.

I have a form containing 3 text boxes (tbFName, tbFNameExpression, tbFNameResult).

tbFName.Text contains an example filename and can be changed by the end user:

P05-158-4J-RM-001-REV-1.xlsx

tbFNameExpression.Text contains a string (which can be changed by the end user) I wish to run as code:

Mid(tbFName.Text , InStrRev(tbFName.Text , "-REV") + 1, 5)

This should populate tbFNameRev.Text with the Revision from the example document name.

REV-1

Obviously the text values can be changed by the end user, depending on what information is required in tbFNResult.

For example, if tbFNameExpression.Text = "Left(tbFName.Text,3)" then tbFNameResult should = "P05"

I have tried the following:

Dim strFNExpression As String = tbFNameExpression.Text
        tbFNameResult.Text = New DataTable().Compute(strFNExpression, Nothing)

But this returns the error:
"The expression contains undefined function call Mid()."

I also tried a function using CodeDom to process an expression from here:
https://www.theswamp.org/index.php?topic=33503.0

Body:
No easy way to do this. You can try regexes:

tbFName.Text = "P05-158-4J-RM-001-REV-1.xlsx" 'Want to extract "REV-1"
tbFNameExpression.Text = "REV-."
tbFNameResult.Text = System.Text.RegularExpressions.Regex.Match(tbFName.Text, tbFNameExpression.Text).Value


问:
Is it possible that I request an EC2 instance but can't get fulfilled?
Edit: This question is NOT to ask about "Spot Instances"; this question is to ask regular "On Demand Instance". I think I need to clarify this, after reading comments below.

Basically, my question is about whether I should consider the risk that when I need to launch an EC2 instance, but that EC2 region has run out of capacity and can't fulfill my request.

I understand the chance for the above situation is extremely low, but I'd like to understand if AWS has any SLA to make sure that situation/risk won't happen.

答:
Today it happened in an AWS account that I manage. If I am not wrong it was the family r4, exactly an r4.xlarge instance (4 hours ago) in Virgina Region. I had to choose a different AZ. That is why AWS always recommends working with more than one AZ.

But for that reason, I started to use Scheduled Reserved Instances

You always will have for a period of time a reserved capacity of a family type of instance(s).

Sure, it works if you have a defined schedule or workflow.

Hope it helps you.


问:
Camel and Spring: stop context when route is completed
I would like to run a route once and stop the context when the route is completed. Currently I do the usual Thread.sleep(3000) in the main Java class to leave some time for the route to finish but it's obviously not accurate, my route may take 1 second or 20 seconds I can not know in advance.

The Java class:

```<code>public static void main(String[] args) throws Exception {
    try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("camel-context.xml")) {
        CamelContext camelContext = SpringCamelContext.springCamelContext(context);
        // context.start(); // apparently not necessary
        camelContext.startRoute("route1");
        try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
        // context.stop(); // apparently not necessary
    }
}
</code>```

The Spring xml:

```<code><route id="route1" autoStartup="false">
    <from uri="timer://runOnce?repeatCount=1&delay=3000" />
    ...
</route>
</code>```

After reading http://camel.465427.n5.nabble.com/Need-control-back-in-the-Main-routine-so-that-we-can-terminate-JVM-td4483312.html#a4484845 especially the 4th post, from Claus Ibsen, I was thinking of using camelContext.getRouteStatus() in a loop with a Thread.sleep() but wherever I try to get the route status in the code (even after the Thread.sleep(3000)), the status is always "started". I don't know any other way to detect when the route is done.

What is the recommended way to stop the Camel context when a/all route(s) is/are completed, using Spring?

答:
A more elegant way would be to use a synchronisation mechanism provided by Java like CountDownLatch. Main thread will wait for the latch to be opened by the Route thread. Something like :

```<code> CountDownLatch latch = new CountDownLatch(1);
 camelContext.addRoutes(createRoute(latch));
</code>```

and somewhere in the createRoute Method add a processor at the end of the route to open the latch. This worked perfectly for me.

```<code>.process(new Processor() {
    @Override
    public void process(Exchange exchange) throws Exception {
        latch.countDown();
    }
});
</code>```

Body:
I would like to run a route once and stop the context when the route is completed. Currently I do the usual Thread.sleep(3000) in the main Java class to leave some time for the route to finish but it's obviously not accurate, my route may take 1 second or 20 seconds I can not know in advance.

The Java class:

public static void main(String[] args) throws Exception {
    try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("camel-context.xml")) {
        CamelContext camelContext = SpringCamelContext.springCamelContext(context);
        // context.start(); // apparently not necessary
        camelContext.startRoute("route1");
        try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
        // context.stop(); // apparently not necessary
    }
}

The Spring xml:

<route id="route1" autoStartup="false">
    <from uri="timer://runOnce?repeatCount=1&delay=3000" />
    ...
</route>

After reading http://camel.465427.n5.nabble.com/Need-control-back-in-the-Main-routine-so-that-we-can-terminate-JVM-td4483312.html#a4484845 especially the 4th post, from Claus Ibsen, I was thinking of using camelContext.getRouteStatus() in a loop with a Thread.sleep() but wherever I try to get the route status in the code (even after the Thread.sleep(3000)), the status is always "started". I don't know any other way to detect when the route is done.

What is the recommended way to stop the Camel context when a/all route(s) is/are completed, using Spring?

Body:
A more elegant way would be to use a synchronisation mechanism provided by Java like CountDownLatch. Main thread will wait for the latch to be opened by the Route thread. Something like :

 CountDownLatch latch = new CountDownLatch(1);
 camelContext.addRoutes(createRoute(latch));

and somewhere in the createRoute Method add a processor at the end of the route to open the latch. This worked perfectly for me.

.process(new Processor() {
    @Override
    public void process(Exchange exchange) throws Exception {
        latch.countDown();
    }
});


问:
library not found for -lPayPalMPL
I have added and used PayPal MPL library. I can use the code but can't build the App. There is a linker error:
"ld: library not found for -lPayPalMPL
clang: error: linker command failed with exit code 1 (use -v to see invocation)"
Does anyone know any solution?</p>

答: This issues comes when Library searchpath in build setting are missing. Just simply add its Done.</p>

Title: library not found for -lPayPalMPL


问:
How can I specify password encryption strength in openssl_pkey_new?
Using the PHP functions openssl_pkey_new and openssl_pkey_export to generate an RSA key, how can one ensure the toughest password protection?
e.g.

```<code>$conf = array (
    'digest_alg'       => 'sha256',
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
    'private_key_bits' => 2048,
    'encrypt_key'      => true,
);
$keypair = openssl_pkey_new( $conf );
openssl_pkey_export( $keypair, $keyout, 'foopass', $conf );
</code>```

Using openssl from the command line, I can specify tripledes like so:

```<code> openssl genrsa -des3 -passout pass:foopass 2048
</code>```

答:
As far as I know, specifying the encrypt_key as true in $configargs (like you did in your code example) already encrypts using Triple DES. If you check the output of $keyout, you will see:

```<code>-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,6FDE8DC937CC1C27
</code>```

This is true whether you use a sha1, md5, sha256 or any other digests.

In other words, 'encrypt_key' => true does exactly the same as openssl genrsa -des3.

Body:
Using the PHP functions openssl_pkey_new and openssl_pkey_export to generate an RSA key, how can one ensure the toughest password protection?
e.g.

$conf = array (
    'digest_alg'       => 'sha256',
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
    'private_key_bits' => 2048,
    'encrypt_key'      => true,
);
$keypair = openssl_pkey_new( $conf );
openssl_pkey_export( $keypair, $keyout, 'foopass', $conf );

Using openssl from the command line, I can specify tripledes like so:

 openssl genrsa -des3 -passout pass:foopass 2048

Body:
As far as I know, specifying the encrypt_key as true in $configargs (like you did in your code example) already encrypts using Triple DES. If you check the output of $keyout, you will see:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,6FDE8DC937CC1C27

This is true whether you use a sha1, md5, sha256 or any other digests.

In other words, 'encrypt_key' => true does exactly the same as openssl genrsa -des3.