问:
DotNetOpenAuth vs Owin OAuth
I am new the webAPI2, so please excuse me if my question is trivial. I want to implement token based security for my webAPI, so that other applications (apart from my SPA) can also call my webAPIs.

I started with Owin OpenAuth and implemented a POC. Everything worked well. But when I had to send client to Authorization to Authorization server, I could not find any inbuilt function to do that. I had to build this my self. Then I came across DotNetOpenAuth that provides APIs to set the communication as well. As far as I could find out, Microsoft is favoring Owin OpenAuth over DotNetOpenAuth.

Can anybody please provide the differences between these two? Also, which one is recommended?

Thanks In Advance

答:
Brock Allen answered a similar question here

The OWIN middleware is grated more for just the protocol bits, but has
  none of the necessary persistence bits (or replay protection or
  refresh token support or many other things). If you are interested in
  working directly with the protocol because you want to learn it and
  really learn how to build a server, then the OWIN middleware is an ok
  place to start. But if all you want is a sever that already has all of
  those pieces implemented, then consider looking into IdentityServer

or DotnetOpenAuth

Title: DotNetOpenAuth vs Owin OAuth


来源: stackexchange

问:
Bluetooth app not working on devices running on Lollipop
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

```<code>private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }
</code>```

CheckBTPermissions()-

```<code>private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }
</code>```

Permissions in Manifest file-

```<code><uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
</code>```

build.gradle-

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

```<code>07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
</code>```

答:
The exception says it all, the method checkSelfPermission is only available on API 23 onwards. If you want to check permission with API 21, use the Android support library and ContextCompat.checkSelfPermission

Edit: Also, location permissions for Bluetooth are only required from API 23 onwards.

ContentLicense: CC BY-SA 3.0

Body:
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }

CheckBTPermissions()-

private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }

Permissions in Manifest file-

<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />

build.gradle-

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)


问:
Change Tableau custom SQL query to reflect year instead of number
Custom SQL query
--Why does year come out as a number with sum parameter

```<code>select
YEAR(s.OrderDate) 'Year',
cat.EnglishProductCategoryName 'Category',
sub.EnglishProductSubcategoryName 'Subcategory',

Count(1) 'Count',
sum (s.SalesAmount) 'Sales',
avg (s.SalesAmount) 'Avg_Sales_Amt',
min (s.SalesAmount) 'Min_Sales_Amt',
max (s.SalesAmount) 'Max_Sales_Amt'
</code>```

Table output

答:
Why - as Tableau recognises it as a number and converts it to that format.  </p>

<p>You can just change Year to Dimension instead a Measure and change the data type to String instead of changing the Custom SQL. </p>

Body:
Custom SQL query
--Why does year come out as a number with sum parameter

select
YEAR(s.OrderDate) 'Year',
cat.EnglishProductCategoryName 'Category',
sub.EnglishProductSubcategoryName 'Subcategory',

Count(1) 'Count',
sum (s.SalesAmount) 'Sales',
avg (s.SalesAmount) 'Avg_Sales_Amt',
min (s.SalesAmount) 'Min_Sales_Amt',
max (s.SalesAmount) 'Max_Sales_Amt'

Table output

Body:
Why - as Tableau recognises it as a number and converts it to that format.

You can just change Year to Dimension instead a Measure and change the data type to String instead of changing the Custom SQL.


问:
CSS - positioning images centrally within a container
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="welcome">
  <div class="container">
    <div class="row">
      <div class="twelve columns">
        <h4>WELCOME TO FEATURE MEDIA</h4>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.</p>
      </div>
    </div>
    <hr class="hrindeximages">
    <div class="images row">
      <div class="four columns">
        <div id="video">
          <h3>VIDEO</h3>
          <img src="images/VIDEO.jpg" alt="Video" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="blog">
          <h3>BLOG</h3>
          <img src="images/blog.jpg" alt="blog" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="faq">
          <h3>FAQ</h3>
          <img src="images/faq.jpg" alt="FAQ" style="width:300px;height:150px;">
        </div>
      </div>
    </div>
  </div>
</section></code>```

答:
The issue is caused by the margin-right: 100px attribute in the .images, .four class. If you get rid of that, your images should be centered:

```<code>.images, .four {
    margin-right: 100px; // this line causes your images to offset from center
}
</code>```

If you still want to have that space in between your images, you can add a margin-left field to balance it out:

```<code>.images, .four {
    margin-right: 50px;
    margin-left: 50px;
}
</code>```

Body:
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}

WELCOME TO FEATURE MEDIA

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.

VIDEO

BLOG

FAQ

Body:
The issue is caused by the margin-right: 100px attribute in the .images, .four class. If you get rid of that, your images should be centered:

.images, .four {
    margin-right: 100px; // this line causes your images to offset from center
}

If you still want to have that space in between your images, you can add a margin-left field to balance it out:

.images, .four {
    margin-right: 50px;
    margin-left: 50px;
}


问:
Proxy Design Pattern- tutorialspoint.com example
http://www.tutorialspoint.com/design_pattern/proxy_pattern.htm

Hi,

I am looking to understand proxy design pattern in java using the example in the
link above. In main method I don't understand the difference between:

```<code>  //image will be loaded from disk

  image.display();
  System.out.println("");

  //image will not be loaded from disk

  image.display();
</code>```

Is this a typo? How can the same 2 image.display() methods give different outputs?

Thanks a lot!

答:
The only difference and easy way to understand it is by using constructor and calling the functionality method, which is to load the image here. If you instantiate your interface with the implementation of this non proxy MainFunctionalityClass and that implementation loads the image inside this constructor. However, using proxy is to apply a wrapper over the MainFunctionalityClass and this time, the called constructor is that of the Proxy's, it means, the MainFunctionalityClass constructor is skipped here.

```<code>    class MainFunctionalityClass implements ICommon{

    MainFunctionalityClass(){
     loadMainFunctionality(); // Costly call
    }
}
</code>```

While the proxy class is defined as:

```<code>class Proxy implements ICommon{
 private String var;

Proxy(String var){
this.var = var; //NO call to big functionality, not costly
}

callMainFunctionality(){
//uses var, MainFunctionalityClass() called
// Costly call but it is called on demand,
}

class MainClassTest{
 public static void main(String[] args){
 ICommon p = new Proxy("abcd");
p.callMainFunctionality();
}

}
</code>```

Proxy Design Pattern can be used for

Loading big functionality on demand lazily.

Restricting the operations of the client(not explained above)

To implement it we need to first to use same interface in both the classes and then to use composition in the proxy class.

Body:
http://www.tutorialspoint.com/design_pattern/proxy_pattern.htm

Hi,

I am looking to understand proxy design pattern in java using the example in the
link above. In main method I don't understand the difference between:

  //image will be loaded from disk

  image.display();
  System.out.println("");

  //image will not be loaded from disk

  image.display();

Is this a typo? How can the same 2 image.display() methods give different outputs?

Thanks a lot!

Body:
The only difference and easy way to understand it is by using constructor and calling the functionality method, which is to load the image here. If you instantiate your interface with the implementation of this non proxy MainFunctionalityClass and that implementation loads the image inside this constructor. However, using proxy is to apply a wrapper over the MainFunctionalityClass and this time, the called constructor is that of the Proxy's, it means, the MainFunctionalityClass constructor is skipped here.

    class MainFunctionalityClass implements ICommon{

    MainFunctionalityClass(){
     loadMainFunctionality(); // Costly call
    }
}

While the proxy class is defined as:

class Proxy implements ICommon{
 private String var;

Proxy(String var){
this.var = var; //NO call to big functionality, not costly
}

callMainFunctionality(){
//uses var, MainFunctionalityClass() called
// Costly call but it is called on demand,
}

class MainClassTest{
 public static void main(String[] args){
 ICommon p = new Proxy("abcd");
p.callMainFunctionality();
}

}

Proxy Design Pattern can be used for

Loading big functionality on demand lazily.

Restricting the operations of the client(not explained above)

To implement it we need to first to use same interface in both the classes and then to use composition in the proxy class.


问:
In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?
I'm using Eclipse for Java development. All my sources compile fine and the resulting application compiles fine. However, I keep getting an "red-x" error notification in the Package Explorer.

All my sources in this source directory (too long for the snapshot) compile fine, none of the show the "red-x" error icon.

Any suggestions on how to fix the problem would be highly appreciated.

答:
Right click on the project with errors, then in the sub-menus select:
 Maven > UpdateProject >

and then:

Select the checkbox for all the dependent projects

select force update of snapshots

click OK.

This worked for me..

OwnerDisplayName: Alfred B. Thordarson


问:
Ways to cast objects to a generic type
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

```<code>private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}
</code>```

and

```<code>private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}
</code>```

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

答:
Because as implies the cast could fail and return null. Without a : class, T could be int etc - which can't be null. With (T)obj it will simply explode in a shower of sparks; no need to handle a null.

As an aside (re struct), note you can use as if it is known you are casting to a Nullable<> - for example:

```<code>static T? Cast<T>(object obj) where T : struct
{
    return obj as T?;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ways to cast objects to a generic type

Body:
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}

and

private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

Body:
Because as implies the cast could fail and return null. Without a : class, T could be int etc - which can't be null. With (T)obj it will simply explode in a shower of sparks; no need to handle a null.

As an aside (re struct), note you can use as if it is known you are casting to a Nullable<> - for example:

static T? Cast<T>(object obj) where T : struct
{
    return obj as T?;
}


问:
Post data to Firebase using Angular 2 without generating the automatic key,
I am using Angular 2 with Firebase as a service provider. And I am not using angular-cli.

Whenever I post some data, it is posted but Firebase generates a unique key based on time stamp, which I don't need. I need to set a custom number or ID at that place. Angular 1 has the provision using child and set property. Is there any provision in Angular 2 too?

答:
You can do this way:

```<code>this.af.database.object(`list/myCustomKey`).update({ age: 101 });
</code>```

See: https://github.com/angular/angularfire2/issues/672

Body:
You can do this way:

this.af.database.object(`list/myCustomKey`).update({ age: 101 });

See: https://github.com/angular/angularfire2/issues/672


问:
SSRS Subscription Schedule Started/Completed Events
I am pretty new to SSRS and I am trying to find a way to know when scheduled report is actually started on the server, when it has completed with success of failure and if it was canceled. As of now, I am using the ReportingService2010 class API to talk to the Report Server and the only way that it seems possible to me is to make something custom that checks the schedules and fire events at these times for the started events and to scan the folder where I'm going to save the report and when a new file is added, I know that the report has been successfully created, and maybe add a Timeout event after x time.

I don't think this is a really clean approach and I'm sure that you guys might have an easier answer because I'm sure that there must be a way to do it without manually scanning everything.

I used the ListJobs() method to access all the jobs that are currently running on the server but it doesn't seem to consider when a subscription is done, because, I only get results in the ListJobs() method when I manually click on "Run Now" for a specific report on the server.

Do you guys have any idea?

Thanks a lot,

Claude

答:
There are few tables in 'ReportServer' database to provide you most of your information. e.g Subscriptions table has column as LastStatus, it gives how many subscriptions were processed and status of reports last run. e.g 'Done: 2 processed of 2 total; 0 errors' , 'Pending' ,

sample query would be like below, this is for getting a schedule but you can check and modify as you need.

Setup a new report with this query and schedule it as per your need to give you the status.

```<code>SELECT CAT.Name
  ,CAT.[Path] AS ReportPath
  ,SUB.LastRunTime
  ,SCH.NextRunTime
  ,CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime,   1), 101) As RunDate
  ,right(convert(varchar(32),SCH.NextRunTime,100),8) As RunTime
  ,SUB.[Description]
  ,SUB.EventType
  ,SUB.LastStatus
  ,SUB.ModifiedDate
  ,SCH.Name AS ScheduleName
FROM reportserver.dbo.Subscriptions AS SUB
 INNER JOIN reportserver.dbo.Users AS USR
     ON SUB.OwnerID = USR.UserID
 INNER JOIN reportserver.dbo.[Catalog] AS CAT
     ON SUB.Report_OID = CAT.ItemID
 INNER JOIN reportserver.dbo.ReportSchedule AS RS
     ON SUB.Report_OID = RS.ReportID
        AND SUB.SubscriptionID = RS.SubscriptionID
 INNER JOIN reportserver.dbo.Schedule AS SCH
     ON RS.ScheduleID = SCH.ScheduleID
--Where CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime,   1), 101)
= CONVERT(VARCHAR(10), CONVERT(datetime, getDate()+1,   1), 101)
ORDER BY USR.UserName
    ,CAT.[Path];
</code>```

Body:
There are few tables in 'ReportServer' database to provide you most of your information. e.g Subscriptions table has column as LastStatus, it gives how many subscriptions were processed and status of reports last run. e.g 'Done: 2 processed of 2 total; 0 errors' , 'Pending' ,

sample query would be like below, this is for getting a schedule but you can check and modify as you need.

Setup a new report with this query and schedule it as per your need to give you the status.

SELECT CAT.Name
  ,CAT.[Path] AS ReportPath
  ,SUB.LastRunTime
  ,SCH.NextRunTime
  ,CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime,   1), 101) As RunDate
  ,right(convert(varchar(32),SCH.NextRunTime,100),8) As RunTime
  ,SUB.[Description]
  ,SUB.EventType
  ,SUB.LastStatus
  ,SUB.ModifiedDate
  ,SCH.Name AS ScheduleName
FROM reportserver.dbo.Subscriptions AS SUB
 INNER JOIN reportserver.dbo.Users AS USR
     ON SUB.OwnerID = USR.UserID
 INNER JOIN reportserver.dbo.[Catalog] AS CAT
     ON SUB.Report_OID = CAT.ItemID
 INNER JOIN reportserver.dbo.ReportSchedule AS RS
     ON SUB.Report_OID = RS.ReportID
        AND SUB.SubscriptionID = RS.SubscriptionID
 INNER JOIN reportserver.dbo.Schedule AS SCH
     ON RS.ScheduleID = SCH.ScheduleID
--Where CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime,   1), 101)
= CONVERT(VARCHAR(10), CONVERT(datetime, getDate()+1,   1), 101)
ORDER BY USR.UserName
    ,CAT.[Path];


问:
use expression tree to evaluate properties of a generic class
i have to evaluate a formula which contains certain expressions, say for eg:"column1 * column3". These column names are dynamic and are generated only at run time. I have the class objects with me having these column names.
The expressions can have any basic arithmetic operators.

I think this could be approached with Expression tree in c#. Would that be the best approach. If so could someone provide me some assistance on how to approach this because i could not find any good examples on Expression trees. Or whether it could/should be done using reflections.

Thanks

答: That really depends, if it is not performance critical code, you are much better off with reflection, the source code will be easier to read and maintain.</p>


问:
XNA GIF Animation Library problem
hey guys, i am trying to use the XNA　Gif Animation Library that i found online, then when i running , it keep givving me an exception said "The size of the data passed in is too large or too small for this resource." for GifAnimationContentTypeReader

```<code>        for (int i = 0; i < num; i++)
        {
            SurfaceFormat format = (SurfaceFormat) input.ReadInt32();
            int width = input.ReadInt32();
            int height = input.ReadInt32();
            int numberLevels = input.ReadInt32();
            frames[i] = new Texture2D(graphicsDevice, width, height, false, format);
            for (int j = 0; j < numberLevels; j++)
            {
                int count = input.ReadInt32();
                byte[] data = input.ReadBytes(count);
                Rectangle? rect = null;
                frames[i].SetData<byte>(j, rect, data, 0, data.Length);
            }
        }
</code>```

at this line "frames[i].SetData(j, rect, data, 0, data.Length);"
I donno how, but the data length is really huge though

Anyone know hows that happen
thx

答:
The number of bytes (in your code: count and data.Length) should be equal to width * height * bytesPerPixel, where the bytesPerPixel depends on the data format (for the default SurfaceFormat.Color format it is 4).

If it is not equal, you don't have enough data (or have too much data) for the that texture.

You haven't provided enough detail in your question for me to be able to tell you why your the values are not equal.

Title: XNA GIF Animation Library problem

Body:
hey guys, i am trying to use the XNA　Gif Animation Library that i found online, then when i running , it keep givving me an exception said "The size of the data passed in is too large or too small for this resource." for GifAnimationContentTypeReader

        for (int i = 0; i < num; i++)
        {
            SurfaceFormat format = (SurfaceFormat) input.ReadInt32();
            int width = input.ReadInt32();
            int height = input.ReadInt32();
            int numberLevels = input.ReadInt32();
            frames[i] = new Texture2D(graphicsDevice, width, height, false, format);
            for (int j = 0; j < numberLevels; j++)
            {
                int count = input.ReadInt32();
                byte[] data = input.ReadBytes(count);
                Rectangle? rect = null;
                frames[i].SetData<byte>(j, rect, data, 0, data.Length);
            }
        }

at this line "frames[i].SetData(j, rect, data, 0, data.Length);"
I donno how, but the data length is really huge though

Anyone know hows that happen
thx


问:
unable to install pandas
```<code>Swans-MacBook-Pro:~ swan_919$ sudo pip install pandas
The directory '/Users/swan_919/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/swan_919/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: pandas in /Library/Python/2.7/site-packages
Requirement already satisfied: pytz>=2011k in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Requirement already satisfied: numpy>=1.7.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Swans-MacBook-Pro:~ swan_919$
</code>```

<p>Hi, I just started learning programming and data science. I had pandas on my previous python version but it wasn't accessible on python 3.6. so at first, i deleted the old pandas files. and tried to install again, but that's basically what happens when i try to do either pip install pandas or sudo pip install pandas. And i can't import pandas either. I would really appreciate the help. thank you! </p>

答: I am not sure why I was getting all these error messages when I tried the suggested answers. But what ended up working for me is when I just do 'pip3 install pandas'</p>

Title: unable to install pandas

Body:
Swans-MacBook-Pro:~ swan_919$ sudo pip install pandas
The directory '/Users/swan_919/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/swan_919/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: pandas in /Library/Python/2.7/site-packages
Requirement already satisfied: pytz>=2011k in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Requirement already satisfied: numpy>=1.7.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas)
Swans-MacBook-Pro:~ swan_919$

Hi, I just started learning programming and data science. I had pandas on my previous python version but it wasn't accessible on python 3.6. so at first, i deleted the old pandas files. and tried to install again, but that's basically what happens when i try to do either pip install pandas or sudo pip install pandas. And i can't import pandas either. I would really appreciate the help. thank you!


问:
How can I check debug mode on Laravel
I want to see errors when I work in the localhost.

App\Exceptions\handler.php

I Tried:

```<code>public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception) && env('APP_DEBUG') === false) {
        return response()->view('errors.404', [], 404);
    } else {
        return parent::render($request, $exception);
    }
}
</code>```

or;

```<code>if ($this->isHttpException($exception) && App::environment('APP_DEBUG') === false)
</code>```

I tried it as above but it does not work.

Thanks.

APP_DEBUG is set to true in .env

答:
Try to change

```<code>env('APP_DEBUG') === false
</code>```

to

```<code>env('APP_DEBUG') == false
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I check debug mode on Laravel

Body:
I want to see errors when I work in the localhost.

App\Exceptions\handler.php

I Tried:

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception) && env('APP_DEBUG') === false) {
        return response()->view('errors.404', [], 404);
    } else {
        return parent::render($request, $exception);
    }
}

or;

if ($this->isHttpException($exception) && App::environment('APP_DEBUG') === false)

I tried it as above but it does not work.

Thanks.

APP_DEBUG is set to true in .env

Body:
Try to change

env('APP_DEBUG') === false

to

env('APP_DEBUG') == false


问:
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse’
I just changed the CMakeLists.txt by adding:

```<code>SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_C_COMPILER   /opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-gcc)
SET(CMAKE_CXX_COMPILER /opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-g++)

SET(CMAKE_FIND_ROOT_PATH  /opt/hisi-linux/x86-arm/arm-hisiv300-linux/)
</code>```

Unluckly,I got a problem:

```<code>root@lzw-virtual-machine:/home/lzw/OpenFace/OpenFace/build# make
Scanning dependencies of target dlib
[  1%] Building CXX object lib/3rdParty/dlib/CMakeFiles/dlib.dir/include/dlib/base64/base64_kernel_1.o
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse’
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse2’
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse3’
</code>```

答:
Those are all options enabling various generations of the x86 instruction set extensions for the SSE SIMD processing unit; they don't exist on ARM so they are not going to work ...

Check your build system is able to distinguish based on CPU architecture ...

Body:
I just changed the CMakeLists.txt by adding:

SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_C_COMPILER   /opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-gcc)
SET(CMAKE_CXX_COMPILER /opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-g++)

SET(CMAKE_FIND_ROOT_PATH  /opt/hisi-linux/x86-arm/arm-hisiv300-linux/)

Unluckly,I got a problem:

root@lzw-virtual-machine:/home/lzw/OpenFace/OpenFace/build# make
Scanning dependencies of target dlib
[  1%] Building CXX object lib/3rdParty/dlib/CMakeFiles/dlib.dir/include/dlib/base64/base64_kernel_1.o
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse’
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse2’
arm-hisiv300-linux-g++: error: unrecognized command line option ‘-msse3’


问:
Trying to understand power function, C Programming Language, 2e, 27
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

```<code>int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}
</code>```

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

答: Thanks for all the great replies. I didn't respond straight away but I did notice how quickly I got several replies. If I only I'd tried this site years ago :-)</p>

Body:
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?


问:
what the name for the item in the green circle
what's the element name in the green circle? Whta's the event corresponding to click this element?

答:
As others have stated, it's the "Select All" Button. Clicking it will select everything in the DataGrid if SelectionMode is set to Extended.

The "Select All" Button is part of the DataGrid Template. Or actually, it's part of the ScrollViewer Template that is part of the DataGrid Template so it's nested pretty deep. The ControlTemplate looks like this. From here you can do anything you want with the SelectAll Button, disable it, change the Background etc.

```<code><Style TargetType="{x:Type DataGrid}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGrid}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
                    <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false">
                        <ScrollViewer.Template>
                            <ControlTemplate TargetType="{x:Type ScrollViewer}">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>

                                    <!-- Here it is -->
                                    <Button Command="{x:Static DataGrid.SelectAllCommand}" Focusable="false" Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.All}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>

                                    <DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" Grid.Column="1" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                                    <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" Grid.ColumnSpan="2" Grid.Row="1"/>
                                    <ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="2" Maximum="{TemplateBinding ScrollableHeight}" Orientation="Vertical" Grid.Row="1" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}"/>
                                    <Grid Grid.Column="1" Grid.Row="2">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>
                                        <ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="1" Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
                                    </Grid>
                                </Grid>
                            </ControlTemplate>
                        </ScrollViewer.Template>
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
As others have stated, it's the "Select All" Button. Clicking it will select everything in the DataGrid if SelectionMode is set to Extended.

The "Select All" Button is part of the DataGrid Template. Or actually, it's part of the ScrollViewer Template that is part of the DataGrid Template so it's nested pretty deep. The ControlTemplate looks like this. From here you can do anything you want with the SelectAll Button, disable it, change the Background etc.

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGrid}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
                    <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false">
                        <ScrollViewer.Template>
                            <ControlTemplate TargetType="{x:Type ScrollViewer}">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>

                                    <!-- Here it is -->
                                    <Button Command="{x:Static DataGrid.SelectAllCommand}" Focusable="false" Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.All}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>

                                    <DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" Grid.Column="1" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                                    <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" Grid.ColumnSpan="2" Grid.Row="1"/>
                                    <ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="2" Maximum="{TemplateBinding ScrollableHeight}" Orientation="Vertical" Grid.Row="1" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}"/>
                                    <Grid Grid.Column="1" Grid.Row="2">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>
                                        <ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="1" Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
                                    </Grid>
                                </Grid>
                            </ControlTemplate>
                        </ScrollViewer.Template>
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
Get instance function from header file
I am currently testing private frameworks for IOS and currently I'm trying to figure out how to check if Night Shift is enabled. For reference, the header file I am working with is located here.

And here is the code I am using below:

```<code>  if (!(NSClassFromString(@"CCUINightShiftSectionController"))) {
            dlopen("System/Library/PrivateFrameworks/ControlCenterUI.framework/ControlCenterUI", RTLD_LOCAL);
}

     NSObject *manager = [NSClassFromString(@"CCUINightShiftSectionController") performSelector:NSSelectorFromString(@"_defaultFontTight")];

            NSLog(@" ok= %@", manager);

        }
</code>```

From that file, I got the data for _defaultFontTight to print in the NSLog just fine, but what I'm struggling with is how do I get the instance functions? More specifically, everything below that start with a -  symbol. I can only get info from a +
 symbol.

If I were to switch out _defaultFontTight with enabled then I get the following:

```<code>2017-07-02 18:09:35.382109-0400 Testing[809:96270] +[CCUINightShiftSectionController enabled]: unrecognized selector sent to class 0x1b7d5e420
</code>```

Any help would be greatly appreciated!

EDIT:

I tried this code below:

```<code>id myInstance =[NSClassFromString(@"CCUINightShiftSectionController") new];
[myInstance performSelector:NSSelectorFromString(@"enabled")];
</code>```

For some frameworks, it gets the instance variable values sucessfully, while for most it just returns null or errors such as [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""

答:
Please note that you are using private frameworks (not documented), and the header file that you are referencing to it, is corresponding to iOS 10.2, so make sure to make your tests on a real iPhone running the same iOS version.

For your calls, try to make them like this:

```<code>id myInstance = [NSClassFromString(@"CCUINightShiftSectionController") new];
if ([myInstance respondsToSelector:@selector(someInstanceMethod)]) {
    [myInstance performSelector:@selector(someInstanceMethod)];
}
</code>```

Also i note that "CCUINightShiftSectionController" is looking to be a "UIViewController" subclass, and it will not be well initialized using the "new" initializer, so you may have null or wrong results.

Good luck to make it working.

Title: Get instance function from header file

Body:
I am currently testing private frameworks for IOS and currently I'm trying to figure out how to check if Night Shift is enabled. For reference, the header file I am working with is located here.

And here is the code I am using below:

  if (!(NSClassFromString(@"CCUINightShiftSectionController"))) {
            dlopen("System/Library/PrivateFrameworks/ControlCenterUI.framework/ControlCenterUI", RTLD_LOCAL);
}

     NSObject *manager = [NSClassFromString(@"CCUINightShiftSectionController") performSelector:NSSelectorFromString(@"_defaultFontTight")];

            NSLog(@" ok= %@", manager);

        }

From that file, I got the data for _defaultFontTight to print in the NSLog just fine, but what I'm struggling with is how do I get the instance functions? More specifically, everything below that start with a -  symbol. I can only get info from a +
 symbol.

If I were to switch out _defaultFontTight with enabled then I get the following:

2017-07-02 18:09:35.382109-0400 Testing[809:96270] +[CCUINightShiftSectionController enabled]: unrecognized selector sent to class 0x1b7d5e420

Any help would be greatly appreciated!

EDIT:

I tried this code below:

id myInstance =[NSClassFromString(@"CCUINightShiftSectionController") new];
[myInstance performSelector:NSSelectorFromString(@"enabled")];

For some frameworks, it gets the instance variable values sucessfully, while for most it just returns null or errors such as [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""

Body:
Please note that you are using private frameworks (not documented), and the header file that you are referencing to it, is corresponding to iOS 10.2, so make sure to make your tests on a real iPhone running the same iOS version.

For your calls, try to make them like this:

id myInstance = [NSClassFromString(@"CCUINightShiftSectionController") new];
if ([myInstance respondsToSelector:@selector(someInstanceMethod)]) {
    [myInstance performSelector:@selector(someInstanceMethod)];
}

Also i note that "CCUINightShiftSectionController" is looking to be a "UIViewController" subclass, and it will not be well initialized using the "new" initializer, so you may have null or wrong results.

Good luck to make it working.


问:
How can I search an XML file and output the results to data grid for editing?
This can be done by using SQL, however I would like to use an XML file to have that ease for the user. I can make it display the data in the data-grid-view normally, but I'm not sure how to search for it as you normally would in an SQL database.

All I need to do is allow the person to search for a name, information or the day visited to put the data in the data-grid-view.

Following is my XML code:

```<code><root>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>10</Dayvisited>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
  </place>
</root>
</code>```

this is how i made it load in to a grid so far

```<code>ds.ReadXml("Database.xml");
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Rows[0].Visible = false;
</code>```

im new at using xml files so any help is appreciated.

答:
Let's simplfy the task by keeping the data in only one DataGridView and hiding those rows that don't match the search string.

Since you already have loaded the XML into a DataTable and bound a DataGridView to it we don't really need to search in the XML data..

The way to go for data-bound DGVs is to set a Filter on the DataSource. For this we need to insert a DataView between the DGV and the DataTable.

Let's start by filling a ComboBox with the DataTable's Columns:

```<code>combo_fields.Items.AddRange(ds.Tables[0].Columns.Cast<DataColumn>()
                                .Select(x => x.ColumnName).ToArray());
combo_fields.SelectedIndex = 1;  // start with the Location field
</code>```

Next we add a TextBox where we enter the search text:

```<code>private void tb_filter_TextChanged(object sender, EventArgs e)
{
    string filter = "";
    if (tb_filter.Text != "")
        filter = combo_fields.Text + " LIKE '*" + tb_filter.Text + "*'";

    DataView dv = new DataView(ds.Tables[0]);
    dv.RowFilter = filter;
    dataGridView1.DataSource = dv;
}
</code>```

That is really all we need. Of course you can easily change the condition from a 'like' to a full match..

You could also search in the XML data and hide rows from the DGV, but it won't get any simpler than the above code, just a little closer to your original question..

Here is how to search an XDocument xDoc:

```<code>var found = xDoc.Descendants(combo_fields.Text)
                .Where(x => x.Value.Contains( tb_filter.Text))
                .Select(x => x.Value).ToList();
</code>```

Now you can use the list of strings to decide which rows we will hide:

```<code>dataGridView1.CurrentCell = null;  // necessary, so we don't try to hide the current row

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[combo_fields.Text].Value != null)
        row.Visible = found.Contains(row.Cells["Location"].Value.ToString());
}
</code>```

After  we are done we can clear the filter TextBox to bring up all rows and and we can save the data..:

```<code>tb_filter.Text = "";

ds.Tables[0].WriteXml(someFileName);
</code>```

Body:
This can be done by using SQL, however I would like to use an XML file to have that ease for the user. I can make it display the data in the data-grid-view normally, but I'm not sure how to search for it as you normally would in an SQL database.

All I need to do is allow the person to search for a name, information or the day visited to put the data in the data-grid-view.

Following is my XML code:

<root>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>10</Dayvisited>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
  </place>
</root>

this is how i made it load in to a grid so far

ds.ReadXml("Database.xml");
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Rows[0].Visible = false;

im new at using xml files so any help is appreciated.

Body:
Let's simplfy the task by keeping the data in only one DataGridView and hiding those rows that don't match the search string.

Since you already have loaded the XML into a DataTable and bound a DataGridView to it we don't really need to search in the XML data..

The way to go for data-bound DGVs is to set a Filter on the DataSource. For this we need to insert a DataView between the DGV and the DataTable.

Let's start by filling a ComboBox with the DataTable's Columns:

combo_fields.Items.AddRange(ds.Tables[0].Columns.Cast<DataColumn>()
                                .Select(x => x.ColumnName).ToArray());
combo_fields.SelectedIndex = 1;  // start with the Location field

Next we add a TextBox where we enter the search text:

private void tb_filter_TextChanged(object sender, EventArgs e)
{
    string filter = "";
    if (tb_filter.Text != "")
        filter = combo_fields.Text + " LIKE '*" + tb_filter.Text + "*'";

    DataView dv = new DataView(ds.Tables[0]);
    dv.RowFilter = filter;
    dataGridView1.DataSource = dv;
}

That is really all we need. Of course you can easily change the condition from a 'like' to a full match..

You could also search in the XML data and hide rows from the DGV, but it won't get any simpler than the above code, just a little closer to your original question..

Here is how to search an XDocument xDoc:

var found = xDoc.Descendants(combo_fields.Text)
                .Where(x => x.Value.Contains( tb_filter.Text))
                .Select(x => x.Value).ToList();

Now you can use the list of strings to decide which rows we will hide:

dataGridView1.CurrentCell = null;  // necessary, so we don't try to hide the current row

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[combo_fields.Text].Value != null)
        row.Visible = found.Contains(row.Cells["Location"].Value.ToString());
}

After  we are done we can clear the filter TextBox to bring up all rows and and we can save the data..:

tb_filter.Text = "";

ds.Tables[0].WriteXml(someFileName);


问:
What, exactly, is memcmp supposed to return?
I would like to know what the function memcmp must return.

I've been searching on the Internet, and usually, memcmp definitions state something like the following:

The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

It is never explicitly said what, exactly, is returned: is it the difference between two byte values, or is it -1, 0 or 1? I am confused:

When testing the function memcmp in a little program, it returns -1, 0 or 1, even when the difference between the two bytes evaluated is higher than 1 or lower than -1.

When looking at functions named memcmp on the Internet, they almost all return the difference between 2 bytes, as an int, instead of returning either -1, 0 or 1.

Since I can't get a precise enough definition of the function memcmp, I ask this question here: what, exactly, is the function memcmp supposed to return? Is there an "official" source code somewhere? (I have seen a lot of source codes for memcmp but none gave me an answer: I then suppose that they are not the function that is written in the library string.h, at least not on my computer...)

答:
As @EugeneSh said, it is not defined.  The POSIX specification says, in addition to the portion you quoted:

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the objects being compared.

Therefore, only zero/nonzero and positive/negative are meaningful tests to apply to the return value from memcmp.  Don't rely on the actual values, since they may differ between different C libraries (or maybe even processor architectures).

Source example

I found a mirror of the GNU C library (glibc) that someone has put on GitHub.  The source for memcmp takes the difference between the two bytes (line 332), so the return value will generally not be only -1 or +1.  However, a particular library may implement memcmp however makes the most sense for the target platform.


问:
Redis consumes max memory on large DEL & HMSET function
Issue: After expected clear and rebuild of specific redis keys, worker dynos doesn't allocate memory (until restart of dyno).

I am experience an issue where my Heroku worker-dynos are hitting 95%-100% max memory usage during a delete and rebuild on about 4000 keys. I have a scheduled rebuild that starts every day at 4:00am. Based on logs I assume the DEL of the keys + the rebuild of keys take about ~1490 seconds.

```<code>Jun 29 04:01:41 app app/worker.2: 4 TID-...io8w RedisWorker JID-...cd2a7 INFO: start
Jun 29 04:06:28 app app/worker.1: 4 TID-...mtks RedisWorker JID-...bf170 INFO: start
Jun 29 04:26:32 app app/worker.1: 4 TID-...mtks RedisWorker JID-...bf170 INFO: done: 1203.71 sec
Jun 29 04:26:33 app app/worker.2: 4 TID-...io8w RedisWorker JID-...cd2a7 INFO: done: 1490.938 sec
</code>```

The memory will hover max usage until the dyno restarts (which is scheduled) or we deploy. Example image: Heroku Memory Usage

This is a high level what gets triggered at 4am:

```<code>  def full_clear
    RedisWorker.delete_keys("key1*")
    RedisWorker.delete_keys("key2*")
    RedisWorker.delete_keys("key3*")
    self.build
    return true
  end

  def build
    ... rebuilds keys based on models ...
    return true
  end

  def self.delete_keys(regex)
    $redis.scan_each(match: regex) do |key|
      $redis.del(key)
    end
  end
</code>```

What I have researched so far or my thoughts:

After redis DEL is being invoked the memory doesn't allocate?

Could there be a better implementation of finding all keys that match and doing a batch delete?

I am using defaults for puma; would configuring puma+sidekiq to better match our resources help be the best starting action? Deploying Rails Applications with the Puma Web Server. After a restart the memory is only about 30%-40% until the next full-rebuild (even during high usage of hmsets).

I noticed that my ObjectSpace counts is comparably a lot lower after the dyno gets restart/rest of day until next scheduled full_rebuild.

Any thoughts how I can go about trying to figure out whats causing the dynos to hang memory? Seems isloated to side / the worker dynos being used do rebuild Redis.

答:
Solution:

I installed New Relic to see if there was a potential memory bloat. One of our most used function calls was doing a N+1 query. Fixed the N+1 query and watched our 60k call in New Relic drop to ~5K.

GC also wasn't collecting because it wasn't hitting our threshold. Later on there might be potential GC optimization -- but for now we our immediate issue has been resolved.

I also reached out to Heroku for their thoughts and this is what was discussed:

Memory usage on the Dyno will be managed by the Ruby VM, and is likely that you're keep ing too much information in memory during the key rebuild. You should look into freeing memory used to generate the key-values after the data has been added redis.

Spending time fixing your N+1 queries will definitely help!

Body:
Issue: After expected clear and rebuild of specific redis keys, worker dynos doesn't allocate memory (until restart of dyno).

I am experience an issue where my Heroku worker-dynos are hitting 95%-100% max memory usage during a delete and rebuild on about 4000 keys. I have a scheduled rebuild that starts every day at 4:00am. Based on logs I assume the DEL of the keys + the rebuild of keys take about ~1490 seconds.

Jun 29 04:01:41 app app/worker.2: 4 TID-...io8w RedisWorker JID-...cd2a7 INFO: start
Jun 29 04:06:28 app app/worker.1: 4 TID-...mtks RedisWorker JID-...bf170 INFO: start
Jun 29 04:26:32 app app/worker.1: 4 TID-...mtks RedisWorker JID-...bf170 INFO: done: 1203.71 sec
Jun 29 04:26:33 app app/worker.2: 4 TID-...io8w RedisWorker JID-...cd2a7 INFO: done: 1490.938 sec

The memory will hover max usage until the dyno restarts (which is scheduled) or we deploy. Example image: Heroku Memory Usage

This is a high level what gets triggered at 4am:

  def full_clear
    RedisWorker.delete_keys("key1*")
    RedisWorker.delete_keys("key2*")
    RedisWorker.delete_keys("key3*")
    self.build
    return true
  end

  def build
    ... rebuilds keys based on models ...
    return true
  end

  def self.delete_keys(regex)
    $redis.scan_each(match: regex) do |key|
      $redis.del(key)
    end
  end

What I have researched so far or my thoughts:

After redis DEL is being invoked the memory doesn't allocate?

Could there be a better implementation of finding all keys that match and doing a batch delete?

I am using defaults for puma; would configuring puma+sidekiq to better match our resources help be the best starting action? Deploying Rails Applications with the Puma Web Server. After a restart the memory is only about 30%-40% until the next full-rebuild (even during high usage of hmsets).

I noticed that my ObjectSpace counts is comparably a lot lower after the dyno gets restart/rest of day until next scheduled full_rebuild.

Any thoughts how I can go about trying to figure out whats causing the dynos to hang memory? Seems isloated to side / the worker dynos being used do rebuild Redis.


问:
std::enable_if predicated on std::is_convertible not deducing template correctly
I have the following code:

```<code>#include <iostream>
#include <type_traits>

template <typename T, typename std::enable_if
                                 <std::is_convertible<int, T>::value, T>::type>
void func(T a)
{
    std::cout << a << std::endl;
}

template <typename T, typename std::enable_if
                                 <!std::is_convertible<int, T>::value, T>::type>
void func(T a)
{
    a.print();
}

class Test
{
public:
    void print()
    {
        std::cout << "Test" << std::endl;
    }
};

int main()
{
    func(3);
    func("Test");
    return 0;
}
</code>```

With this code, I expected the first call to func to print out 3 (as int is indeed convertible to int, the first specialization should be called) and the second call to func to print out Test (Test() is not convertible to int, so the second specialization should be called). However, I instead get a compiler error:

prog.cpp: In function ‘int main()’:

prog.cpp:27:8: error: no matching function for call to ‘func(int)’

prog.cpp:5:6: note: candidate: template [class T, typename std::enable_if[std::is_convertible[int, T>::value, T>::type  > void func(T)

prog.cpp:5:6: note: template argument deduction/substitution failed:

prog.cpp:27:8: note: couldn't deduce template parameter ‘[anonymous>’

If, however, I change the templated functions to instead be (while leaving everything else exactly the same):

```<code>template <typename T, typename std::enable_if
                                 <std::is_convertible<int, T>::value, T>::type* =
                                  nullptr>
void func(T a)
{
    std::cout << a << std::endl;
}

template <typename T, typename std::enable_if
                                 <!std::is_convertible<int, T>::value, T>::type* =
                                  nullptr>
void func(T a)
{
    a.print();
}
</code>```

then everything compiles and works as I expected. What is this extra syntax doing and why do I need it?

答:
```<code>template<typename T, typename std::enable_if<std::is_convertible<int, T>::value, T>::type>
</code>```

if we were to remove the noise, would become

```<code>template<typename T, typename Something<T>::type>
</code>```

which is declaring as its second parameter a non-type parameter, the typename here is specifying the nested type is a name of a type. See here for more information.

In the first case, the second parameter is non-type, so the function call func(3) doesn't fit the template which is expecting func<int, some_int>(3).

Body:
I have the following code:

#include <iostream>
#include <type_traits>

template <typename T, typename std::enable_if
                                 <std::is_convertible<int, T>::value, T>::type>
void func(T a)
{
    std::cout << a << std::endl;
}

template <typename T, typename std::enable_if
                                 <!std::is_convertible<int, T>::value, T>::type>
void func(T a)
{
    a.print();
}

class Test
{
public:
    void print()
    {
        std::cout << "Test" << std::endl;
    }
};

int main()
{
    func(3);
    func("Test");
    return 0;
}

With this code, I expected the first call to func to print out 3 (as int is indeed convertible to int, the first specialization should be called) and the second call to func to print out Test (Test() is not convertible to int, so the second specialization should be called). However, I instead get a compiler error:

prog.cpp: In function ‘int main()’:

prog.cpp:27:8: error: no matching function for call to ‘func(int)’

prog.cpp:5:6: note: candidate: template [class T, typename std::enable_if[std::is_convertible[int, T>::value, T>::type  > void func(T)

prog.cpp:5:6: note: template argument deduction/substitution failed:

prog.cpp:27:8: note: couldn't deduce template parameter ‘[anonymous>’

If, however, I change the templated functions to instead be (while leaving everything else exactly the same):

template <typename T, typename std::enable_if
                                 <std::is_convertible<int, T>::value, T>::type* =
                                  nullptr>
void func(T a)
{
    std::cout << a << std::endl;
}

template <typename T, typename std::enable_if
                                 <!std::is_convertible<int, T>::value, T>::type* =
                                  nullptr>
void func(T a)
{
    a.print();
}

then everything compiles and works as I expected. What is this extra syntax doing and why do I need it?

Body:
template<typename T, typename std::enable_if<std::is_convertible<int, T>::value, T>::type>

if we were to remove the noise, would become

template<typename T, typename Something<T>::type>

which is declaring as its second parameter a non-type parameter, the typename here is specifying the nested type is a name of a type. See here for more information.

In the first case, the second parameter is non-type, so the function call func(3) doesn't fit the template which is expecting func<int, some_int>(3).


问:
Ubuntu Java JDK artifact is missing
Using Ubuntu 16.10 and JDK 1.8.0 I'm getting this while a maven build (3.3.9):

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check (check) on project parent: Execution check of goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check failed: Plugin org.apache.maven.plugins:maven-checkstyle-plugin:2.17 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.8.0 at specified path /usr/lib/jvm/java-8-openjdk-amd64/jre/../lib/tools.jar -> [Help 1]
</code>```

JAVA_HOME is set to this path. What might cause that?

答:
Maybe this caused by environement variable, try this:

```<code>export JAVA_HOME =/~.../dirictoryOfYourJDK
export M2_HOME =/~.../dirictoryOfYourMaven
export PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin
</code>```

i hope that help you

Title: Ubuntu Java JDK artifact is missing

Body:
Using Ubuntu 16.10 and JDK 1.8.0 I'm getting this while a maven build (3.3.9):

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check (check) on project parent: Execution check of goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check failed: Plugin org.apache.maven.plugins:maven-checkstyle-plugin:2.17 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.8.0 at specified path /usr/lib/jvm/java-8-openjdk-amd64/jre/../lib/tools.jar -> [Help 1]

JAVA_HOME is set to this path. What might cause that?

Body:
Maybe this caused by environement variable, try this:

export JAVA_HOME =/~.../dirictoryOfYourJDK
export M2_HOME =/~.../dirictoryOfYourMaven
export PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin

i hope that help you


问:
overwrite in the middle of a File
The Problem is I am in the Middle of a File with fseek Next exists some Bytes of Length m that I want to replace with Bytes of length n. simple write will keep m-n bytes still there. If m > n and if m < n some Bytes (n-m) that I am not willing to change will be overwritten.

I just want to replace a known startPos to endPos Byte Stream with variable length Bytes. What is the Best Solution.

-- EDIT --
Though It can be done by taking a Backup. do there exists any direct solution ?
This is too Messy ? and Kind of Poor Coding.

```<code>o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
    buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
    buffer += fgetc(o)
}
fwrite(b, buffer)
</code>```

//now Copy backup to original

答:
Using the fstream library, here is a simple implementation of what the others might be saying

```<code>/**
 * Overwrite a file while replacing certain positions
 */

#include <iostream>
#include <fstream>

using namespace std;

int readFile(char* filename,int& len,char*& result)
{
    ifstream in(filename); // Open the file
    if(!in.is_open())
        return 1;

    // Get file length
    in.seekg(0,ios::end);
    len = (int)in.tellg();
    in.seekg(0,ios::beg);

    // Initialize result
    result = new char[len+1];

    // Read the file and return its value
    in.read(result,len);

    // Close the file
    in.close();

    return 0;
}

void writeFile(char* filename,char* data,int from,int to,int origdata,int trunc)
{
    ofstream out;
    (trunc == 1) ? out.open(filename,ios::trunc) : out.open(filename,ios::app); // Simple ternary statement to figure out what we need to do

    // Find position if we're not starting from the beginning
    if(trunc == 1)
        out.seekp(from);
     else // Otherwise send us to the beginning
        out.seekp(0,ios::beg);

    if(origdata == 1) // If we need to start in the middle of the data, let's do so
        for(int i=0;i<(to-from);++i)
            data[i] = data[from+i]; // Reverse copy

    out.write(data,(to-from));

    out.close();
}

int main()
{
    char* read;
    int len = 0;
    if(readFile("something.txt",len,read) != 0)
    {
        cout<< "An error occurred!" << endl;
        return 0;
    }

    // Example to make this work
    cout<< "Writing new file...\r\n";
    writeFile("something.txt",read,0,20,1,1); // Initial write
    writeFile("something.txt","\r\nsome other mumbo jumbo",21,45,0,0);
    writeFile("something.txt",read,46,100,1,0); // Replace the rest of the file back

    cout<< "Done!\r\n";
    cin.get(); // Pause
    delete [] read;
    return 0;
}
</code>```

You would could do all your seeking in the readFile function OR simply in the char array (in this case read). From there, you can store the positions and use the writeFile() function appropriately.

Good luck!

Dennis M.

Title: overwrite in the middle of a File

Body:
The Problem is I am in the Middle of a File with fseek Next exists some Bytes of Length m that I want to replace with Bytes of length n. simple write will keep m-n bytes still there. If m > n and if m < n some Bytes (n-m) that I am not willing to change will be overwritten.

I just want to replace a known startPos to endPos Byte Stream with variable length Bytes. What is the Best Solution.

-- EDIT --
Though It can be done by taking a Backup. do there exists any direct solution ?
This is too Messy ? and Kind of Poor Coding.

o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
    buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
    buffer += fgetc(o)
}
fwrite(b, buffer)

//now Copy backup to original

Body:
Using the fstream library, here is a simple implementation of what the others might be saying

/**
 * Overwrite a file while replacing certain positions
 */

#include <iostream>
#include <fstream>

using namespace std;

int readFile(char* filename,int& len,char*& result)
{
    ifstream in(filename); // Open the file
    if(!in.is_open())
        return 1;

    // Get file length
    in.seekg(0,ios::end);
    len = (int)in.tellg();
    in.seekg(0,ios::beg);

    // Initialize result
    result = new char[len+1];

    // Read the file and return its value
    in.read(result,len);

    // Close the file
    in.close();

    return 0;
}

void writeFile(char* filename,char* data,int from,int to,int origdata,int trunc)
{
    ofstream out;
    (trunc == 1) ? out.open(filename,ios::trunc) : out.open(filename,ios::app); // Simple ternary statement to figure out what we need to do

    // Find position if we're not starting from the beginning
    if(trunc == 1)
        out.seekp(from);
     else // Otherwise send us to the beginning
        out.seekp(0,ios::beg);

    if(origdata == 1) // If we need to start in the middle of the data, let's do so
        for(int i=0;i<(to-from);++i)
            data[i] = data[from+i]; // Reverse copy

    out.write(data,(to-from));

    out.close();
}

int main()
{
    char* read;
    int len = 0;
    if(readFile("something.txt",len,read) != 0)
    {
        cout<< "An error occurred!" << endl;
        return 0;
    }

    // Example to make this work
    cout<< "Writing new file...\r\n";
    writeFile("something.txt",read,0,20,1,1); // Initial write
    writeFile("something.txt","\r\nsome other mumbo jumbo",21,45,0,0);
    writeFile("something.txt",read,46,100,1,0); // Replace the rest of the file back

    cout<< "Done!\r\n";
    cin.get(); // Pause
    delete [] read;
    return 0;
}

You would could do all your seeking in the readFile function OR simply in the char array (in this case read). From there, you can store the positions and use the writeFile() function appropriately.

Good luck!

Dennis M.


问:
How to do paged queries in RETS?
I am using a java client (jrets) to query a RETS server. This rets server does not support the OFFSET functionality.

The server admin told me to use the MODIFIED field as a way to page through the records. However, I found that this process does not work.

My use case:

The use case is to download all records of a certain type since january of this year. So, I issue a query with a limit of 500 and download records. I go through the data, and get the maximum MODIFIED date. Then I issue another query from that point on.

However I find that the server is not sorting the data by MODIFIED date and returning it. So, data in each batch contains gaps.

Is there a better way to achieve what I want to do?

答:
I am not sure if this is universal but the GAMLS RETS sends responses sorted by L_ListingID.

I can start with

query = "(L_UpdateDate=2017-01-01T11:42:59Z+)"

Then find the largest 'L_ListingID in the response.

Build a new query

query = "(L_UpdateDate=2017-01-01T11:42:59Z+),(L_ListingID=[LARGEST_Listing_ID])"

And keep going until I get an empty response.

Title: How to do paged queries in RETS?


答:
I think isUndefined is a function in underscore.js, which is a dependency of Restangular:

http://underscorejs.org/#isUndefined

Do you have underscore.js included in your assets?

Title: Failed to instantiate module angularApp due to


问:
Why does this function fail when I use this regular expression?
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

```<code>function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}
</code>```

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

```<code>duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3
</code>```

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

```<code>ss,ss,pp
</code>```

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?

答:
Your regex takes the any letter lets say X from you word and back references one letter to check if it was the same or not. You can use this visualizer to understand what it is doing. It counts the occurrences of characters that are immediately followed by the first occurrence.

Link with your query : https://regexper.com/#%2F(.)%5C1%2B%2Fig

Link to the website: https://regexper.com/

Body:
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

ss,ss,pp

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?


问:
Twitter Bootstrap Navbar align not working properly
im generating a bootstrap navbar using codeigniter, its working fine but i want the admin link to be aligned to the right. here is my code:

```<code>    function get_menu ($array, $child = FALSE)
{
    $CI =& get_instance();
    $str = '';

    if (count($array)) {
        $str .= $child == FALSE ? '<ul class="nav navbar-left navbar-custom">' . PHP_EOL : '</ul>' . PHP_EOL;

        foreach ($array as $item) {

            $active = $CI->uri->segment(1) == $item['slug'] ? TRUE : FALSE;
            if (isset($item['children']) && count($item['children'])) {
                $str .= $active ? '<li class="dropdown active">' : '<li class="dropdown">';
                $str .= '<a  class="dropdown-toggle" data-toggle="dropdown" href="' . site_url(e($item['slug'])) . '">' . e($item['title']);
                $str .= '<b class="caret"></b></a>' . PHP_EOL;
                $str .= get_menu($item['children'], TRUE);
            }
            else {
                $str .= $active ? '<li class="active">' : '<li>';
                $str .= '<a href="' . site_url($item['slug']) . '">' . e($item['title']) . '</a>';

            }

                // Closing tags
            $str .= '</li>' ;
        }
                //add dashboard link to the right of menu for login
        $str .= '<li>' . '<p class="navbar-text navbar-right"><a
    `href="admin/dashboard" class="navbar-link"> ADMIN</a></p></li>' . PHP_EOL;

        $str .= '</ul>' . PHP_EOL;
    }
</code>```

im getting a navbar with required links but its all inline. any help is aappreciated. Cheers

答:
This is because of where you are adding the navbar-right class. You have to add it to an ul element. Change your second to last string:

```<code>$str .= '<li>' . '<p class="navbar-text navbar-right"><a `href="admin/dashboard" class="navbar-link"> ADMIN</a></p></li>' . PHP_EOL;
</code>```

To something along these lines:

```<code><ul class="nav navbar-nav navbar-right">
    <li><a href="admin/dashboard" class="navbar-link"> ADMIN</a></li>
</ul>
</code>```

And do not add it inside of your current ul element, that will also not work; you need to close the navbar-left class then add the navbar-right.

Looking something like this:

UPDATE

I think I got it, you do not have the nav element around your navbar, and that is probably what is causing the issues with alignments...

```<code><?php
function get_menu ($array, $child = FALSE)
{
    $CI =& get_instance();
    $str = '';

    if (count($array)) {
        $str .= $child == FALSE ? '<nav class="navbar navbar-default"> <ul class="nav navbar-nav navbar-custom">' . PHP_EOL; // create the <nav> element

        foreach ($array as $item) {

            $active = $CI->uri->segment(1) == $item['slug'] ? TRUE : FALSE;
            if (isset($item['children']) && count($item['children'])) {
                $str .= $active ? '<li class="dropdown active">' : '<li class="dropdown">';
                $str .= '<a  class="dropdown-toggle" data-toggle="dropdown" href="' . site_url(e($item['slug'])) . '">' . e($item['title']);
                $str .= '<b class="caret"></b></a>' . PHP_EOL;
                $str .= get_menu($item['children'], TRUE);
            }
            else {
                $str .= $active ? '<li class="active">' : '<li>';
                $str .= '<a href="' . site_url($item['slug']) . '">' . e($item['title']) . '</a>';

            }

                // Closing tags
            $str .= '</li>' ;
        }

        $str .= '</ul>' . PHP_EOL;

        //add dashboard link to the right of menu for login
        $str .= '<ul class="nav navbar-nav navbar-right">
                    <li><a href="admin/dashboard" class="navbar-link"> ADMIN</a></li>
                </ul>' . PHP_EOL;

        // add the nav closing tag
        $str .= '</nav>' . PHP_EOL;

    }

?>
</code>```

Body:
im generating a bootstrap navbar using codeigniter, its working fine but i want the admin link to be aligned to the right. here is my code:

    function get_menu ($array, $child = FALSE)
{
    $CI =& get_instance();
    $str = '';

    if (count($array)) {
        $str .= $child == FALSE ? '
' . PHP_EOL : '
' . PHP_EOL;

        foreach ($array as $item) {

            $active = $CI->uri->segment(1) == $item['slug'] ? TRUE : FALSE;
            if (isset($item['children']) && count($item['children'])) {
                $str .= $active ? '
' : '
';
                $str .= '' . e($item['title']);
                $str .= '' . PHP_EOL;
                $str .= get_menu($item['children'], TRUE);
            }
            else {
                $str .= $active ? '
' : '
';
                $str .= '' . e($item['title']) . '';

            }

                // Closing tags
            $str .= '
' ;
        }
                //add dashboard link to the right of menu for login
        $str .= '
' . '
 ADMIN

' . PHP_EOL;

        $str .= '
' . PHP_EOL;
    }

im getting a navbar with required links but its all inline. any help is aappreciated. Cheers

Body:
This is because of where you are adding the navbar-right class. You have to add it to an ul element. Change your second to last string:

$str .= '<li>' . '<p class="navbar-text navbar-right"><a `href="admin/dashboard" class="navbar-link"> ADMIN</a></p></li>' . PHP_EOL;

To something along these lines:

<ul class="nav navbar-nav navbar-right">
    <li><a href="admin/dashboard" class="navbar-link"> ADMIN</a></li>
</ul>

And do not add it inside of your current ul element, that will also not work; you need to close the navbar-left class then add the navbar-right.

Looking something like this:

UPDATE

I think I got it, you do not have the nav element around your navbar, and that is probably what is causing the issues with alignments...

<?php
function get_menu ($array, $child = FALSE)
{
    $CI =& get_instance();
    $str = '';

    if (count($array)) {
        $str .= $child == FALSE ? '<nav class="navbar navbar-default"> <ul class="nav navbar-nav navbar-custom">' . PHP_EOL; // create the <nav> element

        foreach ($array as $item) {

            $active = $CI->uri->segment(1) == $item['slug'] ? TRUE : FALSE;
            if (isset($item['children']) && count($item['children'])) {
                $str .= $active ? '<li class="dropdown active">' : '<li class="dropdown">';
                $str .= '<a  class="dropdown-toggle" data-toggle="dropdown" href="' . site_url(e($item['slug'])) . '">' . e($item['title']);
                $str .= '<b class="caret"></b></a>' . PHP_EOL;
                $str .= get_menu($item['children'], TRUE);
            }
            else {
                $str .= $active ? '<li class="active">' : '<li>';
                $str .= '<a href="' . site_url($item['slug']) . '">' . e($item['title']) . '</a>';

            }

                // Closing tags
            $str .= '</li>' ;
        }

        $str .= '</ul>' . PHP_EOL;

        //add dashboard link to the right of menu for login
        $str .= '<ul class="nav navbar-nav navbar-right">
                    <li><a href="admin/dashboard" class="navbar-link"> ADMIN</a></li>
                </ul>' . PHP_EOL;

        // add the nav closing tag
        $str .= '</nav>' . PHP_EOL;

    }

?>


问:
Docker install lvm plugin
Im trying to docker LVM plugin but facing some issues with GO.

```<code> pr@pr-ubuntu:~/ba/docker-lvm-plugin$ go version
go version go1.8.3 linux/amd64
pr@pr-ubuntu:~/ba/docker-lvm-plugin$ make
go-md2man -in man/docker-lvm-plugin.8.md -out docker-lvm-plugin.8
/usr/bin/go build -o docker-lvm-plugin .
make: /usr/bin/go: Command not found
make: *** [lvm-plugin-build] Error 127
</code>```

Here is my GO version.

```<code>pr@pr-ubuntu:~/ba/docker-lvm-plugin$ go version
go version go1.8.3 linux/amd64
</code>```

答: Looks like the makefile has a hard-coded absolute path to the go binary at /usr/bin/go (bad makefile, no biscuit!) - if your binary is not there, create a symlink to it at that location.

Title: Docker install lvm plugin

Body:
Im trying to docker LVM plugin but facing some issues with GO.

 pr@pr-ubuntu:~/ba/docker-lvm-plugin$ go version
go version go1.8.3 linux/amd64
pr@pr-ubuntu:~/ba/docker-lvm-plugin$ make
go-md2man -in man/docker-lvm-plugin.8.md -out docker-lvm-plugin.8
/usr/bin/go build -o docker-lvm-plugin .
make: /usr/bin/go: Command not found
make: *** [lvm-plugin-build] Error 127

Here is my GO version.

pr@pr-ubuntu:~/ba/docker-lvm-plugin$ go version
go version go1.8.3 linux/amd64


问:
PVRTC2 texture compression on iOS
Imagination Technologies released an OpenGL ES 2.0 extension called IMG_texture_compression_pvrtc2 almost five years ago that offers image quality improvements over PVRTC1 compression. A detailed article is found here,

I know that iOS support PVRTC1 compression, and it is listed in extensions on all devices. Does anyone know if Apple supports PVRTC2 or plans to in the near future? Since the extension has been out for so long, Apple recommends PVRTC over other formats, and I assume their hardware already supports, It seems like the should.

Does anyone know of any mobile platform that supports this extension? Any additional information would be helpful.

答:
Does anyone know if Apple supports PVRTC2

Doesn't look like it.

or plans to in the near future?

You'd have to ask Apple.

Does anyone know of any mobile platform that supports this extension?

It's an IMG proprietary extension and texture format, so you'd have to try and find a non-Apple device with a recent high-end IMG GPU.

You'd probably have more luck looking at the ASTC texture format; that one is a multi-vendor extension (and mandatory in OpenGL ES 3.2 so widely supported).

Title: PVRTC2 texture compression on iOS