问:
Photo rotated from camera (SAMSUNG device)
i hate this company. All them devices have a lot of bugs. Ok question :
Im trying to fix stupid problem  (which as i know exist more than 5 years)
Its photo taken from camera - rotated on 90 degree.
I have two devices :

```<code>  Nexus 5p and Samsung j2
  Nexus - work perfect. Everything fine.
  Samsung - photo rotated
</code>```

For example :

```<code>Photo size - nexus : Portrate : width 1000, height 1900.  Landscape :
width 1900 , height 1000
</code>```

Lets see on samsung device :

```<code>Photo size  - Portrate: width 1900(?????) height - 1000(????)
rotate to landscape : width 1900 height 1000
</code>```

After some testing : if make photo in landscape mode on samsung device - than everything ok. Photo not rotated

If make photo in PORTRATE - photo rotated on 90 degree. (BUT size of photo as on landscape (HOW ITS POSSIBLE) ?

Anyone know how to fix this stupid bug ? Maybe any can tell me how to detect orientation for camera ? Im using IntentActivity for photo :

```<code>String _path = Environment.getExternalStorageDirectory()
                                    + File.separator + "camera_img.jpg";
                            File file = new File(_path);
                            Uri outputFileUri = Uri.fromFile(file);
                            Intent intent = new Intent(
                                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                            startActivityForResult(intent, CAMERA_REQUEST);
</code>```

Any help  ?
I also add a checker , if its samsung device than rotate. But rotation good only if we create photo in portrate mode. In landscape everything fine. So i need somehow detected in which orientation photo was created. Any one know ?

答:
UPD 29.08.2018 I found that this method doesn't work with Samsung device based on Android 8+. I don't have Samsung s8 (for example) and can't understand why this again does not work there.  If someone can test and check why this not work - let's try to fix this together.

I found how to fix: well it's really stupid and very hard for me.

First step get activity result

```<code> @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

            String _path = Environment.getExternalStorageDirectory() + File.separator + "TakenFromCamera.jpg";
            String p1 = Environment.getExternalStorageDirectory().toString();
            String fName = "/TakenFromCamera.jpg";
            final int rotation = getImageOrientation(_path);
            File file = resaveBitmap(p1, fName, rotation);
            Bitmap mBitmap = BitmapFactory.decodeFile(_path);
</code>```

Main steps it's getImageOrientation before changes in file.

getImageOrientation (by path)

resave file (if need send to server, if you need only for preview we can skip this step)

get correct bitmap from file

For preview it's enough to perform only steps 1 and 3, and using this function - just rotate bitmap.

```<code>private Bitmap checkRotationFromCamera(Bitmap bitmap, String pathToFile, int rotate) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return rotatedBitmap;
    }
</code>```

getImageOrientation

```<code>public static int getImageOrientation(String imagePath) {
    int rotate = 0;
    try {
        ExifInterface exif = new ExifInterface(imagePath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return rotate;
}
</code>```

and resaveBitmap if need

```<code>private File resaveBitmap(String path, String filename, int rotation) { //help for fix landscape photos
        String extStorageDirectory = path;
        OutputStream outStream = null;
        File file = new File(filename);
        if (file.exists()) {
            file.delete();
            file = new File(extStorageDirectory, filename);
        }
        try {
            // make a new bitmap from your file
            Bitmap bitmap = BitmapFactory.decodeFile(path + filename);
            bitmap = checkRotationFromCamera(bitmap, path + filename, rotation);
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) ((float) bitmap.getWidth() * 0.3f), (int) ((float) bitmap.getHeight() * 0.3f), false);
            bitmap = Utils.getCircleImage(bitmap);
            outStream = new FileOutputStream(path + filename);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
</code>```

Body:
i hate this company. All them devices have a lot of bugs. Ok question :
Im trying to fix stupid problem  (which as i know exist more than 5 years)
Its photo taken from camera - rotated on 90 degree.
I have two devices :

  Nexus 5p and Samsung j2
  Nexus - work perfect. Everything fine.
  Samsung - photo rotated

For example :

Photo size - nexus : Portrate : width 1000, height 1900.  Landscape :
width 1900 , height 1000

Lets see on samsung device :

Photo size  - Portrate: width 1900(?????) height - 1000(????)
rotate to landscape : width 1900 height 1000

After some testing : if make photo in landscape mode on samsung device - than everything ok. Photo not rotated

If make photo in PORTRATE - photo rotated on 90 degree. (BUT size of photo as on landscape (HOW ITS POSSIBLE) ?

Anyone know how to fix this stupid bug ? Maybe any can tell me how to detect orientation for camera ? Im using IntentActivity for photo :

String _path = Environment.getExternalStorageDirectory()
                                    + File.separator + "camera_img.jpg";
                            File file = new File(_path);
                            Uri outputFileUri = Uri.fromFile(file);
                            Intent intent = new Intent(
                                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                            startActivityForResult(intent, CAMERA_REQUEST);

Any help  ?
I also add a checker , if its samsung device than rotate. But rotation good only if we create photo in portrate mode. In landscape everything fine. So i need somehow detected in which orientation photo was created. Any one know ?

Body:
UPD 29.08.2018 I found that this method doesn't work with Samsung device based on Android 8+. I don't have Samsung s8 (for example) and can't understand why this again does not work there.  If someone can test and check why this not work - let's try to fix this together.

I found how to fix: well it's really stupid and very hard for me.

First step get activity result

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

            String _path = Environment.getExternalStorageDirectory() + File.separator + "TakenFromCamera.jpg";
            String p1 = Environment.getExternalStorageDirectory().toString();
            String fName = "/TakenFromCamera.jpg";
            final int rotation = getImageOrientation(_path);
            File file = resaveBitmap(p1, fName, rotation);
            Bitmap mBitmap = BitmapFactory.decodeFile(_path);

Main steps it's getImageOrientation before changes in file.

getImageOrientation (by path)

resave file (if need send to server, if you need only for preview we can skip this step)

get correct bitmap from file

For preview it's enough to perform only steps 1 and 3, and using this function - just rotate bitmap.

private Bitmap checkRotationFromCamera(Bitmap bitmap, String pathToFile, int rotate) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return rotatedBitmap;
    }

getImageOrientation

public static int getImageOrientation(String imagePath) {
    int rotate = 0;
    try {
        ExifInterface exif = new ExifInterface(imagePath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return rotate;
}

and resaveBitmap if need

private File resaveBitmap(String path, String filename, int rotation) { //help for fix landscape photos
        String extStorageDirectory = path;
        OutputStream outStream = null;
        File file = new File(filename);
        if (file.exists()) {
            file.delete();
            file = new File(extStorageDirectory, filename);
        }
        try {
            // make a new bitmap from your file
            Bitmap bitmap = BitmapFactory.decodeFile(path + filename);
            bitmap = checkRotationFromCamera(bitmap, path + filename, rotation);
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) ((float) bitmap.getWidth() * 0.3f), (int) ((float) bitmap.getHeight() * 0.3f), false);
            bitmap = Utils.getCircleImage(bitmap);
            outStream = new FileOutputStream(path + filename);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


来源: stackexchange

问:
Java how to get abbreviation according from offset
I have Offset value Like UTC+3 I want  abbreviation of it in java</p>

答:
An adaptation of this might be of use.</p>

```<code>Set<String> allZones = ZoneId.getAvailableZoneIds();
        LocalDateTime dt = LocalDateTime.now();

        List<String> zoneList = new ArrayList<>(allZones);
        Collections.sort(zoneList);

        zoneList.stream().map((s) -> ZoneId.of(s)).forEach((zone) -> {
            ZonedDateTime zdt = dt.atZone(zone);
            ZoneOffset offset = zdt.getOffset();
            String out = String.format("%35s %10s%n", zone, offset);
            if (offset.getTotalSeconds() == 10800) {
                System.out.printf(out);
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
An adaptation of this might be of use.

Set<String> allZones = ZoneId.getAvailableZoneIds();
        LocalDateTime dt = LocalDateTime.now();

        List<String> zoneList = new ArrayList<>(allZones);
        Collections.sort(zoneList);

        zoneList.stream().map((s) -> ZoneId.of(s)).forEach((zone) -> {
            ZonedDateTime zdt = dt.atZone(zone);
            ZoneOffset offset = zdt.getOffset();
            String out = String.format("%35s %10s%n", zone, offset);
            if (offset.getTotalSeconds() == 10800) {
                System.out.printf(out);
            }
        });


问:
aurelia.js print a value in my DOM from a select
my values are been printing in a alert, but how can I print this value in my DOM? like in a h1 tag?

app.html:

```<code><template>

  <select value.bind="changedValue" change.delegate="DropdownChanged(changedValue)">
    <option model.bind="1">1</option>
    <option model.bind="2">2</option>
    <option model.bind="3">3</option>
    <option model.bind="4">4</option>
  </select>

</template>
</code>```

app.js

```<code>export class App {
  changedValue;

  DropdownChanged(changedVal) {
    alert(changedVal);
  }

}
</code>```

https://gist.run/?id=87f6897928feb504dad638d439caf92f

答:
Your changedValue in App holds the model you select as I see it.

You just need to give it a default (and maybe a better name)

```<code>export class App {
  value = 1;
</code>```

Then update it when a different value is selected instead of alerting.

```<code>DropdownChanged(changedVal) {
  this.value = changedVal;
}
</code>```

Then you can freely use it in your template

```<code><template>
    <h1>${value}</h1>
...
</code>```

As suggested, you might not need the change interceptor at all, in which case you can just bind to the select's model:

```<code><select value.bind="selectedValue">
</code>```

and

```<code><h1>Selected Value: ${selectedValue}</h1>
</code>```

(no need for any js code in this particular simplified example)

Body:
my values are been printing in a alert, but how can I print this value in my DOM? like in a h1 tag?

app.html:

<template>

  <select value.bind="changedValue" change.delegate="DropdownChanged(changedValue)">
    <option model.bind="1">1</option>
    <option model.bind="2">2</option>
    <option model.bind="3">3</option>
    <option model.bind="4">4</option>
  </select>

</template>

app.js

export class App {
  changedValue;

  DropdownChanged(changedVal) {
    alert(changedVal);
  }

}

https://gist.run/?id=87f6897928feb504dad638d439caf92f

Body:
Your changedValue in App holds the model you select as I see it.

You just need to give it a default (and maybe a better name)

export class App {
  value = 1;

Then update it when a different value is selected instead of alerting.

DropdownChanged(changedVal) {
  this.value = changedVal;
}

Then you can freely use it in your template

<template>
    <h1>${value}</h1>
...

As suggested, you might not need the change interceptor at all, in which case you can just bind to the select's model:

<select value.bind="selectedValue">

and

<h1>Selected Value: ${selectedValue}</h1>

(no need for any js code in this particular simplified example)


问:
Crash with Staggered Layout Manager of Recycler View
I load recycler normally and data is shown properly. But I have requirement to recreate my actvity on certain condition. When I recreate my activity, Recycler view is initialized again and is loaded with new set of data. But this time I get a crash. Below are the logs. Any help would be really appreciated.. !!!</p>

```<code>Fatal Exception: java.lang.ArrayIndexOutOfBoundsException: start < 0 || end > len. start=-1, end=11, len=11
       at java.util.Arrays.checkStartAndEnd(Arrays.java:1732)
       at java.util.Arrays.fill(Arrays.java:803)
       at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.invalidateAfter(StaggeredGridLayoutManager.java:2652)
       at android.support.v7.widget.StaggeredGridLayoutManager.handleUpdate(StaggeredGridLayoutManager.java:1496)
       at android.support.v7.widget.StaggeredGridLayoutManager.onItemsUpdated(StaggeredGridLayoutManager.java:1472)
       at android.support.v7.widget.RecyclerView$6.dispatchUpdate(RecyclerView.java:781)
       at android.support.v7.widget.RecyclerView$6.onDispatchFirstPass(RecyclerView.java:769)
       at android.support.v7.widget.AdapterHelper.dispatchFirstPassAndUpdateViewHolders(AdapterHelper.java:316)
       at android.support.v7.widget.AdapterHelper.dispatchAndUpdateViewHolders(AdapterHelper.java:302)
       at android.support.v7.widget.AdapterHelper.applyUpdate(AdapterHelper.java:222)
       at android.support.v7.widget.AdapterHelper.preProcess(AdapterHelper.java:106)
       at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1492)
       at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:151)
       at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:305)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
       at android.view.Choreographer.doCallbacks(Choreographer.java:670)
       at android.view.Choreographer.doFrame(Choreographer.java:603)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5417)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
When You are try to recreate your activity, RecyclerView still trying to display view items and ComputingLayout

RecyclerView is in a lockdown state and any attempt to update adapter
  contents will result in an exception

Solution

You should just postpone recreate activity using a Handler.

Check RecyclerView.isComputingLayout() should return false before you fire your change.

For more details Check my answer

Body:
I load recycler normally and data is shown properly. But I have requirement to recreate my actvity on certain condition. When I recreate my activity, Recycler view is initialized again and is loaded with new set of data. But this time I get a crash. Below are the logs. Any help would be really appreciated.. !!!

Fatal Exception: java.lang.ArrayIndexOutOfBoundsException: start < 0 || end > len. start=-1, end=11, len=11
       at java.util.Arrays.checkStartAndEnd(Arrays.java:1732)
       at java.util.Arrays.fill(Arrays.java:803)
       at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.invalidateAfter(StaggeredGridLayoutManager.java:2652)
       at android.support.v7.widget.StaggeredGridLayoutManager.handleUpdate(StaggeredGridLayoutManager.java:1496)
       at android.support.v7.widget.StaggeredGridLayoutManager.onItemsUpdated(StaggeredGridLayoutManager.java:1472)
       at android.support.v7.widget.RecyclerView$6.dispatchUpdate(RecyclerView.java:781)
       at android.support.v7.widget.RecyclerView$6.onDispatchFirstPass(RecyclerView.java:769)
       at android.support.v7.widget.AdapterHelper.dispatchFirstPassAndUpdateViewHolders(AdapterHelper.java:316)
       at android.support.v7.widget.AdapterHelper.dispatchAndUpdateViewHolders(AdapterHelper.java:302)
       at android.support.v7.widget.AdapterHelper.applyUpdate(AdapterHelper.java:222)
       at android.support.v7.widget.AdapterHelper.preProcess(AdapterHelper.java:106)
       at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1492)
       at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:151)
       at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:305)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
       at android.view.Choreographer.doCallbacks(Choreographer.java:670)
       at android.view.Choreographer.doFrame(Choreographer.java:603)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5417)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


问:
Is there any way to stop app for desire period?
In android is there any way to stop specific app. Let suppose i want to stop the whatsapp so is there any possibility? I have tried Force Stop method but it does not works. Whatsapp automatically turn on after sometime. </p>

答: Whatsapp like apps must have internal timers on the background service to restart it's services. So it invokes itself sometime later. Try to stop another basic app like calculator.</p>


问:
How to change icon in requestReview()?
I am using SKStoreReviewController.requestReview() to request feedback in my app, however the window shows an old AppIcon that I had in the app.

The icon that is displayed is nowhere to be found in my assets, everything is replaced with the new one.

How can I change it to display the latest one?

答:
Refer this one, this may help you, you need to change app icon in plist.

https://www.propelics.com/customizing-app-icons/

Title: How to change icon in requestReview()?


问:
Visual Studio 2010 - Add New Connection (SQL) as a different Windows Authenticated user
Here is my situation.

Domain Name: myDomain
user:   bob

I want to create a connection to a SQL server in myDomain from VS Studio 2010 as a different Windows user (not SQL Authentication)

My SQL admins will only build a user id myDomain\AppUser

Is there a way to specify a different user/pwd as a Windows authenticated ?

TIA.

Ralph

答:
You can connect with a distinct domain user from VS if you open the Visual Studio as that user using "run as".
Hope this helps.</p>

ContentLicense: CC BY-SA 2.5


问:
Json - stringify so that arrays are on one line
Is it possible to stringify a JSON object to look like this, with arrays in one line - not indented</p>

```<code>{
    "Repeat": {
        "Name": [["Top_level","All"],[[1,1]]],
        "Link": [["Top_level"],[[1,1]]]
    },
    "Delete": ["Confirm","Cancel"],
    "Move": ["Up","Down"],
    "Number": ["Ascending","Descending"]
}
</code>```

答:
Another approach which I took:

```<code>obj => JSON.stringify(obj, (k,v) => Array.isArray(v) ? JSON.stringify(v) : v, 2)
.replace(/"\[[^"\]]*]"/g, r => JSON.stringify(JSON.parse(r)).substr(1).slice(0,-1))
</code>```

*Array must not contain strings (notice the " in the not contains inside the regex), if you remove it it will catch key,values of:
"[": "[1,2,3,4]",

Update 2020-03 - I worked out a more stable solution

const obj = {
  "first_name": "John",
  "last_name": "Smith",
  "age": 21,
  "hobbies": [ "programming", "workout", null, undefined, 24, "\"has double quotes\"" ],
  "nested": {
    "arr": [ "one", "two", "three" ],
  },
  "nested_arr": [
    "first as string",
    {
      "latin": [ "alpha", "beta", "[gamma]" ]
    },
    null
  ]
};

const stringify = (obj, indent = 2) =>
  JSON.stringify(obj, (key, value) => {
    if (Array.isArray(value) && !value.some(x => x && typeof x === 'object')) {
      return `\uE000${JSON.stringify(value.map(v => typeof v === 'string' ? v.replace(/"/g, '\uE001') : v))}\uE000`;
    }
    return value;
  }, indent).replace(/"\uE000([^\uE000]+)\uE000"/g, match => match.substr(2, match.length - 4).replace(/\\"/g, '"').replace(/\uE001/g, '\\\"'));

console.log(stringify(obj));```

Body:
Is it possible to stringify a JSON object to look like this, with arrays in one line - not indented

{
    "Repeat": {
        "Name": [["Top_level","All"],[[1,1]]],
        "Link": [["Top_level"],[[1,1]]]
    },
    "Delete": ["Confirm","Cancel"],
    "Move": ["Up","Down"],
    "Number": ["Ascending","Descending"]
}

Body:
Another approach which I took:

obj => JSON.stringify(obj, (k,v) => Array.isArray(v) ? JSON.stringify(v) : v, 2)
.replace(/"\[[^"\]]*]"/g, r => JSON.stringify(JSON.parse(r)).substr(1).slice(0,-1))

*Array must not contain strings (notice the " in the not contains inside the regex), if you remove it it will catch key,values of:
"[": "[1,2,3,4]",

Update 2020-03 - I worked out a more stable solution

const obj = {
  "first_name": "John",
  "last_name": "Smith",
  "age": 21,
  "hobbies": [ "programming", "workout", null, undefined, 24, "\"has double quotes\"" ],
  "nested": {
    "arr": [ "one", "two", "three" ],
  },
  "nested_arr": [
    "first as string",
    {
      "latin": [ "alpha", "beta", "[gamma]" ]
    },
    null
  ]
};

const stringify = (obj, indent = 2) =>
  JSON.stringify(obj, (key, value) => {
    if (Array.isArray(value) && !value.some(x => x && typeof x === 'object')) {
      return `\uE000${JSON.stringify(value.map(v => typeof v === 'string' ? v.replace(/"/g, '\uE001') : v))}\uE000`;
    }
    return value;
  }, indent).replace(/"\uE000([^\uE000]+)\uE000"/g, match => match.substr(2, match.length - 4).replace(/\\"/g, '"').replace(/\uE001/g, '\\\"'));

console.log(stringify(obj));

ContentLicense: CC BY-SA 4.0


问:
Puppet : file resource only if file exists
What I want to do is quite simple :

1.

Copy /source/file to /target/file. I achieve this using the following:

```<code>file { 'my_file_copy':
  ensure   => file,
  source   => 'file:/source/file',
  path     => "/target/file",
}
</code>```

2.

However, if file /source/file does not exist, I do NOT want it to perform this task.

I am really struggling with this logic. I attempted the solution below but it throws exceptions during puppet run.

puppet: if one file exists then copy another file over

Is there a better way of achieving this task ?
Ideally, I would like to only use "file" and avoid using "exec". But at this point I would settle for a solution !

答:
You could use this logic:</p>

```<code>$file = "/source/file"

  exec { "chk_${file}_exist":
    command => "true",
    path    =>  ["/usr/bin","/usr/sbin", "/bin"],
    onlyif  => "test -f ${file}"
  }

  file {"/target/file":
    ensure => file,
    source => 'file:/source/file',
    owner  => 'root',
    group  => 'root',
    mode   => '0750',
    require => Exec["chk_${file}_exist"],
  }
</code>```

Body:
What I want to do is quite simple :

1.

Copy /source/file to /target/file. I achieve this using the following:

file { 'my_file_copy':
  ensure   => file,
  source   => 'file:/source/file',
  path     => "/target/file",
}

2.

However, if file /source/file does not exist, I do NOT want it to perform this task.

I am really struggling with this logic. I attempted the solution below but it throws exceptions during puppet run.

puppet: if one file exists then copy another file over

Is there a better way of achieving this task ?
Ideally, I would like to only use "file" and avoid using "exec". But at this point I would settle for a solution !

Body:
You could use this logic:

$file = "/source/file"

  exec { "chk_${file}_exist":
    command => "true",
    path    =>  ["/usr/bin","/usr/sbin", "/bin"],
    onlyif  => "test -f ${file}"
  }

  file {"/target/file":
    ensure => file,
    source => 'file:/source/file',
    owner  => 'root',
    group  => 'root',
    mode   => '0750',
    require => Exec["chk_${file}_exist"],
  }


问:
How to edit icon of SearchBar Xamarin Forms on Android?
I need your help !

I work on a mobile development project, cross-platform. I use Visual Studio with Xamarin Forms.
I want to make a page with a SearchBar (Xamarin.Forms class), but, my problem is the personalisation of the SearchBar icon, especially on the Platform Android. My search led me to nothing.
I would be very grateful if you know of a way to edit icon. (I have a model to follow, so It’s well the icon that I want to change and not the color).

Thank you in advance !

enter image description here

答:
```<code>         protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                var plateId = Resources.GetIdentifier("android:id/search_plate", null, null);
                var plate = Control.FindViewById(plateId);
                plate.SetBackgroundColor(Android.Graphics.Color.Transparent);

                SearchView searchView = (base.Control as SearchView);
                var searchIconId = searchView.Resources.GetIdentifier("android:id/search_map_icon", null, null);
                var searchIcon = searchView.FindViewById(searchIconId);
                searchView.SetIconifiedByDefault(false);
                searchIcon.RemoveFromParent();

                int textViewId = Resources.GetIdentifier("android:id/search_src_text", null, null);
                EditText textView = (Control.FindViewById(textViewId) as EditText);
                textView.TextAlignment = Android.Views.TextAlignment.ViewStart;
            }
        }
</code>```

This worked for me

Body:
         protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                var plateId = Resources.GetIdentifier("android:id/search_plate", null, null);
                var plate = Control.FindViewById(plateId);
                plate.SetBackgroundColor(Android.Graphics.Color.Transparent);

                SearchView searchView = (base.Control as SearchView);
                var searchIconId = searchView.Resources.GetIdentifier("android:id/search_map_icon", null, null);
                var searchIcon = searchView.FindViewById(searchIconId);
                searchView.SetIconifiedByDefault(false);
                searchIcon.RemoveFromParent();

                int textViewId = Resources.GetIdentifier("android:id/search_src_text", null, null);
                EditText textView = (Control.FindViewById(textViewId) as EditText);
                textView.TextAlignment = Android.Views.TextAlignment.ViewStart;
            }
        }

This worked for me


问:
Force shiny to render plot in loop
I have a shiny app that runs a simulation. The goal is to show the user the calculation steps in between as a plot.

How do I force shiny to update the plot?

An MWE would look like this

```<code>library(shiny)

server <- function(input, output, session) {
  # base plot as a placeholder
  output$myplot <- renderPlot(plot(1:1, main = "Placeholder"))

  # wait until the button is triggered
  observeEvent(input$run, {
    print("Do some calculations in 3 steps")
    for (i in seq_len(3)) {
      print("Do some calculations")
      # ...
      x <- seq_len(i * 100)
      y <- (x + 1)^2 - 1 # this will do for now

      print("Plot the data ")

      # ISSUE HERE!
      # this should render the current step of the simulation, instead it
      # renders only after the whole code is run (i.e., after step 3)
      output$myplot <- renderPlot(plot(x, y, main = sprintf("Round %i", i), type = "l"))

      print("Wait for 1 second for the user to appreciate the plot...")
      Sys.sleep(1)
    }
  })
}

ui <- fluidPage(
  actionButton("run", "START"),
  plotOutput("myplot")
)

shinyApp(ui = ui, server = server)
</code>```

The issue is, that shiny runs the code and produces one plot at the end of the simulation, however, I want to get a plot at each simulation step (displayed for at least one second).

Any help/hint is greatly appreciated.

Appendix

I have looked at this post, but replacing the text with a plot/renderPlot doesn't yield the correct results.

答:
You could nest an observer into an observeEvent to make it work. Based on Jeff Allen's code from the SO topic you linked.

Crucial part:

```<code>observeEvent(input$run, {
    rv$i <- 0
    observe({
      isolate({
        rv$i <- rv$i + 1
      })

      if (isolate(rv$i) < maxIter){
        invalidateLater(2000, session)
      }
    })
  })
</code>```

Full code:

```<code>library(shiny)

server <- function(input, output, session) {
  rv <- reactiveValues(i = 0)
  maxIter <- 3

  output$myplot <- renderPlot( {
    if(rv$i > 0) {
      x <- seq_len(rv$i * 100)
      y <- (x + 1)^2 - 1 # this will do for now
      plot(x, y, main = sprintf("Round %i", rv$i), type = "l")
    } else {
      plot(1:1, main = "Placeholder")
    }
  })

  observeEvent(input$run, {
    rv$i <- 0
    observe({
      isolate({
        rv$i <- rv$i + 1
      })

      if (isolate(rv$i) < maxIter){
        invalidateLater(2000, session)
      }
    })
  })

}

ui <- fluidPage(
  actionButton("run", "START"),
  plotOutput("myplot")
)

shinyApp(ui = ui, server = server)
</code>```

Title: Force shiny to render plot in loop

Body:
I have a shiny app that runs a simulation. The goal is to show the user the calculation steps in between as a plot.

How do I force shiny to update the plot?

An MWE would look like this

library(shiny)

server <- function(input, output, session) {
  # base plot as a placeholder
  output$myplot <- renderPlot(plot(1:1, main = "Placeholder"))

  # wait until the button is triggered
  observeEvent(input$run, {
    print("Do some calculations in 3 steps")
    for (i in seq_len(3)) {
      print("Do some calculations")
      # ...
      x <- seq_len(i * 100)
      y <- (x + 1)^2 - 1 # this will do for now

      print("Plot the data ")

      # ISSUE HERE!
      # this should render the current step of the simulation, instead it
      # renders only after the whole code is run (i.e., after step 3)
      output$myplot <- renderPlot(plot(x, y, main = sprintf("Round %i", i), type = "l"))

      print("Wait for 1 second for the user to appreciate the plot...")
      Sys.sleep(1)
    }
  })
}

ui <- fluidPage(
  actionButton("run", "START"),
  plotOutput("myplot")
)

shinyApp(ui = ui, server = server)

The issue is, that shiny runs the code and produces one plot at the end of the simulation, however, I want to get a plot at each simulation step (displayed for at least one second).

Any help/hint is greatly appreciated.

Appendix

I have looked at this post, but replacing the text with a plot/renderPlot doesn't yield the correct results.

Body:
You could nest an observer into an observeEvent to make it work. Based on Jeff Allen's code from the SO topic you linked.

Crucial part:

observeEvent(input$run, {
    rv$i <- 0
    observe({
      isolate({
        rv$i <- rv$i + 1
      })

      if (isolate(rv$i) < maxIter){
        invalidateLater(2000, session)
      }
    })
  })

Full code:

library(shiny)

server <- function(input, output, session) {
  rv <- reactiveValues(i = 0)
  maxIter <- 3

  output$myplot <- renderPlot( {
    if(rv$i > 0) {
      x <- seq_len(rv$i * 100)
      y <- (x + 1)^2 - 1 # this will do for now
      plot(x, y, main = sprintf("Round %i", rv$i), type = "l")
    } else {
      plot(1:1, main = "Placeholder")
    }
  })

  observeEvent(input$run, {
    rv$i <- 0
    observe({
      isolate({
        rv$i <- rv$i + 1
      })

      if (isolate(rv$i) < maxIter){
        invalidateLater(2000, session)
      }
    })
  })

}

ui <- fluidPage(
  actionButton("run", "START"),
  plotOutput("myplot")
)

shinyApp(ui = ui, server = server)


问:
How can I get a vertical scrollbar in my ListBox?
In the example below I have a ListBox with dozens of font names in it.

I would have thought it would automatically have a vertical scrollbar on it so that you can select ANY font, not just the first ones in the list, but it doesn't.

So I added a "ScrollViewer" and that puts a "scrollbar area" on the right but there is no scrollbar in the scrollbar area so that you can scroll (!).

Why isn't a scrollbar automatic and how do I force it to have a scrollbar?

```<code><StackPanel Name="stack1">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ScrollViewer>
            <ListBox Grid.Row="0" Name="lstFonts" Margin="3"  ItemsSource="{x:Static Fonts.SystemFontFamilies}"/>
        </ScrollViewer>
    </Grid>
</StackPanel>
</code>```

答: I added a "Height" to my ListBox and it added the scrollbar nicely.</p>

OwnerDisplayName: Edward Tanguay

Body:
In the example below I have a ListBox with dozens of font names in it.

I would have thought it would automatically have a vertical scrollbar on it so that you can select ANY font, not just the first ones in the list, but it doesn't.

So I added a "ScrollViewer" and that puts a "scrollbar area" on the right but there is no scrollbar in the scrollbar area so that you can scroll (!).

Why isn't a scrollbar automatic and how do I force it to have a scrollbar?

<StackPanel Name="stack1">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ScrollViewer>
            <ListBox Grid.Row="0" Name="lstFonts" Margin="3"  ItemsSource="{x:Static Fonts.SystemFontFamilies}"/>
        </ScrollViewer>
    </Grid>
</StackPanel>


问:
WP7 ListPicker scrolling issue
I have created the following:

```<code>    <!--Pivot Control-->
   < controls:Pivot Title="name"

        <!--Pivot item one-->
       < controls:PivotItem Header="h1">
            <Grid>
                <Image Height="140" HorizontalAlignment="Left" Margin="24,21,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
               <TextBlock Height="146" HorizontalAlignment="Left" Margin="246,21,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="194" />
                <StackPanel Margin="10,200,0,0">
                    <toolkit:ListPicker Header="header1" HorizontalAlignment="Left" Name="ListPicker1" VerticalAlignment="Top" Width="429" />
                    <toolkit:ListPicker Header="header2" HorizontalAlignment="Left" Name="ListPicker2" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    <toolkit:ListPicker Header="header3" HorizontalAlignment="Left" Name="ListPicker3" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    </StackPanel>
            <Grid>
        <controls:PivotItem>

        <!--Pivot item two-->
        <controls:PivotItem Header="h2">
            <Grid/>
        <controls:PivotItem>
        <!--Pivot item three-->
        <controls:PivotItem Header="h3">
           < Grid/>
        </controls:PivotItem>
    </controls:Pivot>
</Grid>
</code>```

the third lisppicker ListPicker3 has 5 items I can only see the first two items and the remaining 3 items are invisble because they are below in the page.  The prob is that I cannot scroll down to see them.

Could someone tell me if there is a way to scroll down the page to see the value of the expanded ListPicker3 or suggest me a method to resolve this.

Thanks

答: Wrap the PivotItem < Grid /> XAML element with a < ScrollViewer /> XAML element. </p>

Title: WP7 ListPicker scrolling issue

Body:
I have created the following:

   < controls:Pivot Title="name"

       < controls:PivotItem Header="h1">
            <Grid>
                <Image Height="140" HorizontalAlignment="Left" Margin="24,21,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
               <TextBlock Height="146" HorizontalAlignment="Left" Margin="246,21,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="194" />
                <StackPanel Margin="10,200,0,0">
                    <toolkit:ListPicker Header="header1" HorizontalAlignment="Left" Name="ListPicker1" VerticalAlignment="Top" Width="429" />
                    <toolkit:ListPicker Header="header2" HorizontalAlignment="Left" Name="ListPicker2" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    <toolkit:ListPicker Header="header3" HorizontalAlignment="Left" Name="ListPicker3" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    </StackPanel>
            <Grid>
        <controls:PivotItem>

        <controls:PivotItem Header="h2">
            <Grid/>
        <controls:PivotItem>

        <controls:PivotItem Header="h3">
           < Grid/>
        </controls:PivotItem>
    </controls:Pivot>
</Grid>

the third lisppicker ListPicker3 has 5 items I can only see the first two items and the remaining 3 items are invisble because they are below in the page.  The prob is that I cannot scroll down to see them.

Could someone tell me if there is a way to scroll down the page to see the value of the expanded ListPicker3 or suggest me a method to resolve this.

Thanks


问:
Gulp copy all files inside a directory , without directory
This is my gulpfile

```<code>const gulp = require('gulp');
const runSequence = require('run-sequence');
const gulpCopy = require('gulp-copy');

//move client side library from client-lib to public folder
gulp.task('move-file',function(){
    console.log("Move-files");
    return gulp
        .src(['./client-lib/*.js'])
        .pipe(gulpCopy('./public'))

});

gulp.task('default',function(){
    runSequence('move-file');
});
</code>```

I need to copy all js files inside client-lib folder and copy to public folder . But this code copy with folder and my public folders look like

public->client-lib->myjsfiles

But I need

public->myjsfiles

答:
You dont need to use any NPM for this ,

```<code>remove `const gulpCopy = require('gulp-copy');` ,
</code>```

and gulpCopy this command from task as well .

and simply try

```<code>gulp.task('move-file',function(){
gulp .src('client-lib/*.js') .pipe(rename({dirname: ''}))
.pipe(gulp.dest('./public'))
});
</code>```

Body:
This is my gulpfile

const gulp = require('gulp');
const runSequence = require('run-sequence');
const gulpCopy = require('gulp-copy');

//move client side library from client-lib to public folder
gulp.task('move-file',function(){
    console.log("Move-files");
    return gulp
        .src(['./client-lib/*.js'])
        .pipe(gulpCopy('./public'))

});

gulp.task('default',function(){
    runSequence('move-file');
});

I need to copy all js files inside client-lib folder and copy to public folder . But this code copy with folder and my public folders look like

public->client-lib->myjsfiles

But I need

public->myjsfiles

Body:
You dont need to use any NPM for this ,

remove `const gulpCopy = require('gulp-copy');` ,

and gulpCopy this command from task as well .

and simply try

gulp.task('move-file',function(){
gulp .src('client-lib/*.js') .pipe(rename({dirname: ''}))
.pipe(gulp.dest('./public'))
});


问:
spring restTemplate dynamic mapping
I am using spring restTemplate to map a response to a POJO.
The response of the rest api is like this:

```<code>"attributes": {
    "name": {
        "type": "String",
        "value": ["John Doe"]
    },
    "permanentResidence": {
        "type": "Boolean",
        "value": [true]
    },
    "assignments": {
        "type": "Grid",
        "value": [{
            "id": "AIS002",
            "startDate": "12012016",
            "endDate": "23112016"
        },{
            "id": "AIS097",
            "startDate": "12042017",
            "endDate": "23092017"
        }]
    }
}
</code>```

in the parent class, I have:

```<code>public class Users {
    private Map<String, Attribute> attributes;
}
</code>```

If all the values of were String type, then I could have done like:

```<code>public class Attribute {
    private String type;
    private String[] value;
}
</code>```

But the values are of different types. So I thought of doing the following:

```<code>public class Attribute {
    private String type;
    private Object[] value;
}
</code>```

The above should work, but at every step I have to find out what is the type of Object.

So, my question is can I have something like this:

```<code>public class Attribute {

    @JsonProperty("type")
    private String type;

    @JsonProperty("value")
    private String[] stringValues;

    @JsonProperty("value")
    private Boolean[] booleanValues;

    @JsonProperty("value")
    private Assignments[] assignmentValues; // for Grid type
}
</code>```

But it is not working and throwing errors: Conflicting setter definitions for property "value"

What is the recommended way of handling this scenario?

答:
I would recommend Jackson facilities for handling polymorphism here:

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = BooleanAttribute.class, name = "Boolean"),
        @JsonSubTypes.Type(value = StringAttribute.class, name = "String")
})
class Attribute {
    private String type;
}

class BooleanAttribute extends Attribute {
    private Boolean[] value;
}

class StringAttribute extends Attribute {
    private String[] value;
}
</code>```

JsonTypeInfo tells Jackson that this is a base class and the type will be determined by a JSON field named "type"

JsonSubTypes maps subtypes of Attribute to values of "type" in JSON.

If you add an appropriate subtype for Assignments and getters/setters Jackson will be able to parse your JSON.

Title: spring restTemplate dynamic mapping

Body:
I am using spring restTemplate to map a response to a POJO.
The response of the rest api is like this:

"attributes": {
    "name": {
        "type": "String",
        "value": ["John Doe"]
    },
    "permanentResidence": {
        "type": "Boolean",
        "value": [true]
    },
    "assignments": {
        "type": "Grid",
        "value": [{
            "id": "AIS002",
            "startDate": "12012016",
            "endDate": "23112016"
        },{
            "id": "AIS097",
            "startDate": "12042017",
            "endDate": "23092017"
        }]
    }
}

in the parent class, I have:

public class Users {
    private Map<String, Attribute> attributes;
}

If all the values of were String type, then I could have done like:

public class Attribute {
    private String type;
    private String[] value;
}

But the values are of different types. So I thought of doing the following:

public class Attribute {
    private String type;
    private Object[] value;
}

The above should work, but at every step I have to find out what is the type of Object.

So, my question is can I have something like this:

public class Attribute {

    @JsonProperty("type")
    private String type;

    @JsonProperty("value")
    private String[] stringValues;

    @JsonProperty("value")
    private Boolean[] booleanValues;

    @JsonProperty("value")
    private Assignments[] assignmentValues; // for Grid type
}

But it is not working and throwing errors: Conflicting setter definitions for property "value"

What is the recommended way of handling this scenario?

Body:
I would recommend Jackson facilities for handling polymorphism here:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = BooleanAttribute.class, name = "Boolean"),
        @JsonSubTypes.Type(value = StringAttribute.class, name = "String")
})
class Attribute {
    private String type;
}

class BooleanAttribute extends Attribute {
    private Boolean[] value;
}

class StringAttribute extends Attribute {
    private String[] value;
}

JsonTypeInfo tells Jackson that this is a base class and the type will be determined by a JSON field named "type"

JsonSubTypes maps subtypes of Attribute to values of "type" in JSON.

If you add an appropriate subtype for Assignments and getters/setters Jackson will be able to parse your JSON.


答:
If you want to do programatically then you have to get permission for Administrative. And then your app will be able to kill other Apps. Like Greenify.

If you want to kill applications -> Use Greenify -> Auto Hibernate options. It will automatically hibernate applications after certain period of time.

Third way is root your phone and edit the permission of application. -> Remove permission of Boot to Turn on flag.

Title: Is there any way to stop app for desire period?

Body: In android is there any way to stop specific app. Let suppose i want to stop the whatsapp so is there any possibility? I have tried Force Stop method but it does not works. Whatsapp automatically turn on after sometime.


问:
SQL neatly self join a table n times
I'm building a back-end for a project to construct a (purely functional) graph database system.

One operation I'm trying to implement is self joining a precomputed view to itself exactly n times (i.e. finding pairs of results that are exactly n instances of a particular relation away from each other in the graph)

A slightly ugly solution I've come up with is generating a big tree of joins in a style similar to exponentiation by squaring

Is there a neater/better way to do this? Perhaps using recursive queries?

Each possible pre-generated view has a left_id and right_id field, which represent indices into entity tables.

A simplified example is the following:

Given the following table representing part of the relation n -> succ(n) (in reality the relation may be much more complicated)

```<code>left_id | right_id
__________________
   1    |    2
   2    |    3
   3    |    4
   4    |    5
   5    |    6
   7    |    8
</code>```

The ideal result of querying with n = 3 would be

```<code>left_id | right_id
__________________
   1    |    4
   2    |    5
   3    |    6
   4    |    7
   5    |    8
</code>```

(An explanation of why I'm using SQL is that one part of this project is to demonstrate that SQL is a poor choice for such a system, followed by a more bespoke backend to solve the issues with using an underlying relational as opposed to a graph model)

答:
Many databases support recursive CTEs, which directly support such graph walking.

Even in databases that do not, this is not particularly difficult, using dynamic SQL and a WHERE clause:

For n = 1:

```<code>select t1.left_id, t2.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id;
</code>```

For n = 2:

```<code>select t1.left_id, t3.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id join
     t t3
     on t3.left_id = t2.right_id;
</code>```

For n = 3:

```<code>select t1.left_id, t4.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id join
     t t3
     on t3.left_id = t2.right_id join
     t t4
     on t4.left_id = t3.right_id;
</code>```

Each additional value of "n" adds another join condition.  These queries can readily take advantage of an index on the table, so performance should be reasonable.

Whether this is better or worse than graph databases is somewhat moot.  Each type of database has different strengths.  Many relational databases do support recursive CTEs (and hence graph walking).  However, the performance is probably going to be better on a software system specifically designed for this purpose.

Title: SQL neatly self join a table n times

Body:
I'm building a back-end for a project to construct a (purely functional) graph database system.

One operation I'm trying to implement is self joining a precomputed view to itself exactly n times (i.e. finding pairs of results that are exactly n instances of a particular relation away from each other in the graph)

A slightly ugly solution I've come up with is generating a big tree of joins in a style similar to exponentiation by squaring

Is there a neater/better way to do this? Perhaps using recursive queries?

Each possible pre-generated view has a left_id and right_id field, which represent indices into entity tables.

A simplified example is the following:

Given the following table representing part of the relation n -> succ(n) (in reality the relation may be much more complicated)

left_id | right_id
__________________
   1    |    2
   2    |    3
   3    |    4
   4    |    5
   5    |    6
   7    |    8

The ideal result of querying with n = 3 would be

left_id | right_id
__________________
   1    |    4
   2    |    5
   3    |    6
   4    |    7
   5    |    8

(An explanation of why I'm using SQL is that one part of this project is to demonstrate that SQL is a poor choice for such a system, followed by a more bespoke backend to solve the issues with using an underlying relational as opposed to a graph model)

Body:
Many databases support recursive CTEs, which directly support such graph walking.

Even in databases that do not, this is not particularly difficult, using dynamic SQL and a WHERE clause:

For n = 1:

select t1.left_id, t2.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id;

For n = 2:

select t1.left_id, t3.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id join
     t t3
     on t3.left_id = t2.right_id;

For n = 3:

select t1.left_id, t4.right_id
from t t1 join
     t t2
     on t2.left_id = t1.right_id join
     t t3
     on t3.left_id = t2.right_id join
     t t4
     on t4.left_id = t3.right_id;

Each additional value of "n" adds another join condition.  These queries can readily take advantage of an index on the table, so performance should be reasonable.

Whether this is better or worse than graph databases is somewhat moot.  Each type of database has different strengths.  Many relational databases do support recursive CTEs (and hence graph walking).  However, the performance is probably going to be better on a software system specifically designed for this purpose.


问:
How to disable Cassandra Replication with keyspace
I have a Cassandra DB and a keyspace with some Tables which i do not want to repplicate.
I know, a key feature of cassandra is the replication, but i do not want to replicate.

I have 3 DataCenters:  dc1, dc2, dc3

currently i'am creating the Keyspace like this on each DC:

```<code>CREATE KEYSPACE IF NOT EXISTS myKeyspace
  WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1'};
</code>```

As i understood this means dc1 will be replicated to one of the three other DCs?
How should this look like if i do not want to replicate?

答:
```<code>CREATE KEYSPACE IF NOT EXISTS myKeyspace WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1'};
</code>```

This means that you have replication factor 1 on dc1. So what have you have currently is what you want. Replication factor of 1 will mean only one node will hold the data and it won't be replicated anywhere else. The number is not for how many copies but for the number of nodes that hold the data.

If you wanted it replicated to other dcs it would be something like this:

```<code>CREATE KEYSPACE IF NOT EXISTS myKeyspace WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1', 'dc2': '1', 'dc3': '3'};
</code>```

Meaning dc1 will have data on 1 node, dc2 will have data on 1 node and dc1 will have the data on 3 nodes

Body:
I have a Cassandra DB and a keyspace with some Tables which i do not want to repplicate.
I know, a key feature of cassandra is the replication, but i do not want to replicate.

I have 3 DataCenters:  dc1, dc2, dc3

currently i'am creating the Keyspace like this on each DC:

CREATE KEYSPACE IF NOT EXISTS myKeyspace
  WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1'};

As i understood this means dc1 will be replicated to one of the three other DCs?
How should this look like if i do not want to replicate?

Body:
CREATE KEYSPACE IF NOT EXISTS myKeyspace WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1'};

This means that you have replication factor 1 on dc1. So what have you have currently is what you want. Replication factor of 1 will mean only one node will hold the data and it won't be replicated anywhere else. The number is not for how many copies but for the number of nodes that hold the data.

If you wanted it replicated to other dcs it would be something like this:

CREATE KEYSPACE IF NOT EXISTS myKeyspace WITH replication={'class':'NetworkTopologyStrategy', 'dc1': '1', 'dc2': '1', 'dc3': '3'};

Meaning dc1 will have data on 1 node, dc2 will have data on 1 node and dc1 will have the data on 3 nodes


问:
SSL Cert on internal private network
I have a Server which is on both the internet and a private network.

I am trying to set up TLS on an internal private network as requested by my manager.

The service is available to both internet and private internal network clients.

External clients use the internet with their Client certificates - this works great.

Internal clients get an Cert error as they are accessing the service using the IP address of the server on the internal network.

I've tried 'trick' the client machines by translating the domain name in the Server cert to the IP address of the server - but we still get the server cert Error.

As far as I am aware I cant get a cert issued for the server as it's not a verifiable domain name ( in fact its an IP address ). We do not have any DNS on the private network.

Any idea what else I could try?

答:
Usually, you set up split DNS to resolve the server's name to the private IP instead of the public IP - your local DNS server just resolves the name by a local entry instead of passing the request to an upstream server. That way, both internal and external users resolve the name to the address they need and both groups are happy.

If you do need to use IP addresses you have to include both of them as alternate names in the certificate.

Title: SSL Cert on internal private network


问:
Git: List git branches, sort by (and show) date
How can I list git branches showing and sorting by their last commits' dates?

I've found this:

```<code>for k in `git branch | sed s/^..//`; do
    echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k"`\\t"$k";
done | sort -r
</code>```

I'd expect plain git to have this feature. Does it?

I also found git show-branch --date-order but the output is something different.

答:
I've enjoyed the @Will Sheppard solution to put some colors. </p>

```<code>git for-each-ref --sort=committerdate refs/heads/ --format='%(color: red)%(committerdate:short) %(color: cyan)%(refname:short)'
</code>```

Body:
How can I list git branches showing and sorting by their last commits' dates?

I've found this:

for k in `git branch | sed s/^..//`; do
    echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k"`\\t"$k";
done | sort -r

I'd expect plain git to have this feature. Does it?

I also found git show-branch --date-order but the output is something different.

Body:
I've enjoyed the @Will Sheppard solution to put some colors.

git for-each-ref --sort=committerdate refs/heads/ --format='%(color: red)%(committerdate:short) %(color: cyan)%(refname:short)'


问:
Existing li gets overridden in todolist instead of adding a new li
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>spooky</h1>

<input type="text" class="input">
<ul>
  <li>1</li>
  <li>2</li>
</ul></code>```

答:
It happens because you have stored ul element in a variable, so you're appending new child at the same position (ul parent is not updated with information about new elements in it).

Try with:

```<code>let addNewFunc = function () {
  let name = document.querySelector("ul").appendChild(addNew);
};
</code>```

Body:
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};

spooky

<input type="text" class="input">

1

2

Body:
It happens because you have stored ul element in a variable, so you're appending new child at the same position (ul parent is not updated with information about new elements in it).

Try with:

let addNewFunc = function () {
  let name = document.querySelector("ul").appendChild(addNew);
};


问:
How to set validation on Phone number in PHP
This is my code:

I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend

what can I do? for set validation for phone number field.

```<code><!DOCTYPE HTML>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
$nameErr = $phoneErr = "";
$name =  $phone = "";

$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field

     $name = htmlspecialchars($_REQUEST['name']);
     $phone = htmlspecialchars($_REQUEST['phone']);

    if (empty($name)) {
        $nameErr = "* Name is required";
      $error = 1;
        // echo "Name is empty";
    }

    if (empty($phone)) {
        // echo "phone is empty";
        $phoneErr = "* Phone is required";
        $error = 1;
    }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <h1>Login Form</h1>
  Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
   <span class="error"> <?php echo $nameErr?></span>
  <br></br>

  Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
    <span class="error"> <?php echo $phoneErr?></span>
   <br><br>

  <input type="submit">

  <br><br>

</form>

</body>
</html>
</code>```

I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number

答:
Why do you need to validate phone number using php?
You can do it using JS as shown below.

```<code>if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
      alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
    return;
}
</code>```

Body:
This is my code:

I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend

what can I do? for set validation for phone number field.

<!DOCTYPE HTML>

<?php
$nameErr = $phoneErr = "";
$name =  $phone = "";

$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field

     $name = htmlspecialchars($_REQUEST['name']);
     $phone = htmlspecialchars($_REQUEST['phone']);

    if (empty($name)) {
        $nameErr = "* Name is required";
      $error = 1;
        // echo "Name is empty";
    }

    if (empty($phone)) {
        // echo "phone is empty";
        $phoneErr = "* Phone is required";
        $error = 1;
    }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

Login Form

  Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
    <?php echo $nameErr?>

  Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
     <?php echo $phoneErr?>

  <input type="submit">

</form>

I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number

Body:
Why do you need to validate phone number using php?
You can do it using JS as shown below.

if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
      alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
    return;
}


问:
how to map a file in RAM by offset and size in windows
I have a C++ programfind to delete files on hard drive. So the program starts reading from beginning of a partition and whenever it sees a valid signature it'll read that and find the file size according to the what kind of file is.

Then it saves the beginning size and offset of the file into the database.
Now what I want is giving the files to the some analyzers when this process has done!

What I am doing now is recovering the files into the hard then giving their addresses to the analyzer. But it's too long.

I want to load these files into RAM by a virtual file system that it gets file address offset and file size, then give an virtual address that the analyzers could read that files by fopen() and it's get faster but I don't want to write files on partition.

In fact the files has existed into the partition but not in the file system table.

Is there any solution for this way?

答:
There's a simple trick which you have to know. Call CreateFile as you do know, but pass FILE_ATTRIBUTE_TEMPORARY. This is a strong hint to Windows to keep the file in RAM, as you intend to delete it right after use.

You can also pass FILE_FLAG_DELETE_ON_CLOSE to make things easier for yourself.


问:
How to design a query where I retrieve last data from resource that I want to apply filter to in RESTful way?
How should a query look like when I want to retrieve last measurements from installations that aren't removed?

Something like that?

```<code>/my-web-service/installations/measurements/last?removed=false
</code>```

The thing is, I don't want to retrieve last measurements that weren't removed from installations. I want to retrieve last measurements from installations that weren't removed.

答:
I see a couple possibilities here:

If you need to read the data from the endpoint transactionally, the way you designed it is the way to go. What I'd change is the name of the param from removed to installationRemoved since it's more descriptive and shorten the endpoint to /my-web-service/measurements/ - since with installations it's unclear in which scope does the client operate. Also, don't you need since param to filter the last measurements?

It there's a chance to split the two endpoints I'd add:

/my-web-service/installations/?removed=false

/my-web-service/measurements/?since=timestamp&installations=<array>

It does not make it better (when it comes to better or worse) but easier and more predictive for the users.

In general try to add more general endpoints with filtering options rather then highly dedicated - doing one particular thing. This way leads to hard to use, loose API. Also, on filtering.

And final notice, your API is good if your clients use it not because they have to but when they like it ;)

Body:
How should a query look like when I want to retrieve last measurements from installations that aren't removed?

Something like that?

/my-web-service/installations/measurements/last?removed=false

The thing is, I don't want to retrieve last measurements that weren't removed from installations. I want to retrieve last measurements from installations that weren't removed.


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答: It's possible to do what you wish, but I would say you have to retrieve the external HTML file using XMLHttpRequest first.</p>


问:
tFPDF add multiple DejaVu fonts
How would one use multiple styles of DejaVu fonts when using tFPDF?

I would like to use the DejaVuSans font for some text and DejaVuSansMono for other.

The tutorial  shows you can include font like this:$pdf -> AddFont('DejaVu','','DejaVuSans.ttf',true); and then use it like $pdf -> SetFont("DejaVu","",10);

But if I add additional font $pdf->AddFont('DejaVu','','DejaVuSansMono.ttf',true); nothing changes.

So how do I specify where I want to use the Mono font and where the default one?

My code currently looks like this (doesn't work):

```<code>$pdf->AddFont('DejaVu','','DejaVuSans.ttf',true);
$pdf->SetFont("DejaVu","",10);
$pdf->Cell(10,10 , "sometext");

$pdf->AddFont('DejaVu','','DejaVuSansMono.ttf',true);
$pdf->SetFont("DejaVu","",10);
$pdf->Cell(10,10 , "sometext");
</code>```

答:
For anyone still interested in an answer

You only need to AddFont once:

```<code>$pdf->AddFont('dejavusans', '', 'DejaVuSans.ttf', true);
$pdf->AddFont('dejavusans', 'B', 'DejaVuSans-Bold.ttf', true);
$pdf->AddFont('dejavusans', 'I', 'DejaVuSans-Oblique.ttf', true);
$pdf->AddFont('dejavusans', 'BI', 'DejaVuSans-BoldOblique.ttf', true);
</code>```

Then, when using a font for a piece of text, use it like this:

```<code>$pdf->SetFont('dejavusans', '', 9);
</code>```

or

```<code>$pdf->SetFont('dejavusans', 'I', 10);
</code>```

So, only AddFont once, and then SetFont them where you need them. I tried using other names than 'dejavusans', but that did not seem to work.

Title: tFPDF add multiple DejaVu fonts

Body:
How would one use multiple styles of DejaVu fonts when using tFPDF?

I would like to use the DejaVuSans font for some text and DejaVuSansMono for other.

The tutorial  shows you can include font like this:$pdf -> AddFont('DejaVu','','DejaVuSans.ttf',true); and then use it like $pdf -> SetFont("DejaVu","",10);

But if I add additional font $pdf->AddFont('DejaVu','','DejaVuSansMono.ttf',true); nothing changes.

So how do I specify where I want to use the Mono font and where the default one?

My code currently looks like this (doesn't work):

$pdf->AddFont('DejaVu','','DejaVuSans.ttf',true);
$pdf->SetFont("DejaVu","",10);
$pdf->Cell(10,10 , "sometext");

$pdf->AddFont('DejaVu','','DejaVuSansMono.ttf',true);
$pdf->SetFont("DejaVu","",10);
$pdf->Cell(10,10 , "sometext");

Body:
For anyone still interested in an answer

You only need to AddFont once:

$pdf->AddFont('dejavusans', '', 'DejaVuSans.ttf', true);
$pdf->AddFont('dejavusans', 'B', 'DejaVuSans-Bold.ttf', true);
$pdf->AddFont('dejavusans', 'I', 'DejaVuSans-Oblique.ttf', true);
$pdf->AddFont('dejavusans', 'BI', 'DejaVuSans-BoldOblique.ttf', true);

Then, when using a font for a piece of text, use it like this:

$pdf->SetFont('dejavusans', '', 9);

or

$pdf->SetFont('dejavusans', 'I', 10);

So, only AddFont once, and then SetFont them where you need them. I tried using other names than 'dejavusans', but that did not seem to work.


问:
how to access table itself from dtOptions in angularJS-datatables
I'm tring to have a csv download button and need to exclude a couple of columns from table.

I've found a exportOptions defines which columns should be exported.
this option comes from jQuery datatalbles and table.column() method is likely to be used to select columns.

now I need to select certain columns, but I couldn't find out how with angular-datatables way.

anyone knows solution?

```<code>    <table dt-options="dtOptions" dt-column-defs="dtColumnDef">
        <thead>
            <tr>
                <th>hoo</th>
                <th>hoo</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>hoo</td>
                <td>hoo</td>
            </tr>
        </tbody>
    </table>

<script>
    // here is inside my controller

    $scope.dtOptions = DTOptionsBuilder
    .newOptions()
    .withDOM('tB')
    .withButtons([
    {
        text: 'download csv',
        extend: 'csv',
        exportOptions:
        {
            // columns: I neet to select certain columns here
            // wiht method like "table.columns(0)" mentioned in jQuery datatables document
            // but I don't know how in angular-datatables
        }
    }]);
</script>
</code>```

I use angular-way to render table.

答:
There is no difference between the angular way and a pure jQuery DataTable. And you do not need to access the table instance in exportOptions. What you need is to return a column selector; here are some examples (dont know exactly what you are trying to do) :

```<code>exportOptions: {
  columns: [0,4,5] //some columns by index
}
exportOptions: {
  columns: 'th' //any column
}
exportOptions: {
  columns: ['th:eq(1)', 'th:eq(5)'] //same as numbered array
}
exportOptions: {
  columns: 'th:not(:first)' //exclude the first column
}
exportOptions: {
  columns: 'th:not(.no-export)' //exclude columns with class no-export
}
</code>```

etc.

Body:
I'm tring to have a csv download button and need to exclude a couple of columns from table.

I've found a exportOptions defines which columns should be exported.
this option comes from jQuery datatalbles and table.column() method is likely to be used to select columns.

now I need to select certain columns, but I couldn't find out how with angular-datatables way.

anyone knows solution?

                hoo
                hoo

                hoo
                hoo

I use angular-way to render table.

Body:
There is no difference between the angular way and a pure jQuery DataTable. And you do not need to access the table instance in exportOptions. What you need is to return a column selector; here are some examples (dont know exactly what you are trying to do) :

exportOptions: {
  columns: [0,4,5] //some columns by index
}
exportOptions: {
  columns: 'th' //any column
}
exportOptions: {
  columns: ['th:eq(1)', 'th:eq(5)'] //same as numbered array
}
exportOptions: {
  columns: 'th:not(:first)' //exclude the first column
}
exportOptions: {
  columns: 'th:not(.no-export)' //exclude columns with class no-export
}

etc.


答:
You can create new li like this:</p>

```<code>let addNewFunc = function () {
      var ul = document.getElementById("list");
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("option string"));
      ul.appendChild(li);
};
</code>```

Title: Existing li gets overridden in todolist instead of adding a new li

Body:
You can create new li like this:

let addNewFunc = function () {
      var ul = document.getElementById("list");
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("option string"));
      ul.appendChild(li);
};


问:
Drop down in detailsview not updating to database
I have fields for a contact. 3 of those fields are drop downs to values from another table in the database. For example, Contacts has the foreign key for departmentid which pulls from the department table to get the description.  But when i click the Edit and update, this does not update my database.  It acts like nothing happened.

EDIT:  Just noticed this, but when i change the name and click update.  I get an error telling me that EmployerCode cannot be set to null.  I know that the database is set to not nullable.  But i do not understand why the original value is not being pulled.  When i load the contact, all three of the drop downs have values from the database loaded. Although i am seeing that all three are displaying the first item in the table and not the item the contact has in it's values.  But when editing the contact, it acts like those values are not loaded and are just null.

```<code><asp:DetailsView ID="detailsViewContact" runat="server" Height="90px" Width="293px"
DataSourceID="ContactDataSource" AutoGenerateRows="False"
BackColor="#FFCC66" BorderStyle="None" BorderWidth="0px" CellPadding="3"
DataKeyNames="ContactID" Font-Bold="True" HorizontalAlign="Center">
<CommandRowStyle BackColor="White" BorderColor="White" Font-Bold="True"
  Font-Size="Large" HorizontalAlign="Center" />
<Fields>
  <asp:BoundField DataField="SSOID" HeaderText="SSOID"
    SortExpression="SSOID" />
  <asp:BoundField DataField="FirstName" HeaderText="FirstName"
    SortExpression="FirstName" />
  <asp:BoundField DataField="Lastname" HeaderText="Lastname"
    SortExpression="Lastname" />
  <asp:BoundField DataField="Address" HeaderText="Address"
    SortExpression="Address" />
  <asp:BoundField DataField="City" HeaderText="City"
    SortExpression="City" />
  <asp:BoundField DataField="State" HeaderText="State"
    SortExpression="State" />
  <asp:BoundField DataField="ZipCode" HeaderText="ZipCode"
    SortExpression="ZipCode" />
  <asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress"
    SortExpression="EmailAddress" />
  <asp:TemplateField HeaderText="AccessRightID" SortExpression="AccessRightID">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList2" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList3" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList10" Enabled="false" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="EmployerCode" SortExpression="EmployerCode">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList5" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList6" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList4" Enabled="false" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="DepartmentID" SortExpression="DepartmentID">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList8" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList9" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList7" Enabled="false" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
    ShowInsertButton="True" />
</Fields>
</code>```

here are my datasources

```<code><asp:EntityDataSource ID="EmployerDataSource" runat="server"
ConnectionString="name=WorkStudyEntities"
DefaultContainerName="WorkStudyEntities" EnableFlattening="False"
EntitySetName="Employers" EnableUpdate="True">
</code>```

答: It looks like this was a fluke somehow. I redid the page and it all worked correctly</p>

Body:
I have fields for a contact. 3 of those fields are drop downs to values from another table in the database. For example, Contacts has the foreign key for departmentid which pulls from the department table to get the description.  But when i click the Edit and update, this does not update my database.  It acts like nothing happened.

EDIT:  Just noticed this, but when i change the name and click update.  I get an error telling me that EmployerCode cannot be set to null.  I know that the database is set to not nullable.  But i do not understand why the original value is not being pulled.  When i load the contact, all three of the drop downs have values from the database loaded. Although i am seeing that all three are displaying the first item in the table and not the item the contact has in it's values.  But when editing the contact, it acts like those values are not loaded and are just null.

<asp:DetailsView ID="detailsViewContact" runat="server" Height="90px" Width="293px"
DataSourceID="ContactDataSource" AutoGenerateRows="False"
BackColor="#FFCC66" BorderStyle="None" BorderWidth="0px" CellPadding="3"
DataKeyNames="ContactID" Font-Bold="True" HorizontalAlign="Center">
<CommandRowStyle BackColor="White" BorderColor="White" Font-Bold="True"
  Font-Size="Large" HorizontalAlign="Center" />
<Fields>
  <asp:BoundField DataField="SSOID" HeaderText="SSOID"
    SortExpression="SSOID" />
  <asp:BoundField DataField="FirstName" HeaderText="FirstName"
    SortExpression="FirstName" />
  <asp:BoundField DataField="Lastname" HeaderText="Lastname"
    SortExpression="Lastname" />
  <asp:BoundField DataField="Address" HeaderText="Address"
    SortExpression="Address" />
  <asp:BoundField DataField="City" HeaderText="City"
    SortExpression="City" />
  <asp:BoundField DataField="State" HeaderText="State"
    SortExpression="State" />
  <asp:BoundField DataField="ZipCode" HeaderText="ZipCode"
    SortExpression="ZipCode" />
  <asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress"
    SortExpression="EmailAddress" />
  <asp:TemplateField HeaderText="AccessRightID" SortExpression="AccessRightID">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList2" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList3" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList10" Enabled="false" runat="server"
        DataSourceID="AccessRightDataSource" DataTextField="AccessRightDescription"
        DataValueField="AccessRightID">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="EmployerCode" SortExpression="EmployerCode">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList5" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList6" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList4" Enabled="false" runat="server"
        DataSourceID="EmployerDataSource" DataTextField="EmployerName"
        DataValueField="EmployerCode">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="DepartmentID" SortExpression="DepartmentID">
    <EditItemTemplate>
      <asp:DropDownList ID="DropDownList8" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </EditItemTemplate>
    <InsertItemTemplate>
      <asp:DropDownList ID="DropDownList9" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </InsertItemTemplate>
    <ItemTemplate>
      <asp:DropDownList ID="DropDownList7" Enabled="false" runat="server"
        DataSourceID="DepartmentDataSource" DataTextField="Description"
        DataValueField="DepartmentID">
      </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateField>
  <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
    ShowInsertButton="True" />
</Fields>

here are my datasources

<asp:EntityDataSource ID="EmployerDataSource" runat="server"
ConnectionString="name=WorkStudyEntities"
DefaultContainerName="WorkStudyEntities" EnableFlattening="False"
EntitySetName="Employers" EnableUpdate="True">


问:
Unable insert element in nested array dynamically
I am working on angular tree which is having a large nested array.

nodes :

```<code>public fonts: TreeModel = {
    value: 'Fonts',
    children: [
      {
        value: 'Serif  -  All my children and I are STATIC ¯\\_(ツ)_/¯',
        settings: {
          'static': true
        },
        children: [
          { value: 'Antiqua' },
          { value: 'DejaVu Serif' },
          { value: 'Garamond' },
          { value: 'Georgia' },
          { value: 'Times New Roman' },
          {
            value: 'Slab serif',
            children: [
              { value: 'Candida' },
              { value: 'Swift' },
              { value: 'Guardian Egyptian' }
            ]
          }
        ]
      },
      {
        value: 'Sans-serif',
        children: [
          { value: 'Arial' },
          { value: 'Century Gothic' },
          { value: 'DejaVu Sans' },
          { value: 'Futura' },
          { value: 'Geneva' },
          { value: 'Liberation Sans' }
        ]
      }
    ]};
</code>```

The Tree looks similar to one present in image :

Each time user clicks on Any node, an API request goes to bring Child of that node (JSON Array). then i need to append this response array into original tree array .
The problem I'm facing is how do i insert child of nodes dynamically into original array against the parent node user clicked on.

Any better solution of current problem will also be  helpful for me.
Currently i am using angular2-tree-component to implement the tree.

答:
Finally i got the solution.

I switched to ng2-tree to implement the tree.
It has all the in built methods for tree-nodes and also it is well documented.

npm: ng2-tree

For every node provide an id. When user clicks on any node call a method to add childs into it.

```<code>public addChildFFS(id: number | string, newNode: TreeModel) {

    newNode.id = ++this.lastFFSNodeId;
    const treeController = this.treeFFS.getControllerByNodeId(id);
    if (treeController) {
        treeController.addChild(newNode);
    } else {}
}
</code>```

Body:
I am working on angular tree which is having a large nested array.

nodes :

public fonts: TreeModel = {
    value: 'Fonts',
    children: [
      {
        value: 'Serif  -  All my children and I are STATIC ¯\\_(ツ)_/¯',
        settings: {
          'static': true
        },
        children: [
          { value: 'Antiqua' },
          { value: 'DejaVu Serif' },
          { value: 'Garamond' },
          { value: 'Georgia' },
          { value: 'Times New Roman' },
          {
            value: 'Slab serif',
            children: [
              { value: 'Candida' },
              { value: 'Swift' },
              { value: 'Guardian Egyptian' }
            ]
          }
        ]
      },
      {
        value: 'Sans-serif',
        children: [
          { value: 'Arial' },
          { value: 'Century Gothic' },
          { value: 'DejaVu Sans' },
          { value: 'Futura' },
          { value: 'Geneva' },
          { value: 'Liberation Sans' }
        ]
      }
    ]};

The Tree looks similar to one present in image :

Each time user clicks on Any node, an API request goes to bring Child of that node (JSON Array). then i need to append this response array into original tree array .
The problem I'm facing is how do i insert child of nodes dynamically into original array against the parent node user clicked on.

Any better solution of current problem will also be  helpful for me.
Currently i am using angular2-tree-component to implement the tree.

Body:
Finally i got the solution.

I switched to ng2-tree to implement the tree.
It has all the in built methods for tree-nodes and also it is well documented.

npm: ng2-tree

For every node provide an id. When user clicks on any node call a method to add childs into it.

public addChildFFS(id: number | string, newNode: TreeModel) {

    newNode.id = ++this.lastFFSNodeId;
    const treeController = this.treeFFS.getControllerByNodeId(id);
    if (treeController) {
        treeController.addChild(newNode);
    } else {}
}


问:
sidebar-toggle adminlte not work in yii2
How can I fix my left side navigation. I am using AdminLTE 2.0in yii2 framework.

The problem is, the toggle side-bar not work after i do composer update yesterday (9.00 am Malaysia time).

I suspect the error must happen from javascript.

But could not find any.

Therefore, i give you my code to discuss here.

Thank You

backend\views\layout\header.php

<?php
use backend\assets\AppAsset;
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;

/* @var $this \yii\web\View */
/* @var $content string */

AppAsset::register($this);
?>

        AU

        AuTem

            Toggle navigation

                        4

You have 4 messages

                            <img src="<?= $directoryAsset ?>/img/avatar2.png" class="img-circle" alt="user image"/>

                            AdminLTE Design Team
                             2 hours

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar.png" class="img-circle" alt="user image"/>

                            Developers
                             Today

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar2.png" class="img-circle" alt="user image"/>

                            Sales Department
                             Yesterday

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar.png" class="img-circle" alt="user image"/>

                            Reviewers
                             2 days

Why not buy a new awesome theme?

See All Messages

        10

You have 10 notifications

                         5 new members joined today

                         Very long description here that may not fit into the page
                        and may cause design problems

                         5 new members joined

                         25 sales made

                         You changed your username

View all

        9

You have 9 tasks

                            Design some buttons
                            20%

                                20% Complete

                            Create a nice theme
                            40%

                                40% Complete

                            Some task I need to do
                            60%

                                60% Complete

                            Make beautiful transitions
                            80%

                                80% Complete

            View all tasks

<?php
if (Yii::$app->user->isGuest) {
    ?>

        <?= Html::a('Login', ['/site/login']) ?>

<?php
} else {
    ?>

            <?= @Yii::$app->user->identity->username ?>

                <img src="<?= $directoryAsset ?>/img/avatar5.png" class="img-circle" alt="User Image"/>

                    <?= @Yii::$app->user->identity->username ?> - Web Developer
                    Member since Nov. 2012

                    Followers

                    Sales

                    Friends

                    Profile

                    <?= Html::a(
                            'Sign out',
                            ['/site/logout'],
                            ['data-method' => 'post','class'=>'btn btn-default btn-flat']
                        ) ?>

<?php
}
?>

```
</div>
</div>
</p>

<p>backend\assets\AppAsset.php</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        'js/highcharts.js',
        'js/exporting.js',
        'js/graphDashboard.js',
        'js/jquery.dataTables.bootstrap.js',
        'js/jquery.dataTables.min.js',
        'js/manageAlumni.js',
        'js/viewReport.js',
        'js/managefaculty.js',
        'js/managecourse.js',
        'js/statisticAlumni.js',
        'js/advSearch.js',
        'js/app.min.js',

    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        //'fedemotta\datatables\DataTablesAsset',
    ];
}</code>```

答:
Try to replace

```<code>data-toggle="offcanvas"
</code>```

with

```<code>data-toggle="push-menu"
</code>```

Body:
How can I fix my left side navigation. I am using AdminLTE 2.0in yii2 framework.

The problem is, the toggle side-bar not work after i do composer update yesterday (9.00 am Malaysia time).

I suspect the error must happen from javascript.

But could not find any.

Therefore, i give you my code to discuss here.

Thank You

backend\views\layout\header.php

<?php
use backend\assets\AppAsset;
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;

/* @var $this \yii\web\View */
/* @var $content string */

AppAsset::register($this);
?>

        AU

        AuTem

            Toggle navigation

                        4

You have 4 messages

                            <img src="<?= $directoryAsset ?>/img/avatar2.png" class="img-circle" alt="user image"/>

                            AdminLTE Design Team
                             2 hours

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar.png" class="img-circle" alt="user image"/>

                            Developers
                             Today

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar2.png" class="img-circle" alt="user image"/>

                            Sales Department
                             Yesterday

Why not buy a new awesome theme?

                            <img src="<?= $directoryAsset ?>/img/avatar.png" class="img-circle" alt="user image"/>

                            Reviewers
                             2 days

Why not buy a new awesome theme?

See All Messages

        10

You have 10 notifications

                         5 new members joined today

                         Very long description here that may not fit into the page
                        and may cause design problems

                         5 new members joined

                         25 sales made

                         You changed your username

View all

        9

You have 9 tasks

                            Design some buttons
                            20%

                                20% Complete

                            Create a nice theme
                            40%

                                40% Complete

                            Some task I need to do
                            60%

                                60% Complete

                            Make beautiful transitions
                            80%

                                80% Complete

            View all tasks

<?php
if (Yii::$app->user->isGuest) {
    ?>

        <?= Html::a('Login', ['/site/login']) ?>

<?php
} else {
    ?>

            <?= @Yii::$app->user->identity->username ?>

                <img src="<?= $directoryAsset ?>/img/avatar5.png" class="img-circle" alt="User Image"/>

                    <?= @Yii::$app->user->identity->username ?> - Web Developer
                    Member since Nov. 2012

                    Followers

                    Sales

                    Friends

                    Profile

                    <?= Html::a(
                            'Sign out',
                            ['/site/logout'],
                            ['data-method' => 'post','class'=>'btn btn-default btn-flat']
                        ) ?>

<?php
}
?>

backend\assets\AppAsset.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        'js/highcharts.js',
        'js/exporting.js',
        'js/graphDashboard.js',
        'js/jquery.dataTables.bootstrap.js',
        'js/jquery.dataTables.min.js',
        'js/manageAlumni.js',
        'js/viewReport.js',
        'js/managefaculty.js',
        'js/managecourse.js',
        'js/statisticAlumni.js',
        'js/advSearch.js',
        'js/app.min.js',

    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        //'fedemotta\datatables\DataTablesAsset',
    ];
}

Body:
Try to replace

data-toggle="offcanvas"

with

data-toggle="push-menu"