问:
WPF rendering is too slow
I am experiencing a strange problem trying to use WPF to render a number of polylines (64 polylines about 400-500 vertices in each on a 2300x1024 Canvas).  Polylines are updated every 50ms.

For some reason my application UI becomes very sluggish and almost unresponsive to user input.

I am using to following class to avoid updating the point collection while it is displayed:

```<code>class DoubleBufferPlot
    {
        /// <summary>
        /// Double-buffered point collection
        /// </summary>
        private readonly PointCollection[] mLineBuffer =
        {
            new PointCollection(),
            new PointCollection()
        };

        private int mWorkingBuffer; //index of the workign buffer (buffer being modified)

        #region Properties

        //Polyline displayed
        public Polyline Display { get; private set; }

        /// <summary>
        /// index operator to access points
        /// </summary>
        /// <param name="aIndex">index</param>
        /// <returns>Point at aIndex</returns>
        public Point this[int aIndex]
        {
            get { return mLineBuffer[mWorkingBuffer][aIndex]; }
            set { mLineBuffer[mWorkingBuffer][aIndex] = value; }
        }

        /// <summary>
        /// Number of points in the working buffer
        /// </summary>
        public int WorkingPointCount
        {
            get { return mLineBuffer[mWorkingBuffer].Count; }

            set
            {
                SetCollectionSize(mLineBuffer[mWorkingBuffer], value);
            }
        }
        #endregion

        public DoubleBufferPlot(int numPoints = 0)
        {
            Display = new Polyline {Points = mLineBuffer[1]};

            if (numPoints > 0)
            {
                SetCollectionSize(mLineBuffer[0], numPoints);
                SetCollectionSize(mLineBuffer[1], numPoints);
            }
        }

        /// <summary>
        /// Swap working and display buffer
        /// </summary>
        public void Swap()
        {
            Display.Points = mLineBuffer[mWorkingBuffer];  //display workign buffer

            mWorkingBuffer = (mWorkingBuffer + 1) & 1; //swap

            //adjust buffer size if needed
            if (Display.Points.Count != mLineBuffer[mWorkingBuffer].Count)
            {
                SetCollectionSize(mLineBuffer[mWorkingBuffer], Display.Points.Count);
            }
        }

        private static void SetCollectionSize(IList<Point> collection, int newSize)
        {
            while (collection.Count > newSize)
            {
                collection.RemoveAt(collection.Count - 1);
            }

            while (collection.Count < newSize)
            {
                collection.Add(new Point());
            }
        }
    }
</code>```

I update the working buffer offscreen and then call Swap() to have it displayed.  All 64 polylines (DoubleBufferPlot.Display) are added to a Canvas as children.

I used Visual Studio Concurrency Analyzer tool to see what's going on and discovered that after each update the main thread spends 46ms performing some WPF-related tasks: System.Widnows.ContextLayoutManager.UpdateLayout() and System.Windows.Media.MediaContex.Render().

I also discovered that there is another thread that's running almost non-stop rendering
wpfgfx_v0400.dll!CPartitionThread::ThreadMain
...
wpfgfx_v0400.dll!CDrawingContext::Render
...
etc.

I read a number of articles on WPF including this:  Can WPF render a line path with 300,000 points on it in a performance-sensitive environment?
and also this article http://msdn.microsoft.com/en-us/magazine/dd483292.aspx.

I am (or my company rather) trying to avoid DrawingVisual since the rest of the project uses WPF shapes API.

Any idea why this is so slow?  I even tried disabling anti-aliasing (RenderOptions.SetEdgeMode(mCanvas, EdgeMode.Aliased)) but it did not help very much.

Why does layout update takes so long.  Anyone who is an expert in WPF internals?

Thank you very much.

答:
The fastest way I've found to draw frequently updated geometry is to create a DrawingGroup "backingStore", output that backing store during OnRender(), and then update that backingStore when my data needs to update, by using backingStore.Open(). (see code below)

In my tests, this was more efficient than using WriteableBitmap or RenderTargetBitmap.

If your UI is becoming unresponsive, how are you triggering your redraw every 50ms? Is it possible some of the redraw is taking longer than 50ms and backing up the message-pump with redraw messages? One method to avoid this is to shut off your redraw timer during your redraw loop (or make it a one-shot timer), and only enable it at the end. Another method is to do your redraw during a CompositionTarget.Rendering event, which happens right before the WPF redraw.

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}
</code>```

Title: WPF rendering is too slow

Body:
I am experiencing a strange problem trying to use WPF to render a number of polylines (64 polylines about 400-500 vertices in each on a 2300x1024 Canvas).  Polylines are updated every 50ms.

For some reason my application UI becomes very sluggish and almost unresponsive to user input.

I am using to following class to avoid updating the point collection while it is displayed:

class DoubleBufferPlot
    {
        ///
        /// Double-buffered point collection
        ///
        private readonly PointCollection[] mLineBuffer =
        {
            new PointCollection(),
            new PointCollection()
        };

        private int mWorkingBuffer; //index of the workign buffer (buffer being modified)

        #region Properties

        //Polyline displayed
        public Polyline Display { get; private set; }

        ///
        /// index operator to access points
        ///
        /// <param name="aIndex">index</param>
        /// <returns>Point at aIndex</returns>
        public Point this[int aIndex]
        {
            get { return mLineBuffer[mWorkingBuffer][aIndex]; }
            set { mLineBuffer[mWorkingBuffer][aIndex] = value; }
        }

        ///
        /// Number of points in the working buffer
        ///
        public int WorkingPointCount
        {
            get { return mLineBuffer[mWorkingBuffer].Count; }

            set
            {
                SetCollectionSize(mLineBuffer[mWorkingBuffer], value);
            }
        }
        #endregion

        public DoubleBufferPlot(int numPoints = 0)
        {
            Display = new Polyline {Points = mLineBuffer[1]};

            if (numPoints > 0)
            {
                SetCollectionSize(mLineBuffer[0], numPoints);
                SetCollectionSize(mLineBuffer[1], numPoints);
            }
        }

        ///
        /// Swap working and display buffer
        ///
        public void Swap()
        {
            Display.Points = mLineBuffer[mWorkingBuffer];  //display workign buffer

            mWorkingBuffer = (mWorkingBuffer + 1) & 1; //swap

            //adjust buffer size if needed
            if (Display.Points.Count != mLineBuffer[mWorkingBuffer].Count)
            {
                SetCollectionSize(mLineBuffer[mWorkingBuffer], Display.Points.Count);
            }
        }

        private static void SetCollectionSize(IList<Point> collection, int newSize)
        {
            while (collection.Count > newSize)
            {
                collection.RemoveAt(collection.Count - 1);
            }

            while (collection.Count < newSize)
            {
                collection.Add(new Point());
            }
        }
    }

I update the working buffer offscreen and then call Swap() to have it displayed.  All 64 polylines (DoubleBufferPlot.Display) are added to a Canvas as children.

I used Visual Studio Concurrency Analyzer tool to see what's going on and discovered that after each update the main thread spends 46ms performing some WPF-related tasks: System.Widnows.ContextLayoutManager.UpdateLayout() and System.Windows.Media.MediaContex.Render().

I also discovered that there is another thread that's running almost non-stop rendering
wpfgfx_v0400.dll!CPartitionThread::ThreadMain
...
wpfgfx_v0400.dll!CDrawingContext::Render
...
etc.

I read a number of articles on WPF including this:  Can WPF render a line path with 300,000 points on it in a performance-sensitive environment?
and also this article http://msdn.microsoft.com/en-us/magazine/dd483292.aspx.

I am (or my company rather) trying to avoid DrawingVisual since the rest of the project uses WPF shapes API.

Any idea why this is so slow?  I even tried disabling anti-aliasing (RenderOptions.SetEdgeMode(mCanvas, EdgeMode.Aliased)) but it did not help very much.

Why does layout update takes so long.  Anyone who is an expert in WPF internals?

Thank you very much.

Body:
The fastest way I've found to draw frequently updated geometry is to create a DrawingGroup "backingStore", output that backing store during OnRender(), and then update that backingStore when my data needs to update, by using backingStore.Open(). (see code below)

In my tests, this was more efficient than using WriteableBitmap or RenderTargetBitmap.

If your UI is becoming unresponsive, how are you triggering your redraw every 50ms? Is it possible some of the redraw is taking longer than 50ms and backing up the message-pump with redraw messages? One method to avoid this is to shut off your redraw timer during your redraw loop (or make it a one-shot timer), and only enable it at the end. Another method is to do your redraw during a CompositionTarget.Rendering event, which happens right before the WPF redraw.

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}


来源: stackexchange

问:
What exactly is the zookeeper quorum setting in hbase-site.xml?
What exactly is the zookeeper quorum setting in hbase-site.xml?</p>

答:
As described in hbase-default.xml, here's the setting:

Comma separated list of servers in the ZooKeeper Quorum. For example, "host1.mydomain.com,host2.mydomain.com,host3.mydomain.com". By default this is set to localhost for local and pseudo-distributed modes of operation. For a fully-distributed setup, this should be set to a full list of ZooKeeper quorum servers. If HBASE_MANAGES_ZK is set in hbase-env.sh this is the list of servers which we will start/stop ZooKeeper on.

What this actually does has been answered by Edward J. Yoon here. With editing on my part, for clarity:

The Apache Zookeeper is a coordination service for distributed applications, like Google's Chubby. Many projects uses zookeeper, and we (Apache Hama) also use zookeeper for barrier synchronization of Bulk Synchronous Parallel computing framework.

Today, I surveyed more about the paxos and dynamic quorum features of the Zookeeper project, to better name the class org.apache.hama.zookeeper.QuorumPeer. Because of documentation is not enough ( http://hadoop.apache.org/zookeeper/docs/r3.0.0/api/index.html ), I didn't understand the meaning of "quorum", as this term was somewhat odd to me. But, "org.apache.hama.zookeeper.QuorumPeer" is the proper name!! xD

So, what is the Quorum and why do we need a Quorum?

According to Wikipedia, Quorum is the minimum number of members of a deliberative body necessary to conduct the business of that group. Ordinarily, this is a majority of the people expected to be there, although many bodies may have a lower or higher quorum.

As you know, a Fault-Tolerant mechanism is one of the important functions of distributed system. The Quorum algorithm is used to prevent a split-brain condition. When split-brain condition occurs, according to the Quorum algorithm, zookeeper determines the "Primary Partition" and "Secondary Partition". Then, the servers in primary group receive and process user's request, and the servers in secondary group become read-only.

When does this system recover from a split-brain condition? When they're merged to one partition again. Internally, zookeeper uses atomic broadcast protocol instead of Paxos.

You should also read the original version, in case I mistranslated the concepts he was trying to present.

My understanding of the quorum mechanism in Apache Zookeeper is it explicitly defines a replication quorum across several pre-defined hosts. If this quorum is not met, the partitions that disagree are split off to a secondary partition until Zookeeper can reintegrate them with the primary partition.

This adds more granularity to Hadoop's eventual consistency model. HBase, meanwhile, is currently in the process of further integrating Zookeeper with its code.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
javascript click event :click once trigger twice callback function?
I'm currently building a "simons game", according to the FCC project (here).
  In my first version(not fully functional) demo, I find a weird bug, every time I click buttons(the colored div) once, the callback function "startAnswer" will be called twice, so the game will not be played correctly, here is my code at CodePen.io.
  my code: https://codepen.io/NxDon/pen/eRpRra

here is a note about how my code works:

I create a game object by new GameConstructor(line 99);

I bind callback functions to "start" and "strict" button.

when player click the "start" button, the callback function "startGame"(line 17) will be invoked, It will initialize some parameters, and display the answer for player to repeat;

when the display is over, I click one of the four ring area(which I refer as the button), to match the answer. the ring area has bound its click event with callback function "startAnswer(line 55)" at the game start phase, my intuition is the if I click the ring area once, the callback function will invoke once, instead, the startAnswer was continuously invoked twice. That the part It confuses me. Thanks for your help.

答:
You have more than 1 listener for the button ,

```<code>$(id).off('click');//removes past listeners
$(id).click(function(){
    startAnswer();
});
</code>```

https://codepen.io/smsbhatt/pen/yXYPWW

Body:
You have more than 1 listener for the button ,

$(id).off('click');//removes past listeners
$(id).click(function(){
    startAnswer();
});

https://codepen.io/smsbhatt/pen/yXYPWW


问:
Validate mobile number into 10 digit numbers in php jquery
I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number. </p>

```<code><script type="text/javascript" >
 $(function() {
   $("#phno").bind("keypress", function (event) {
                if (event.charCode != 0) {
                       var regex = new RegExp("^[0-9]{10}$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter valid Student Phone No");
                        event.preventDefault();
                        return false;
                    }
                }
            });
 });
</code>```

答:
You can try this

```<code>var regex = new RegExp("/^[0-9]{1,10}$/");
</code>```

Or try this

```<code>var str='0123456789';
console.log(str.match(/^\d{10}$/)); // retunr null if don't match
</code>```

Body:
You can try this

var regex = new RegExp("/^[0-9]{1,10}$/");

Or try this

var str='0123456789';
console.log(str.match(/^\d{10}$/)); // retunr null if don't match


问:
RSA Encryption using Python
I'm trying to RSA encrypt a word 2 characters at a time padding with a space using Python but not sure how I go about it.

For example if the encryption exponent was 8 and a modulus of 37329 and the word was 'Pound' how would I go about it? I know I need to start with pow(ord('P') and need to take into consideration that the word is 5 characters and I need to do it 2 characters at a time padding with a space. I'm not sure but do I also need to use <<8 somewhere?

Thank you

答:
If you want to efficiently code the RSA encryption using python, my github repository would definitely to understand and interpret the mathematical definitions of RSA in python

Cryptogrphic Algoritms Implementation Using Python

RSA Key Generation

```<code>def keyGen():
    ''' Generate  Keypair '''
    i_p=randint(0,20)
    i_q=randint(0,20)
    # Instead of Asking the user for the prime Number which in case is not feasible,
    # generate two numbers which is much highly secure as it chooses higher primes
    while i_p==i_q:
        continue
    primes=PrimeGen(100)
    p=primes[i_p]
    q=primes[i_q]
    #computing n=p*q as a part of the RSA Algorithm
    n=p*q
    #Computing lamda(n), the Carmichael's totient Function.
    # In this case, the totient function is the LCM(lamda(p),lamda(q))=lamda(p-1,q-1)
    # On the Contrary We can also apply the Euler's totient's Function phi(n)
    #  which sometimes may result larger than expected
    lamda_n=int(lcm(p-1,q-1))
    e=randint(1,lamda_n)
    #checking the Following : whether e and lamda(n) are co-prime
    while math.gcd(e,lamda_n)!=1:
        e=randint(1,lamda_n)
    #Determine the modular Multiplicative Inverse
    d=modinv(e,lamda_n)
    #return the Key Pairs
    # Public Key pair : (e,n), private key pair:(d,n)
    return ((e,n),(d,n))
</code>```

Title: RSA Encryption using Python

Body:
If you want to efficiently code the RSA encryption using python, my github repository would definitely to understand and interpret the mathematical definitions of RSA in python

Cryptogrphic Algoritms Implementation Using Python

RSA Key Generation

def keyGen():
    ''' Generate  Keypair '''
    i_p=randint(0,20)
    i_q=randint(0,20)
    # Instead of Asking the user for the prime Number which in case is not feasible,
    # generate two numbers which is much highly secure as it chooses higher primes
    while i_p==i_q:
        continue
    primes=PrimeGen(100)
    p=primes[i_p]
    q=primes[i_q]
    #computing n=p*q as a part of the RSA Algorithm
    n=p*q
    #Computing lamda(n), the Carmichael's totient Function.
    # In this case, the totient function is the LCM(lamda(p),lamda(q))=lamda(p-1,q-1)
    # On the Contrary We can also apply the Euler's totient's Function phi(n)
    #  which sometimes may result larger than expected
    lamda_n=int(lcm(p-1,q-1))
    e=randint(1,lamda_n)
    #checking the Following : whether e and lamda(n) are co-prime
    while math.gcd(e,lamda_n)!=1:
        e=randint(1,lamda_n)
    #Determine the modular Multiplicative Inverse
    d=modinv(e,lamda_n)
    #return the Key Pairs
    # Public Key pair : (e,n), private key pair:(d,n)
    return ((e,n),(d,n))

ContentLicense: CC BY-SA 4.0


问:
Error on integrating of Ionic2 Auth service
I'm trying to integrate facebook login to my ionic 2 app. I was following the guide here and all is good until I stared to using Auth and User in the constructor.

The problem is , currently when i use  public auth: Auth, public user: User in my constructor then it give issue

Uncaught Error: Cannot find module "ionic-native"

Following is my full code

import { Component } from '@angular/core';
import { Auth, User } from '@ionic/cloud-angular';
@Component({
  selector: 'social-auth',
  templateUrl: 'social.html',
})
export class SocialAuth {
  constructor(public auth: Auth, public user: User) {
  }
  openTwitter(){
    this.auth.login('twitter').then((data) => {
     console.log(data);
    });
  }
}
```

<p>My package json is </p>

<pre class="lang-js prettyprint-override"><code>{
  "name": "ionic-app-base",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build --rollup ./config/rollup.config.js",
    "minify": "ionic-app-scripts minify --cleancss ./config/cleancss.config.js",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.0",
    "@angular/compiler": "4.0.0",
    "@angular/compiler-cli": "4.0.0",
    "@angular/core": "4.0.0",
    "@angular/forms": "4.0.0",
    "@angular/http": "4.0.0",
    "@angular/platform-browser": "4.0.0",
    "@angular/platform-browser-dynamic": "4.0.0",
    "@ionic-native/camera": "^3.10.3",
    "@ionic-native/core": "^3.6.1",
    "@ionic-native/device": "^3.6.1",
    "@ionic-native/file": "^3.6.1",
    "@ionic-native/file-path": "^3.6.1",
    "@ionic-native/geolocation": "^3.6.1",
    "@ionic-native/in-app-browser": "^3.12.1",
    "@ionic-native/paypal": "^3.10.2",
    "@ionic-native/sim": "^3.5.0",
    "@ionic-native/social-sharing": "^3.10.3",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic-native/toast": "^3.6.1",
    "@ionic-native/transfer": "^3.6.1",
    "@ionic/cloud-angular": "^0.12.0",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.0.1",
    "ionic-debug-console": "^0.1.0",
    "ionic-native": "^3.5.0",
    "ionicons": "3.0.0",
    "moment": "^2.18.1",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "@ionic/cli-plugin-ionic-angular": "1.1.2",
    "typescript": "~2.2.1"
  }
}
</code>```

and when I am installing ionic clound then this is i am getting :-

答:
You have an  invalid package in your package.json.

```<code>"ionic-native": "^3.5.0",
</code>```

From version 3.x,
ionic-native is split into @ionic-native/core and @ionic-native/package_name.So ionic-native 3.x does not exist.

Remove the "ionic-native": "^3.5.0", entry from your package.json.

Clear node_modules folder and run npm install

Also as mentioned in my comment:
you dont need to set Auth as provider again..It will be taken care of by the Cloud module

Body:
I'm trying to integrate facebook login to my ionic 2 app. I was following the guide here and all is good until I stared to using Auth and User in the constructor.

The problem is , currently when i use  public auth: Auth, public user: User in my constructor then it give issue

Uncaught Error: Cannot find module "ionic-native"

Following is my full code

import { Component } from '@angular/core';
import { Auth, User } from '@ionic/cloud-angular';
@Component({
  selector: 'social-auth',
  templateUrl: 'social.html',
})
export class SocialAuth {
  constructor(public auth: Auth, public user: User) {
  }
  openTwitter(){
    this.auth.login('twitter').then((data) => {
     console.log(data);
    });
  }
}

My package json is

{
  "name": "ionic-app-base",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build --rollup ./config/rollup.config.js",
    "minify": "ionic-app-scripts minify --cleancss ./config/cleancss.config.js",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.0",
    "@angular/compiler": "4.0.0",
    "@angular/compiler-cli": "4.0.0",
    "@angular/core": "4.0.0",
    "@angular/forms": "4.0.0",
    "@angular/http": "4.0.0",
    "@angular/platform-browser": "4.0.0",
    "@angular/platform-browser-dynamic": "4.0.0",
    "@ionic-native/camera": "^3.10.3",
    "@ionic-native/core": "^3.6.1",
    "@ionic-native/device": "^3.6.1",
    "@ionic-native/file": "^3.6.1",
    "@ionic-native/file-path": "^3.6.1",
    "@ionic-native/geolocation": "^3.6.1",
    "@ionic-native/in-app-browser": "^3.12.1",
    "@ionic-native/paypal": "^3.10.2",
    "@ionic-native/sim": "^3.5.0",
    "@ionic-native/social-sharing": "^3.10.3",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic-native/toast": "^3.6.1",
    "@ionic-native/transfer": "^3.6.1",
    "@ionic/cloud-angular": "^0.12.0",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.0.1",
    "ionic-debug-console": "^0.1.0",
    "ionic-native": "^3.5.0",
    "ionicons": "3.0.0",
    "moment": "^2.18.1",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "@ionic/cli-plugin-ionic-angular": "1.1.2",
    "typescript": "~2.2.1"
  }
}

and when I am installing ionic clound then this is i am getting :-

Body:
You have an  invalid package in your package.json.

"ionic-native": "^3.5.0",

From version 3.x,
ionic-native is split into @ionic-native/core and @ionic-native/package_name.So ionic-native 3.x does not exist.

Remove the "ionic-native": "^3.5.0", entry from your package.json.

Clear node_modules folder and run npm install

Also as mentioned in my comment:
you dont need to set Auth as provider again..It will be taken care of by the Cloud module


问:
Handling cancellation of LinkedIn app download dialog in android
I am using the LinkedIn SDK in my android app, which requires the LinkedIn app to be installed in the device. When the LinkedIn app is not installed in the device, it shows a dialog asking to download the app.

So far I have not found a way to detect if the dialog has been cancelled, from the app. Digging down I've found that the dialog is shown by a LinkedIn SDK class called AppStore in com.linkedin.platform.internals

Please advice.

答:
There is no official way to find out if the dialogue was canceled, but we can use our own custom implementation to check if the app is installed or not and then proceed with the login process I am doing it using the below code

```<code>@Override
public void onResume() {
    super.onResume();

    //check if the linkdin is installed or not
    if (linkedInInstalled()) {//if the linkedin is installed then proceed with login
        login_linkedin();
    } else {//else do not login ask user to download the app
        showLinkdingInstallPopup();
    }
}

private boolean linkedInInstalled() {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo("com.linkedin.android", PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
</code>```

if the LinkedIn app is installed then proceed with normal login process and if not then show a message to the user to install the linked in

```<code>private void showLinkdingInstallPopup() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Linkedin is not installed on you device please install it to proceed with linkedin synch");
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();

            try {
                Intent viewIntent =
                        new Intent("android.intent.action.VIEW",
                                Uri.parse("https://play.google.com/store/apps/details?id=com.linkedin.android&hl=en"));
                startActivity(viewIntent);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Unable to connect try after some time...",
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

        }
    });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //handle the dialog cancelled logic
            dialogInterface.dismiss();
            finish();
        }
    });

    AlertDialog dialog = builder.create();
    dialog.show();

}
</code>```

Body:
There is no official way to find out if the dialogue was canceled, but we can use our own custom implementation to check if the app is installed or not and then proceed with the login process I am doing it using the below code

@Override
public void onResume() {
    super.onResume();

    //check if the linkdin is installed or not
    if (linkedInInstalled()) {//if the linkedin is installed then proceed with login
        login_linkedin();
    } else {//else do not login ask user to download the app
        showLinkdingInstallPopup();
    }
}

private boolean linkedInInstalled() {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo("com.linkedin.android", PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

if the LinkedIn app is installed then proceed with normal login process and if not then show a message to the user to install the linked in

private void showLinkdingInstallPopup() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Linkedin is not installed on you device please install it to proceed with linkedin synch");
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();

            try {
                Intent viewIntent =
                        new Intent("android.intent.action.VIEW",
                                Uri.parse("https://play.google.com/store/apps/details?id=com.linkedin.android&hl=en"));
                startActivity(viewIntent);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Unable to connect try after some time...",
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

        }
    });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //handle the dialog cancelled logic
            dialogInterface.dismiss();
            finish();
        }
    });

    AlertDialog dialog = builder.create();
    dialog.show();

}


问:
Convert Column from String to Int - Alter Script MSSQL
Can you change a column from a varchar to an int.

I have a table with a zipcode column and I want the zips to be ints instead of varchars.

答:
Actually, I suggest you do NOT make that change at all.  You are in a better position for future growth if you can support the alphanumeric ZIPs outside of the US, and to do that your ZIP code column should remain a varchar.

For instance, just 2 minutes ago, I received an order from:

```<code>Hever, Belgium
VLA3191
</code>```

Body:
Actually, I suggest you do NOT make that change at all.  You are in a better position for future growth if you can support the alphanumeric ZIPs outside of the US, and to do that your ZIP code column should remain a varchar.

For instance, just 2 minutes ago, I received an order from:

Hever, Belgium
VLA3191


问:
iOS Different result about calculating text size between boundingRectWithSize and CoreText method
Same single line of text get different width between boundingRectWithSize andCoreText` method.

Here is my code and results:

```<code>- (IBAction)buttonSeletor:(id)sender {
    [self getSeparatedLinesWithText:self.contentField.text fontSize:self.fontField.text.floatValue labelWidth:10000];
}

- (void)getSeparatedLinesWithText:(NSString *)text fontSize:(CGFloat)fontSize labelWidth:(CGFloat)labelWidth
{
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    CTParagraphStyleSetting set[kCTParagraphStyleSpecifierCount] = { 0 };
    int count = 0;
    CTLineBreakMode paraLineBreak = (CTLineBreakMode)NSLineBreakByCharWrapping;
    set[count].spec = kCTParagraphStyleSpecifierLineBreakMode;
    set[count].valueSize = sizeof(CTLineBreakMode);
    set[count].value = &paraLineBreak;
    count++;
    CTParagraphStyleRef style = CTParagraphStyleCreate(set, count);

    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:(NSString *)kCTParagraphStyleAttributeName value:(__bridge id)style range:NSMakeRange(0, attStr.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);

    CGFloat width = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :font} context:nil].size.width;
    CTLineRef obj = (__bridge CTLineRef)(lines[0]);
    CGRect r = CTLineGetBoundsWithOptions(obj, kCTLineBoundsExcludeTypographicLeading);
    NSLog(@"\ntext %@\nboundingRectWithSize %f\nCoreText %f\nboundingRectWithSize/CoreText %f",text,width,r.size.width,width/r.size.width);
}
</code>```

Result:

Design sketch:

答:
If you want to display maximum three lines in label then you not need to calculate width etc. You can manage it from your interface (storyboard or xib) by autolayout.

give your label have three constraint like : leading,trailing,top and set number of line to 3 ! if you have fixed width label then set constraints like : top,leading, fixed width and number of line should be three!

and it will resize according to content and will not show more than three lines!

Body:
Same single line of text get different width between boundingRectWithSize andCoreText` method.

Here is my code and results:

- (IBAction)buttonSeletor:(id)sender {
    [self getSeparatedLinesWithText:self.contentField.text fontSize:self.fontField.text.floatValue labelWidth:10000];
}

- (void)getSeparatedLinesWithText:(NSString *)text fontSize:(CGFloat)fontSize labelWidth:(CGFloat)labelWidth
{
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    CTParagraphStyleSetting set[kCTParagraphStyleSpecifierCount] = { 0 };
    int count = 0;
    CTLineBreakMode paraLineBreak = (CTLineBreakMode)NSLineBreakByCharWrapping;
    set[count].spec = kCTParagraphStyleSpecifierLineBreakMode;
    set[count].valueSize = sizeof(CTLineBreakMode);
    set[count].value = &paraLineBreak;
    count++;
    CTParagraphStyleRef style = CTParagraphStyleCreate(set, count);

    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:(NSString *)kCTParagraphStyleAttributeName value:(__bridge id)style range:NSMakeRange(0, attStr.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);

    CGFloat width = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :font} context:nil].size.width;
    CTLineRef obj = (__bridge CTLineRef)(lines[0]);
    CGRect r = CTLineGetBoundsWithOptions(obj, kCTLineBoundsExcludeTypographicLeading);
    NSLog(@"\ntext %@\nboundingRectWithSize %f\nCoreText %f\nboundingRectWithSize/CoreText %f",text,width,r.size.width,width/r.size.width);
}

Result:

Design sketch:


问:
how to refer to the id in jquery
I am trying to delete row by calling rest web service using jquery. in the url field i have to mention the id dyanmically in jquery . this is my code

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>

    <form id = "add">
        <h1>Add Employee</h1><br>
        <table>
        <tr><td>Id : </td><td><input type="text" id="empId" disabled="true" readonly = "true" /></td></tr>
        <tr><td>Name : </td><td><input type="text" id="name" /></td></tr>
        <tr><td>Age : </td><td><input type="text" id="age" /></td></tr>
        <tr><td>Salary : </td><td><input type="text" id="salary" /></td></tr>
        <tr><td>Address : </td><td><input type="text" id="address" /></td></tr>
        <tr><td><input type = "submit" value = "submit" ></td></tr>
        </table></form>
        <form id=  "list">
        <h1>Employee List</h1>
        <table  id= "content" border= "0">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Age</th>
                <th>Salary</th>
                <th>Address</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody id = "emp">
        </tbody>
        </table>
    </form>
    <script>

    $(document).ready(function(){

        listEmployee();
        addEmployee();
        deleteEmployee();
    });

    function listEmployee(){

        $.ajax({

            url: '/Ram/rest/restemployees',
            type: 'GET',
            dataType: 'JSON',
            success: function(data){

                $.each(data, function(i,value){
                    $("#content tbody").append("<tr>" + "<td>" + value.id + "</td>" +
                            "<td>" + value.name + "</td>" +
                            "<td>" + value.age + "</td>" +
                            "<td>" + value.salary + "</td>" +
                            "<td>" + value.address + "</td>" +
                            "<td>" + "<button onClick='deleteEmployee()'>Edit</button" + "</td>" +
                            "<td>" + "<button id='btnDel'>Delete</button>" +"</tr>")
                });

            },
            error: function(data){

            }

        });
    }

    function addEmployee(){

        $("#add").submit(function(e){

            var employee  = new Object();
            employee.name = $("#name").val();
            employee.age = $("#age").val();
            employee.salary = $("#salary").val();
            employee.address = $("#address").val();
            e.preventDefault();
            $.ajax({

                url : "/Ram/rest/add",
                type : "POST",
                data : employee,
                success : function(data){
                    location.reload(true);
                },
                error : function(data){

                }

            });
        });

    }

    function deleteEmployee(){

        var employee = new Object();
        employee.id = $("#empId").val();
        var id = $("#empId").val();
            $.ajax({

                url : "/Ram/rest/delete/" + id  ,
                type : "GET",
                data: employee,
                success: function(data){
                    alert("2");
                    location.reload(true);
                },
                error : function(data){

                }
            });

    }

    </script>
</body>

</html>
</code>```

but the url is not accepting id value. how can i pass the url value dynamically?

答:
You need to remove Data and then try it will work check below code :
And URL is not correct URL should be : "url : "/Ram/rest/delete?id=" + id  ,"

function deleteEmployee(){

        //var employee = new Object();

        var id = $("#empId").val();
            $.ajax({

                url : "/Ram/rest/delete?id=" + id  ,
                type : "GET",
                dataType: "html",
                data: 'json',
                cache: false,
                //data: employee,
                success: function(data){
                    alert("2");
                    location.reload(true);
                },
                error : function(data){

                }
            });

    }
```

<p><strong>Second Possible way :</strong></p>

<pre class="lang-js prettyprint-override"><code>var employee = {
            "id": $("#empId").val()
        }

        $.ajax({

            url: "/Ram/rest/delete/",
            type: "GET",
            dataType: "html",
            data: 'json',
            cache: false,
            contentType: "application/json;",
            data: JSON.stringify(employee),
            success: function (data) {
                alert("2");
                location.reload(true);
            },
            error: function (data) {

            }
        });
</code>```

Title: how to refer to the id in jquery

Body:
I am trying to delete row by calling rest web service using jquery. in the url field i have to mention the id dyanmically in jquery . this is my code

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>

    <form id = "add">

Add Employee

Id : 	<input type="text" id="empId" disabled="true" readonly = "true" />

Name : 	<input type="text" id="name" />

Age : 	<input type="text" id="age" />

Salary : 	<input type="text" id="salary" />

Address : 	<input type="text" id="address" />

<input type = "submit" value = "submit" >

</form>
        <form id=  "list">

Employee List

                Id
                Name
                Age
                Salary
                Address
                Edit
                Delete

    </form>

but the url is not accepting id value. how can i pass the url value dynamically?

Body:
You need to remove Data and then try it will work check below code :
And URL is not correct URL should be : "url : "/Ram/rest/delete?id=" + id  ,"

function deleteEmployee(){

        //var employee = new Object();

        var id = $("#empId").val();
            $.ajax({

                url : "/Ram/rest/delete?id=" + id  ,
                type : "GET",
                dataType: "html",
                data: 'json',
                cache: false,
                //data: employee,
                success: function(data){
                    alert("2");
                    location.reload(true);
                },
                error : function(data){

                }
            });

    }

Second Possible way :

var employee = {
            "id": $("#empId").val()
        }

        $.ajax({

            url: "/Ram/rest/delete/",
            type: "GET",
            dataType: "html",
            data: 'json',
            cache: false,
            contentType: "application/json;",
            data: JSON.stringify(employee),
            success: function (data) {
                alert("2");
                location.reload(true);
            },
            error: function (data) {

            }
        });


问:
How can I get a favicon to show up in my django app?
I just want to drop the favicon.ico in my staticfiles directory and then have it show up in my app.

How can I accomplish this?

I have placed the favicon.ico file in my staticfiles directory, but it doesn't show up and I see this in my log:

```<code>127.0.0.1 - - [21/Feb/2014 10:10:53] "GET /favicon.ico HTTP/1.1" 404 -
</code>```

If I go to http://localhost:8000/static/favicon.ico, I can see the favicon.

答:
The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.

Add {% block extrahead %} to the overriding template.

```<code>{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
    {{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

{% endblock %}

{% block extrahead %}
    <link rel="shortcut icon" href="{% static 'app/img/favicon.ico'  %}" />
{% endblock %}
{% block stylesheets %}

    {{ block.super }}
{% endblock %}
</code>```

Body:
I just want to drop the favicon.ico in my staticfiles directory and then have it show up in my app.

How can I accomplish this?

I have placed the favicon.ico file in my staticfiles directory, but it doesn't show up and I see this in my log:

127.0.0.1 - - [21/Feb/2014 10:10:53] "GET /favicon.ico HTTP/1.1" 404 -

If I go to http://localhost:8000/static/favicon.ico, I can see the favicon.

Body:
The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.

Add {% block extrahead %} to the overriding template.

{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
    {{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

{% endblock %}

{% block extrahead %}
    <link rel="shortcut icon" href="{% static 'app/img/favicon.ico'  %}" />
{% endblock %}
{% block stylesheets %}

    {{ block.super }}
{% endblock %}


问:
Certain Unix commands fail with "... not found", when executed through Java using JSch even with setPty enabled
I'm creating an android app that sends commands to a linux terminal on a device. I am able to get the proper output when using the "ls" command, however the device does not give me any output when I use "ifconfig" or "iwconfig". Using Tera Term, I have verified these commands do work. I have tried including ((ChannelExec)channel).setPty(true); in order to fix this, however the terminal still appears to not recognise the command. Adding that line of code also changes my output for the "ls" command to something I do not recognise.

This is my JSch code:

```<code>package com.example.riot94.whizpacecontroller;
import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
 * Created by riot94 on 1/6/2017.
 */

public class JSchConnectionProtocol extends AsyncTask<String, Void, String>{
    private String host;
    private String user;
    private String password;

    public JSchConnectionProtocol(String h, String u, String p){
        host = h;
        user = u;
        password = p;
    }

    @Override
    protected String doInBackground(String... command) {
        String output = "";
        try{
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session=jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);
            session.setTimeout(10000);
            Log.d("CONNECTION", "Attempting to connect to " + host + " as user: " + user);
            session.connect();
            Log.d("CONNECTION", "Connected to " + host + " as user: " + user);

            Channel channel=session.openChannel("exec");
            ((ChannelExec)channel).setPty(true);
            ((ChannelExec)channel).setCommand(command[0]);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            output = printOutputAfterXMilliSeconds(channel,1000);

            channel.disconnect();
            session.disconnect();
            Log.d("DONE","DONE");
        }catch(Exception e){
            e.printStackTrace();
        }
        return output;
    }

    private String printOutputAfterXMilliSeconds(Channel channel, int ms) throws IOException, JSchException {
        InputStream in=channel.getInputStream();
        channel.connect();
        String totalOutput = "";
        byte[] tmp=new byte[1024];
        while(true){
            while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                String output = new String(tmp, 0, i);
                totalOutput += output;
                Log.d("OUTPUT", output);
            }

            if(channel.isClosed()){
                Log.d("EXIT_STAT","exit-status: "+channel.getExitStatus());
                break;
            }

            try{
                Log.d("PRE-SLEEP","About to sleep");
                Thread.sleep(ms);
                //channel.sendSignal("2");
                Log.d("POST-SLEEP","Slept and woken");
            }catch(Exception ee){
                ee.printStackTrace();
                channel.disconnect();
            }
        }
        return totalOutput;
    }

}
</code>```

My android app receives an empty String in its activity when I enter

iwconfig

without ((ChannelExec)channel).setPty(true);. With it, my output is:

ash: iwconfig: not found

     exit-status: 127

I get a similar result with

ifconfig

My output of the "ls" command with ((ChannelExec)channel).setPty(true);:

[1;34mGUI[0m                            [1;32mmeter.sh[0m
[1;32mReadme4Gui[0m                     [0;0mmeter_iplist.txt[0m
[1;32mami_concentrator_ETH_20120413[0m  [0;0mmeter_list.txt[0m
[1;32mami_demo_qingjun[0m               [0;0mroute.sh[0m
[1;32mami_festtech[0m                   [1;32mscript.sh[0m
[1;32mami_mac[0m                        [1;32msetGateway.sh[0m
[1;32mami_qingjun[0m                    [1;32mspectrmgmt[0m
[1;32mbootup.sh[0m                      [1;32msystem.sh[0m
[1;32mconcentrator.sh[0m                [1;32mtemp1.sh[0m
[1;32mdisFreq.sh[0m                     [1;32mtest.sh[0m
[1;32mdisLinkQuality.sh[0m              [1;32mtest1.sh[0m
```

<p>My output of the "ls" command without <code>((ChannelExec)channel).setPty(true);</code>:</p>

<pre class="lang-none prettyprint-override"><code>GUI
Readme4Gui
ami_concentrator_ETH_20120413
ami_demo_qingjun
ami_festtech
ami_mac
ami_qingjun
bootup.sh
concentrator.sh
disFreq.sh
disLinkQuality.sh
meter.sh
meter_iplist.txt
meter_list.txt
route.sh
script.sh
setGateway.sh
spectrmgmt
system.sh
temp1.sh
test.sh
test1.sh
</code>```

I am not sure what I am doing wrong, how I can fix this so that I can get the correct output for both the iwconfig/ifconfig and ls commands?

答:
Your server/shell is misconfigured somehow. It does not set the PATH correctly, when a shell session is not started. That's, why the ifconfig/iwconfig binaries cannot be found.

Either fix your startup scripts to set the PATH correctly for all situations. Or use a full path to the ifconfig/iwconfig.

To find the full path, open a regular shell session using your SSH client and type:

```<code>which ifconfig
</code>```

For a similar issue, see Certain Unix commands fail with "... not found", when executed through Java using JSch.

Body:
I'm creating an android app that sends commands to a linux terminal on a device. I am able to get the proper output when using the "ls" command, however the device does not give me any output when I use "ifconfig" or "iwconfig". Using Tera Term, I have verified these commands do work. I have tried including ((ChannelExec)channel).setPty(true); in order to fix this, however the terminal still appears to not recognise the command. Adding that line of code also changes my output for the "ls" command to something I do not recognise.

This is my JSch code:

package com.example.riot94.whizpacecontroller;
import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
 * Created by riot94 on 1/6/2017.
 */

public class JSchConnectionProtocol extends AsyncTask<String, Void, String>{
    private String host;
    private String user;
    private String password;

    public JSchConnectionProtocol(String h, String u, String p){
        host = h;
        user = u;
        password = p;
    }

    @Override
    protected String doInBackground(String... command) {
        String output = "";
        try{
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session=jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);
            session.setTimeout(10000);
            Log.d("CONNECTION", "Attempting to connect to " + host + " as user: " + user);
            session.connect();
            Log.d("CONNECTION", "Connected to " + host + " as user: " + user);

            Channel channel=session.openChannel("exec");
            ((ChannelExec)channel).setPty(true);
            ((ChannelExec)channel).setCommand(command[0]);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            output = printOutputAfterXMilliSeconds(channel,1000);

            channel.disconnect();
            session.disconnect();
            Log.d("DONE","DONE");
        }catch(Exception e){
            e.printStackTrace();
        }
        return output;
    }

    private String printOutputAfterXMilliSeconds(Channel channel, int ms) throws IOException, JSchException {
        InputStream in=channel.getInputStream();
        channel.connect();
        String totalOutput = "";
        byte[] tmp=new byte[1024];
        while(true){
            while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                String output = new String(tmp, 0, i);
                totalOutput += output;
                Log.d("OUTPUT", output);
            }

            if(channel.isClosed()){
                Log.d("EXIT_STAT","exit-status: "+channel.getExitStatus());
                break;
            }

            try{
                Log.d("PRE-SLEEP","About to sleep");
                Thread.sleep(ms);
                //channel.sendSignal("2");
                Log.d("POST-SLEEP","Slept and woken");
            }catch(Exception ee){
                ee.printStackTrace();
                channel.disconnect();
            }
        }
        return totalOutput;
    }

}

My android app receives an empty String in its activity when I enter

iwconfig

without ((ChannelExec)channel).setPty(true);. With it, my output is:

ash: iwconfig: not found

     exit-status: 127

I get a similar result with

ifconfig

My output of the "ls" command with ((ChannelExec)channel).setPty(true);:

[1;34mGUI[0m                            [1;32mmeter.sh[0m
[1;32mReadme4Gui[0m                     [0;0mmeter_iplist.txt[0m
[1;32mami_concentrator_ETH_20120413[0m  [0;0mmeter_list.txt[0m
[1;32mami_demo_qingjun[0m               [0;0mroute.sh[0m
[1;32mami_festtech[0m                   [1;32mscript.sh[0m
[1;32mami_mac[0m                        [1;32msetGateway.sh[0m
[1;32mami_qingjun[0m                    [1;32mspectrmgmt[0m
[1;32mbootup.sh[0m                      [1;32msystem.sh[0m
[1;32mconcentrator.sh[0m                [1;32mtemp1.sh[0m
[1;32mdisFreq.sh[0m                     [1;32mtest.sh[0m
[1;32mdisLinkQuality.sh[0m              [1;32mtest1.sh[0m

My output of the "ls" command without ((ChannelExec)channel).setPty(true);:

GUI
Readme4Gui
ami_concentrator_ETH_20120413
ami_demo_qingjun
ami_festtech
ami_mac
ami_qingjun
bootup.sh
concentrator.sh
disFreq.sh
disLinkQuality.sh
meter.sh
meter_iplist.txt
meter_list.txt
route.sh
script.sh
setGateway.sh
spectrmgmt
system.sh
temp1.sh
test.sh
test1.sh

I am not sure what I am doing wrong, how I can fix this so that I can get the correct output for both the iwconfig/ifconfig and ls commands?

Body:
Your server/shell is misconfigured somehow. It does not set the PATH correctly, when a shell session is not started. That's, why the ifconfig/iwconfig binaries cannot be found.

Either fix your startup scripts to set the PATH correctly for all situations. Or use a full path to the ifconfig/iwconfig.

To find the full path, open a regular shell session using your SSH client and type:

which ifconfig

For a similar issue, see Certain Unix commands fail with "... not found", when executed through Java using JSch.


问:
Get The State of Connected Components in Jest & Enzyme
Good day people! Let's say that i have this component Class:

@connect(
  state =>({
    someState: state.oneLevel.response
  })
)
export default class SomeClass extends React.Component{
constructor(props){
  super(props)
  this.state ={
    someState: [],
    isLoading: false,
    isLoaded: false
  }
}
}```
</div>
</div>
</p>

<p>This component has an async call with superagent</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>componentDidMount(){
 var url = 'someapi.com/somedatatofetch'
 this.setState({isLoading: true})
 request.get(url)
 .set('some headers 1', 'somevalue')
 .set('some headers 2', 'somevalue')
 .then((success) => {
      this.setState({
        isLoading: false,
        isLoaded: true
      })
 })
}</code>```

Now I've been assigned to write a unit test for this Component to check whether it has successfully changed its state or not. I'm using Jest as my test framework and enzyme for handling DOM Renderer etc.

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)

  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(wrapper.state(isLoaded)).toEqual(expectedState)
    })
  }
})```

With that code the response is as follows:
TypeError: Cannot read property 'isLoaded' of null

my question is, is there anyway to get the state using connected components?
I've tried exporting the component as ConnectedComponents and {Components}
and it works flawlessly but I want to use connected components.

Why did I want to use connected components? Because the every components of my applications is built using this scheme and its not feasible to export as ConnectedComponents and {Components} for there is so many components within my applications and it might leads to more problems

答:
I've managed to solve this problem by finding the Node component using
wrapper.find('SomeComponent') if you console.log() it, you'll see that it will yields the component nodes along with the states. This is my final code

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)

  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    var somecomponent = wrapper.find("SomeComponent")
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(somecomponent.getNode().state.isLoaded)toEqual(expectedState)

    })
  }
})```

as you can see I'm making another variable to contain the SomeComponent search result. And finally, i called the getNode() function to get the SomeComponent along with its states.
I did not know whether this is the best practice or not but it works. I'd love some feedback tho if there's a better way of doing this

Body:
Good day people! Let's say that i have this component Class:

@connect(
  state =>({
    someState: state.oneLevel.response
  })
)
export default class SomeClass extends React.Component{
constructor(props){
  super(props)
  this.state ={
    someState: [],
    isLoading: false,
    isLoaded: false
  }
}
}

This component has an async call with superagent

componentDidMount(){
 var url = 'someapi.com/somedatatofetch'
 this.setState({isLoading: true})
 request.get(url)
 .set('some headers 1', 'somevalue')
 .set('some headers 2', 'somevalue')
 .then((success) => {
      this.setState({
        isLoading: false,
        isLoaded: true
      })
 })
}

Now I've been assigned to write a unit test for this Component to check whether it has successfully changed its state or not. I'm using Jest as my test framework and enzyme for handling DOM Renderer etc.

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)

  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(wrapper.state(isLoaded)).toEqual(expectedState)
    })
  }
})

With that code the response is as follows:
TypeError: Cannot read property 'isLoaded' of null

my question is, is there anyway to get the state using connected components?
I've tried exporting the component as ConnectedComponents and {Components}
and it works flawlessly but I want to use connected components.

Why did I want to use connected components? Because the every components of my applications is built using this scheme and its not feasible to export as ConnectedComponents and {Components} for there is so many components within my applications and it might leads to more problems

Body:
I've managed to solve this problem by finding the Node component using
wrapper.find('SomeComponent') if you console.log() it, you'll see that it will yields the component nodes along with the states. This is my final code

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)

  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    var somecomponent = wrapper.find("SomeComponent")
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(somecomponent.getNode().state.isLoaded)toEqual(expectedState)

    })
  }
})

as you can see I'm making another variable to contain the SomeComponent search result. And finally, i called the getNode() function to get the SomeComponent along with its states.
I did not know whether this is the best practice or not but it works. I'd love some feedback tho if there's a better way of doing this


问:
How can we use Assets Catalog Color Sets?
I usually use custom UIColors on iOS using extensions with Swift, but now with iOS 11/ Xcode 9 we can create Colors Sets. How can we use them?

Update - Tip

As @Cœur says we can drag&drop de color, and use it like a UIColor object and a possible solution could be use it as a extension:

Or as a constant:

Now I wanna know if we can access them like an UIImage access to an Asset Image or not, like:

```<code>UIImage(named: "image-name") -> UIColor(named: "color-name")
</code>```

答:
(short answer to the question update: there is UIColor(named: "MyColor") in Xcode 9.0)

Answering the original question:

you create your color set

you find your color among your snippets and you drag-n-drop it

it will translate to a color literal when looking at the source code:

#colorLiteral(red: 0, green: 0.6378085017, blue: 0.8846047521, alpha: 1)

You notice how the values of red, green and blue are different? It's because I defined them using Color Space Display P3, but the colorLiteral is using Color Space sRGB.

Body:
I usually use custom UIColors on iOS using extensions with Swift, but now with iOS 11/ Xcode 9 we can create Colors Sets. How can we use them?

Update - Tip

As @Cœur says we can drag&drop de color, and use it like a UIColor object and a possible solution could be use it as a extension:

Or as a constant:

Now I wanna know if we can access them like an UIImage access to an Asset Image or not, like:

UIImage(named: "image-name") -> UIColor(named: "color-name")


问:
How to open/run .jar file (double-click not working)?
I can't open or run my .jar file.

I just installed java, but I tried to open the .jar with other programs first, so the double-click defaults to something else and I can't change it back.

```<code>java -jar myfile.jar`
</code>```

Above command returns:

'java' is not recognized as an internal or external command, operable program or batch file.

Is there a way I can still open/run this?

e: OS is Windows 8.

Also, I downloaded the .jar file; didn't create it myself (if that's relevant)
Not sure if it contains an executable (but I think it does).

答:
If the intention of the question is to view the contents of the JAR file, then the following java command would help.. (provided, JDK location is added to the environment variables.)

Windows Command prompt> jar tvf yourJarFile.jar

Example:

jar tvf log4j-extras-1.2.17.jar

Reference: http://docs.oracle.com/javase/tutorial/deployment/jar/view.html

Body:
I can't open or run my .jar file.

I just installed java, but I tried to open the .jar with other programs first, so the double-click defaults to something else and I can't change it back.

java -jar myfile.jar`

Above command returns:

'java' is not recognized as an internal or external command, operable program or batch file.

Is there a way I can still open/run this?

e: OS is Windows 8.

Also, I downloaded the .jar file; didn't create it myself (if that's relevant)
Not sure if it contains an executable (but I think it does).


问:
OOP: two very similar methods, but different types of data --howto optimise?
I'm trying to optimise some code. Specifically, I have two methods that are very similar in terms of what they do. The operations they perform are the same, the difference is that one concatenates strings, and the other appends these strings into a list. The only parts of the methods that are different are the instances that involve string or list-specific methods/operations.

example:

```<code>    class Some_Class:
        def __init__(self, num):
            self.num = num

        def some_function(self):
            collector = ''
            for x in range(self.num):
                #do something
                collector+= #the something
            return collector

        def some_function(self):
            collector = []
            for x in range(self.num):
                #do something
                collector.append(#the result of something)
            return collector
</code>```

What would be the best way of optimising the code? A simple

```<code>    if type(data) == str:
        #do something
    else:
        #assume it's a list, and act accordingly
</code>```

...results in unsightly, hard to heard code, as I would have to write this in multiple places. Recommendations?

答:
I may be misinterpreting what you are wanting, but here are some suggestions anyway.

If your two methods as you say are similar, essentially doing the same thing, but producing a differently formatting response, what you could do is something like the following to consolidate duplicated code into a single private function of the class:

```<code>class Some_Class:
    def __init__(self, num):
        self.num = num

    # obviously these two `some_function`s wouldn't have the same name?
    def some_function(self):
        collector = ''
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector+= result
        return collector

    def some_function(self):
        collector = []
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector.append(result)
        return collector

    def _do_something(self, <some args>):
        # common function containing all the repeated functionality
        # between the other two functions

        # do something
</code>```

If you must have everything in a single function, then your if/else example is probably still a good way to go. Perhaps using a bool variable instead of calling type everytime would be neater though.

Body:
I'm trying to optimise some code. Specifically, I have two methods that are very similar in terms of what they do. The operations they perform are the same, the difference is that one concatenates strings, and the other appends these strings into a list. The only parts of the methods that are different are the instances that involve string or list-specific methods/operations.

example:

    class Some_Class:
        def __init__(self, num):
            self.num = num

        def some_function(self):
            collector = ''
            for x in range(self.num):
                #do something
                collector+= #the something
            return collector

        def some_function(self):
            collector = []
            for x in range(self.num):
                #do something
                collector.append(#the result of something)
            return collector

What would be the best way of optimising the code? A simple

    if type(data) == str:
        #do something
    else:
        #assume it's a list, and act accordingly

...results in unsightly, hard to heard code, as I would have to write this in multiple places. Recommendations?

Body:
I may be misinterpreting what you are wanting, but here are some suggestions anyway.

If your two methods as you say are similar, essentially doing the same thing, but producing a differently formatting response, what you could do is something like the following to consolidate duplicated code into a single private function of the class:

class Some_Class:
    def __init__(self, num):
        self.num = num

    # obviously these two `some_function`s wouldn't have the same name?
    def some_function(self):
        collector = ''
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector+= result
        return collector

    def some_function(self):
        collector = []
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector.append(result)
        return collector

    def _do_something(self, <some args>):
        # common function containing all the repeated functionality
        # between the other two functions

        # do something

If you must have everything in a single function, then your if/else example is probably still a good way to go. Perhaps using a bool variable instead of calling type everytime would be neater though.


问:
How do I make a redirect in PHP?
Is it possible to redirect a user to a different page through the use of PHP?

Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?

This could even protect my pages from unauthorized users.

答:
Yes, it's possible to use PHP. We will redirect to another page.

Try following code:

```<code><?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.php");
?>
</code>```

Title: How do I make a redirect in PHP?

Body:
Yes, it's possible to use PHP. We will redirect to another page.

Try following code:

<?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.php");
?>


问:
Importing asset bundle from web server in Android mobile
In Unity, I am creating an asset bundle and am loading that assets from server and am running that app in Android.  Now the problem was asset bundle can't be loaded in Android device, but it was loaded in Editor. Can anyone give me a suggestion to load assets bundle in Android?</p>

答:
I created assetbundles using this code

```<code>public class creatinassets : MonoBehaviour {

[MenuItem ("Assets/Build AssetBundles")]
static void BulidAllAssetBundles()
{
    BuildPipeline.BuildAssetBundles("Assets/Asset bundles",BuildAssetBundleOptions.None, BuildTarget.Android );
}
</code>```

I loaded the bundle using following code

```<code>public class loading : MonoBehaviour {
public GameObject cub;
public WWW www;

void Start()
{
    StartCoroutine ("Downloadobject");
}
IEnumerator Downloadobject()
{
    www = WWW.LoadFromCacheOrDownload  ("http://192.168.1.126/gopinath/AssetBundles/light",3);// light= Assetbundlename
    yield return www;

    AssetBundle bundle = www.assetBundle;
    if (bundle == null) {
        Debug.Log ("error loading www");
    } else {

         cub = (GameObject)bundle.LoadAsset ("lamp"); //lamp = Assetname
        Instantiate (cub);

    }
}
</code>```

}

Body:
I created assetbundles using this code

public class creatinassets : MonoBehaviour {

[MenuItem ("Assets/Build AssetBundles")]
static void BulidAllAssetBundles()
{
    BuildPipeline.BuildAssetBundles("Assets/Asset bundles",BuildAssetBundleOptions.None, BuildTarget.Android );
}

I loaded the bundle using following code

public class loading : MonoBehaviour {
public GameObject cub;
public WWW www;

void Start()
{
    StartCoroutine ("Downloadobject");
}
IEnumerator Downloadobject()
{
    www = WWW.LoadFromCacheOrDownload  ("http://192.168.1.126/gopinath/AssetBundles/light",3);// light= Assetbundlename
    yield return www;

    AssetBundle bundle = www.assetBundle;
    if (bundle == null) {
        Debug.Log ("error loading www");
    } else {

         cub = (GameObject)bundle.LoadAsset ("lamp"); //lamp = Assetname
        Instantiate (cub);

    }
}

}


问:
I do *not* want correct rounding for function exp
The GCC implementation of the C mathematical library on Debian systems has apparently an (IEEE 754-2008)-compliant implementation of the function exp, implying that rounding shall always be correct:

(from Wikipedia) The IEEE floating point standard guarantees that add, subtract, multiply, divide, fused multiply–add, square root, and floating point remainder will give the correctly rounded result of the infinite precision operation. No such guarantee was given in the 1985 standard for more complex functions and they are typically only accurate to within the last bit at best. However, the 2008 standard guarantees that conforming implementations will give correctly rounded results which respect the active rounding mode; implementation of the functions, however, is optional.

It turns out that I am encountering a case where this feature is actually hindering, because the exact result of the exp function is often nearly exactly at the middle between two consecutive double values (1), and then the program carries plenty of several further computations, losing up to a factor 400 (!) in speed: this was actually the explanation to my (ill-asked :-S) Question #43530011.

(1) More precisely, this happens when the argument of exp turns out to be of the form (2 k + 1) × 2-53 with k a rather small integer (like 242 for instance). In particular, the computations involved by pow (1. + x, 0.5) tend to call exp with such an argument when x is of the order of magnitude of 2-44.

Since implementations of correct rounding can be so much time-consuming in certain circumstances, I guess that the developers will also have devised a way to get a slightly less precise result (say, only up to 0.6 ULP or something like this) in a time which is (roughly) bounded for every value of the argument in a given range… (2)

… But how to do this??

(2) What I mean is that I just do not want that some exceptional values of the argument like (2 k + 1) × 2-53 would be much more time-consuming than most values of the same order of magnitude; but of course I do not mind if some exceptional values of the argument go much faster, or if large arguments (in absolute value) need a larger computation time.

Here is a minimal program showing the phenomenon:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
 {
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
   {
    a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
    c += exp (a); // Just to be sure that the compiler will actually perform the computation of exp (a).
   }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
 }
</code>```

Now after gcc -std=c99 program53.c -lm -o program53:

$ ./program53
1.000000e+06
Clock time spent: 13470008
$ ./program53
1.000000e+06
Clock time spent: 13292721
$ ./program53
1.000000e+06
Clock time spent: 13201616
```

<p>On the other hand, with <code>program52</code> and <code>program54</code> (got by replacing <code>0x20000000000000</code> by resp. <code>0x10000000000000</code> and <code>0x40000000000000</code>):</p>

<pre class="lang-none prettyprint-override"><code>$ ./program52
1.000000e+06
Clock time spent: 83594
$ ./program52
1.000000e+06
Clock time spent: 69095
$ ./program52
1.000000e+06
Clock time spent: 54694
$ ./program54
1.000000e+06
Clock time spent: 86151
$ ./program54
1.000000e+06
Clock time spent: 74209
$ ./program54
1.000000e+06
Clock time spent: 78612
</code>```

Beware, the phenomenon is implementation-dependent! Apparently, among the common implementations, only those of the Debian systems (including Ubuntu) show this phenomenon.

P.-S.: I hope that my question is not a duplicate: I searched for a similar question thoroughly without success, but maybe I did note use the relevant keywords… :-/

答:
This is an "answer"/followup to EOF's preceding comments re his trecu() algorithm and code for his "binary tree summation" suggestion. "Prerequisites" before reading this are reading that discussion. It would be nice to collect all that in one organized place, but I haven't done that yet...

...What I did do was build EOF's trecu() into the test program from the preceding answer that I'd written by modifying the OP's original test program. But then I found that trecu() generated exactly (and I mean exactly) the same answer as the "plain sum" c using exp(), not the sum cm1 using expm1() that we'd expected from a more accurate binary tree summation.

But that test program's a bit (maybe two bits:) "convoluted" (or, as EOF said, "unreadable"), so I wrote a separate smaller test program, given below (with example runs and discussion below that), to separately test/exercise trecu(). Moreover, I also wrote function bintreesum() into the code below, which abstracts/encapsulates the iterative code for binary tree summation that I'd embedded into the preceding test program. In that preceding case, my iterative code indeed came close to the cm1 answer, which is why I'd expected EOF's recursive trecu() to do the same. Long-and-short of it is that, below, same thing happens -- bintreesum() remains close to correct answer, while trecu() gets further away, exactly reproducing the "plain sum".

What we're summing below is just sum(i),i=1...n, which is just the well-known n(n+1)/2. But that's not quite right -- to reproduce OP's problem, summand is not sum(i) alone but rather sum(1+i*10^(-e)), where e can be given on the command-line. So for, say, n=5, you don't get 15 but rather 5.000...00015, or for n=6 you get 6.000...00021, etc. And to avoid a long, long format, I printf() sum-n to remove that integer part. Okay??? So here's the code...

```<code>/* Quoting from EOF's comment...
   What I (EOF) proposed is effectively a binary tree of additions:
   a+b+c+d+e+f+g+h as ((a+b)+(c+d))+((e+f)+(g+h)).
   Like this: Add adjacent pairs of elements, this produces
   a new sequence of n/2 elements.
   Recurse until only one element is left. */
#include <stdio.h>
#include <stdlib.h>

double trecu(double *vals, double sum, int n) {
  int midn = n/2;
  switch (n) {
    case  0: break;
    case  1: sum += *vals; break;
    default: sum = trecu(vals+midn, trecu(vals,sum,midn), n-midn); break; }
  return(sum);
  } /* --- end-of-function trecu() --- */

double bintreesum(double *vals, int n, int binsize) {
  double binsum = 0.0;
  int nbin0 = (n+(binsize-1))/binsize,
      nbin1 = (nbin0+(binsize-1))/binsize,
      nbins[2] = { nbin0, nbin1 };
  double *vbins[2] = {
            (double *)malloc(nbin0*sizeof(double)),
            (double *)malloc(nbin1*sizeof(double)) },
         *vbin0=vbins[0], *vbin1=vbins[1];
  int ibin=0, i;
  for ( i=0; i<nbin0; i++ ) vbin0[i] = 0.0;
  for ( i=0; i<n; i++ ) vbin0[i%nbin0] += vals[i];
  while ( nbins[ibin] > 1 ) {
    int jbin = 1-ibin;        /* other bin, 0<-->1 */
    nbins[jbin] = (nbins[ibin]+(binsize-1))/binsize;
    for ( i=0; i<nbins[jbin]; i++ ) vbins[jbin][i] = 0.0;
    for ( i=0; i<nbins[ibin]; i++ )
      vbins[jbin][i%nbins[jbin]] += vbins[ibin][i];
    ibin = jbin;              /* swap bins for next pass */
    } /* --- end-of-while(nbins[ibin]>0) --- */
  binsum = vbins[ibin][0];
  free((void *)vbins[0]);  free((void *)vbins[1]);
  return ( binsum );
  } /* --- end-of-function bintreesum() --- */

#if defined(TESTTRECU)
#include <math.h>
#define MAXN (2000000)
int main(int argc, char *argv[]) {
  int N       = (argc>1? atoi(argv[1]) : 1000000 ),
      e       = (argc>2? atoi(argv[2]) : -10 ),
      binsize = (argc>3? atoi(argv[3]) : 2 );
  double tens = pow(10.0,(double)e);
  double *vals = (double *)malloc(sizeof(double)*MAXN),
         sum = 0.0;
  double trecu(), bintreesum();
  int i;
  if ( N > MAXN ) N=MAXN;
  for ( i=0; i<N; i++ ) vals[i] = 1.0 + tens*(double)(i+1);
  for ( i=0; i<N; i++ ) sum += vals[i];
  printf(" N=%d, Sum_i=1^N {1.0 + i*%.1e} - N  =  %.8e,\n"
         "\t plain_sum-N  = %.8e,\n"
         "\t trecu-N      = %.8e,\n"
         "\t bintreesum-N = %.8e \n",
         N, tens, tens*((double)N)*((double)(N+1))/2.0,
          sum-(double)N,
         trecu(vals,0.0,N)-(double)N,
         bintreesum(vals,N,binsize)-(double)N );
  } /* --- end-of-function main() --- */
#endif
</code>```

So if you save that as trecu.c, then compile it as cc –DTESTTRECU trecu.c –lm –o trecu And then run with zero to three optional command-line args as trecu #trials e binsize Defaults are #trials=1000000 (like OP's program), e=–10, and binsize=2 (for my bintreesum() function to do a binary-tree sum rather than larger-size bins).

And here are some test results illustrating the problem described above,

```<code>bash-4.3$ ./trecu
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-10} - N  =  5.00000500e+01,
         plain_sum-N  = 5.00000500e+01,
         trecu-N      = 5.00000500e+01,
         bintreesum-N = 5.00000500e+01
bash-4.3$ ./trecu 1000000 -15
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-15} - N  =  5.00000500e-04,
         plain_sum-N  = 5.01087168e-04,
         trecu-N      = 5.01087168e-04,
         bintreesum-N = 5.00000548e-04
bash-4.3$
bash-4.3$ ./trecu 1000000 -16
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-16} - N  =  5.00000500e-05,
         plain_sum-N  = 6.67552231e-05,
         trecu-N      = 6.67552231e-05,
         bintreesum-N = 5.00001479e-05
bash-4.3$
bash-4.3$ ./trecu 1000000 -17
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-17} - N  =  5.00000500e-06,
         plain_sum-N  = 0.00000000e+00,
         trecu-N      = 0.00000000e+00,
         bintreesum-N = 4.99992166e-06
</code>```

So you can see that for the default run, e=–10, everybody's doing everything right. That is, the top line that says "Sum" just does the n(n+1)/2 thing, so presumably displays the right answer. And everybody below that agrees for the default e=–10 test case. But for the e=–15 and e=–16 cases below that, trecu() exactly agrees with the plain_sum, while bintreesum stays pretty close to the right answer. And finally, for e=–17, plain_sum and trecu() have "disappeared", while bintreesum()'s still hanging in there pretty well.

So trecu()'s correctly doing the sum all right, but its recursion's apparently not doing that "binary tree" type of thing that my more straightforward iterative bintreesum()'s apparently doing correctly. And that indeed demonstrates that EOF's suggestion for "binary tree summation" realizes quite an improvement over the plain_sum for these 1+epsilon kind of cases. So we'd really like to see his trecu() recursion work!!! When I originally looked at it, I thought it did work. But that double-recursion (is there a special name for that?) in his default: case is apparently more confusing (at least to me:) than I thought. Like I said, it is doing the sum, but not the "binary tree" thing.

Okay, so who'd like to take on the challenge and explain what's going on in that trecu() recursion? And, maybe more importantly, fix it so it does what's intended. Thanks.

Body:
The GCC implementation of the C mathematical library on Debian systems has apparently an (IEEE 754-2008)-compliant implementation of the function exp, implying that rounding shall always be correct:

(from Wikipedia) The IEEE floating point standard guarantees that add, subtract, multiply, divide, fused multiply–add, square root, and floating point remainder will give the correctly rounded result of the infinite precision operation. No such guarantee was given in the 1985 standard for more complex functions and they are typically only accurate to within the last bit at best. However, the 2008 standard guarantees that conforming implementations will give correctly rounded results which respect the active rounding mode; implementation of the functions, however, is optional.

It turns out that I am encountering a case where this feature is actually hindering, because the exact result of the exp function is often nearly exactly at the middle between two consecutive double values (1), and then the program carries plenty of several further computations, losing up to a factor 400 (!) in speed: this was actually the explanation to my (ill-asked :-S) Question #43530011.

(1) More precisely, this happens when the argument of exp turns out to be of the form (2 k + 1) × 2-53 with k a rather small integer (like 242 for instance). In particular, the computations involved by pow (1. + x, 0.5) tend to call exp with such an argument when x is of the order of magnitude of 2-44.

Since implementations of correct rounding can be so much time-consuming in certain circumstances, I guess that the developers will also have devised a way to get a slightly less precise result (say, only up to 0.6 ULP or something like this) in a time which is (roughly) bounded for every value of the argument in a given range… (2)

… But how to do this??

(2) What I mean is that I just do not want that some exceptional values of the argument like (2 k + 1) × 2-53 would be much more time-consuming than most values of the same order of magnitude; but of course I do not mind if some exceptional values of the argument go much faster, or if large arguments (in absolute value) need a larger computation time.

Here is a minimal program showing the phenomenon:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
 {
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
   {
    a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
    c += exp (a); // Just to be sure that the compiler will actually perform the computation of exp (a).
   }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
 }

Now after gcc -std=c99 program53.c -lm -o program53:

$ ./program53
1.000000e+06
Clock time spent: 13470008
$ ./program53
1.000000e+06
Clock time spent: 13292721
$ ./program53
1.000000e+06
Clock time spent: 13201616

On the other hand, with program52 and program54 (got by replacing 0x20000000000000 by resp. 0x10000000000000 and 0x40000000000000):

$ ./program52
1.000000e+06
Clock time spent: 83594
$ ./program52
1.000000e+06
Clock time spent: 69095
$ ./program52
1.000000e+06
Clock time spent: 54694
$ ./program54
1.000000e+06
Clock time spent: 86151
$ ./program54
1.000000e+06
Clock time spent: 74209
$ ./program54
1.000000e+06
Clock time spent: 78612

Beware, the phenomenon is implementation-dependent! Apparently, among the common implementations, only those of the Debian systems (including Ubuntu) show this phenomenon.

P.-S.: I hope that my question is not a duplicate: I searched for a similar question thoroughly without success, but maybe I did note use the relevant keywords… :-/

Body:
This is an "answer"/followup to EOF's preceding comments re his trecu() algorithm and code for his "binary tree summation" suggestion. "Prerequisites" before reading this are reading that discussion. It would be nice to collect all that in one organized place, but I haven't done that yet...

...What I did do was build EOF's trecu() into the test program from the preceding answer that I'd written by modifying the OP's original test program. But then I found that trecu() generated exactly (and I mean exactly) the same answer as the "plain sum" c using exp(), not the sum cm1 using expm1() that we'd expected from a more accurate binary tree summation.

But that test program's a bit (maybe two bits:) "convoluted" (or, as EOF said, "unreadable"), so I wrote a separate smaller test program, given below (with example runs and discussion below that), to separately test/exercise trecu(). Moreover, I also wrote function bintreesum() into the code below, which abstracts/encapsulates the iterative code for binary tree summation that I'd embedded into the preceding test program. In that preceding case, my iterative code indeed came close to the cm1 answer, which is why I'd expected EOF's recursive trecu() to do the same. Long-and-short of it is that, below, same thing happens -- bintreesum() remains close to correct answer, while trecu() gets further away, exactly reproducing the "plain sum".

What we're summing below is just sum(i),i=1...n, which is just the well-known n(n+1)/2. But that's not quite right -- to reproduce OP's problem, summand is not sum(i) alone but rather sum(1+i*10^(-e)), where e can be given on the command-line. So for, say, n=5, you don't get 15 but rather 5.000...00015, or for n=6 you get 6.000...00021, etc. And to avoid a long, long format, I printf() sum-n to remove that integer part. Okay??? So here's the code...

/* Quoting from EOF's comment...
   What I (EOF) proposed is effectively a binary tree of additions:
   a+b+c+d+e+f+g+h as ((a+b)+(c+d))+((e+f)+(g+h)).
   Like this: Add adjacent pairs of elements, this produces
   a new sequence of n/2 elements.
   Recurse until only one element is left. */
#include <stdio.h>
#include <stdlib.h>

double trecu(double *vals, double sum, int n) {
  int midn = n/2;
  switch (n) {
    case  0: break;
    case  1: sum += *vals; break;
    default: sum = trecu(vals+midn, trecu(vals,sum,midn), n-midn); break; }
  return(sum);
  } /* --- end-of-function trecu() --- */

double bintreesum(double *vals, int n, int binsize) {
  double binsum = 0.0;
  int nbin0 = (n+(binsize-1))/binsize,
      nbin1 = (nbin0+(binsize-1))/binsize,
      nbins[2] = { nbin0, nbin1 };
  double *vbins[2] = {
            (double *)malloc(nbin0*sizeof(double)),
            (double *)malloc(nbin1*sizeof(double)) },
         *vbin0=vbins[0], *vbin1=vbins[1];
  int ibin=0, i;
  for ( i=0; i<nbin0; i++ ) vbin0[i] = 0.0;
  for ( i=0; i<n; i++ ) vbin0[i%nbin0] += vals[i];
  while ( nbins[ibin] > 1 ) {
    int jbin = 1-ibin;        /* other bin, 0<-->1 */
    nbins[jbin] = (nbins[ibin]+(binsize-1))/binsize;
    for ( i=0; i<nbins[jbin]; i++ ) vbins[jbin][i] = 0.0;
    for ( i=0; i<nbins[ibin]; i++ )
      vbins[jbin][i%nbins[jbin]] += vbins[ibin][i];
    ibin = jbin;              /* swap bins for next pass */
    } /* --- end-of-while(nbins[ibin]>0) --- */
  binsum = vbins[ibin][0];
  free((void *)vbins[0]);  free((void *)vbins[1]);
  return ( binsum );
  } /* --- end-of-function bintreesum() --- */

#if defined(TESTTRECU)
#include <math.h>
#define MAXN (2000000)
int main(int argc, char *argv[]) {
  int N       = (argc>1? atoi(argv[1]) : 1000000 ),
      e       = (argc>2? atoi(argv[2]) : -10 ),
      binsize = (argc>3? atoi(argv[3]) : 2 );
  double tens = pow(10.0,(double)e);
  double *vals = (double *)malloc(sizeof(double)*MAXN),
         sum = 0.0;
  double trecu(), bintreesum();
  int i;
  if ( N > MAXN ) N=MAXN;
  for ( i=0; i<N; i++ ) vals[i] = 1.0 + tens*(double)(i+1);
  for ( i=0; i<N; i++ ) sum += vals[i];
  printf(" N=%d, Sum_i=1^N {1.0 + i*%.1e} - N  =  %.8e,\n"
         "\t plain_sum-N  = %.8e,\n"
         "\t trecu-N      = %.8e,\n"
         "\t bintreesum-N = %.8e \n",
         N, tens, tens*((double)N)*((double)(N+1))/2.0,
          sum-(double)N,
         trecu(vals,0.0,N)-(double)N,
         bintreesum(vals,N,binsize)-(double)N );
  } /* --- end-of-function main() --- */
#endif

So if you save that as trecu.c, then compile it as cc –DTESTTRECU trecu.c –lm –o trecu And then run with zero to three optional command-line args as trecu #trials e binsize Defaults are #trials=1000000 (like OP's program), e=–10, and binsize=2 (for my bintreesum() function to do a binary-tree sum rather than larger-size bins).

And here are some test results illustrating the problem described above,

bash-4.3$ ./trecu
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-10} - N  =  5.00000500e+01,
         plain_sum-N  = 5.00000500e+01,
         trecu-N      = 5.00000500e+01,
         bintreesum-N = 5.00000500e+01
bash-4.3$ ./trecu 1000000 -15
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-15} - N  =  5.00000500e-04,
         plain_sum-N  = 5.01087168e-04,
         trecu-N      = 5.01087168e-04,
         bintreesum-N = 5.00000548e-04
bash-4.3$
bash-4.3$ ./trecu 1000000 -16
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-16} - N  =  5.00000500e-05,
         plain_sum-N  = 6.67552231e-05,
         trecu-N      = 6.67552231e-05,
         bintreesum-N = 5.00001479e-05
bash-4.3$
bash-4.3$ ./trecu 1000000 -17
 N=1000000, Sum_i=1^N {1.0 + i*1.0e-17} - N  =  5.00000500e-06,
         plain_sum-N  = 0.00000000e+00,
         trecu-N      = 0.00000000e+00,
         bintreesum-N = 4.99992166e-06

So you can see that for the default run, e=–10, everybody's doing everything right. That is, the top line that says "Sum" just does the n(n+1)/2 thing, so presumably displays the right answer. And everybody below that agrees for the default e=–10 test case. But for the e=–15 and e=–16 cases below that, trecu() exactly agrees with the plain_sum, while bintreesum stays pretty close to the right answer. And finally, for e=–17, plain_sum and trecu() have "disappeared", while bintreesum()'s still hanging in there pretty well.

So trecu()'s correctly doing the sum all right, but its recursion's apparently not doing that "binary tree" type of thing that my more straightforward iterative bintreesum()'s apparently doing correctly. And that indeed demonstrates that EOF's suggestion for "binary tree summation" realizes quite an improvement over the plain_sum for these 1+epsilon kind of cases. So we'd really like to see his trecu() recursion work!!! When I originally looked at it, I thought it did work. But that double-recursion (is there a special name for that?) in his default: case is apparently more confusing (at least to me:) than I thought. Like I said, it is doing the sum, but not the "binary tree" thing.

Okay, so who'd like to take on the challenge and explain what's going on in that trecu() recursion? And, maybe more importantly, fix it so it does what's intended. Thanks.