问:
Display dynamic HTML as tab content in Angular UI
In this plunk I have a Angular UI tabs with HTML content that needs to be generated dynamically. Still, the tab contents shows instead the HTML markup. How to fix this?

HTML

```<code> <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      {{tab.content}}
    </uib-tab>
 </uib-tabset>
</code>```

Javascript

```<code>var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
                    { title:'title 1', content:'<div id="id1">111</div>' },
                    { title:'title 2', content:'<div id="id2">222</div>' }
                  ];
});
</code>```

答:
Use

 :

```<code> <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-bind-html="tab.content"></div>
    </uib-tab>
  </uib-tabset>
</code>```

Body:
In this plunk I have a Angular UI tabs with HTML content that needs to be generated dynamically. Still, the tab contents shows instead the HTML markup. How to fix this?

HTML

 <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      {{tab.content}}
    </uib-tab>
 </uib-tabset>

Javascript

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
                    { title:'title 1', content:'
111
' },
                    { title:'title 2', content:'
222
' }
                  ];
});

Body:
Use <div ng-bind-html="tab.content"></div> :

 <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-bind-html="tab.content"></div>
    </uib-tab>
  </uib-tabset>


来源: stackexchange

问:
FileReader trying to read hexadecimals, java
I have a file I want to read into my java project. It contains hexadecimal data. The file I have does not have a file-extension, which is how I'll have to work with it because that's how the program will receive the files.

I know I have the right file, because in Sublime Text it opens like this.

http://i.imgur.com/iF3iX68.png

Nice and hexadecimal. ... But open the same file in Gedit...

http://i.imgur.com/Vf5Hyc6.png

Complete chaos. When I then attempt to open the file in my project the way I know how,

```<code>try (BufferedReader br = new BufferedReader(new FileReader(url))) {
    while ((line = br.readLine()) != null) {
        byte[] sj = line.getBytes();
        char[] charLine = new char[line.length()];
        line.getChars(0, line.length(), charLine, 0);
    }
} (catch and stuff below)
</code>```

Gets me a byte array that is like

```<code>525 = -65
526 = -67
527 = 15
528 = -17
529 = -65
530 = -67
531 = 15
532 = -17
533 = -65
</code>```

and so on in a system that shouldn't possibly be able to get negative numbers. And in my char array...

```<code>525 = '\u000F' 15
526 = '�' 65533
527 = '\u000F' 15
528 = '�' 65533
529 = '\u000F' 15
530 = '�' 65533
531 = '\u000F' 15
532 = '\u0003' 3
533 = '\u0010' 16
</code>```

Values that are only 15 in the char-array is sometimes -65 and sometimes 15 in the byte-array, and none of them look like the hexadecimals in the sublime file. I know the bytes/chars each represent two symbols in the sublime file, but... yeah.

I am honestly quite stumped. How do I properly read hexadecimal numbers from this file? Like how Sublime opens it?

答:
I write a code that transforms one line of hex into array of integers so i think that this is what You want.
In shotrt - code takes one line of text from file with You presented on first photo and trim to hex values as one strin then splits in to array of Strings and decode for signed values of Integer and returns array of integers. I have tested ths code manualy so there is main() below. Sorry for languange byt hen You see time of this post You will Undestand :) - 01:00 AM :)</p>

```<code>import java.util.Arrays;

    /**
     * Created by maciej.brzozowski.83@gmail.com on 2017-04-03 01:00AM.
     */
    public class hexDecoder {

        public  int[] decode(String inputString){
            inputString= inputString.substring(inputString.indexOf(" "));
            inputString= inputString.trim();
            String hexArray[] = inputString.split(" ");
            int[] intValuesOfHex = new int[hexArray.length];
            for (int i = 0; i <hexArray.length ; i++) {
              intValuesOfHex[i]=Integer.valueOf(hexArray[i],16);
              }

        return intValuesOfHex;
        }

        public static void main(String[] args) {
           String hexToDecode = "33  c60f cc0f d20f d80f de0f e407 ea0f f10f";
            System.out.println(Arrays.toString(new hexDecoder().decode(hexToDecode)));
        }

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a file I want to read into my java project. It contains hexadecimal data. The file I have does not have a file-extension, which is how I'll have to work with it because that's how the program will receive the files.

I know I have the right file, because in Sublime Text it opens like this.

http://i.imgur.com/iF3iX68.png

Nice and hexadecimal. ... But open the same file in Gedit...

http://i.imgur.com/Vf5Hyc6.png

Complete chaos. When I then attempt to open the file in my project the way I know how,

try (BufferedReader br = new BufferedReader(new FileReader(url))) {
    while ((line = br.readLine()) != null) {
        byte[] sj = line.getBytes();
        char[] charLine = new char[line.length()];
        line.getChars(0, line.length(), charLine, 0);
    }
} (catch and stuff below)

Gets me a byte array that is like

525 = -65
526 = -67
527 = 15
528 = -17
529 = -65
530 = -67
531 = 15
532 = -17
533 = -65

and so on in a system that shouldn't possibly be able to get negative numbers. And in my char array...

525 = '\u000F' 15
526 = '�' 65533
527 = '\u000F' 15
528 = '�' 65533
529 = '\u000F' 15
530 = '�' 65533
531 = '\u000F' 15
532 = '\u0003' 3
533 = '\u0010' 16

Values that are only 15 in the char-array is sometimes -65 and sometimes 15 in the byte-array, and none of them look like the hexadecimals in the sublime file. I know the bytes/chars each represent two symbols in the sublime file, but... yeah.

I am honestly quite stumped. How do I properly read hexadecimal numbers from this file? Like how Sublime opens it?

Body:
I write a code that transforms one line of hex into array of integers so i think that this is what You want.
In shotrt - code takes one line of text from file with You presented on first photo and trim to hex values as one strin then splits in to array of Strings and decode for signed values of Integer and returns array of integers. I have tested ths code manualy so there is main() below. Sorry for languange byt hen You see time of this post You will Undestand :) - 01:00 AM :)

import java.util.Arrays;

    /**
     * Created by maciej.brzozowski.83@gmail.com on 2017-04-03 01:00AM.
     */
    public class hexDecoder {

        public  int[] decode(String inputString){
            inputString= inputString.substring(inputString.indexOf(" "));
            inputString= inputString.trim();
            String hexArray[] = inputString.split(" ");
            int[] intValuesOfHex = new int[hexArray.length];
            for (int i = 0; i <hexArray.length ; i++) {
              intValuesOfHex[i]=Integer.valueOf(hexArray[i],16);
              }

        return intValuesOfHex;
        }

        public static void main(String[] args) {
           String hexToDecode = "33  c60f cc0f d20f d80f de0f e407 ea0f f10f";
            System.out.println(Arrays.toString(new hexDecoder().decode(hexToDecode)));
        }

    }


问:
Big O Notation - O(nlog(n)) vs O(log(n^2))
Is the notation of NLog(N) the same as Log(N^2)? If so, why is it not written like that?

Is NLog(N) the standard notation? I feel like Log(N^2) is less confusing to see.

答:
O(log(n^2)) is simply O(2 log(n)) = O(log(n)). It is a logarithmic function. Its value is much smaller than the linear function O(n).

O(n log(n)) is a larger function. Its values are larger than the linear function O(n)

They are completely different functions (and different big-O complexities). O(n log(n)) is much larger than O(log(n^2))

This plot shows the difference:


问:
Epson printer connect fails status ERR_CONN
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

```<code>private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
</code>```

mPrinter.addFeedLine(2);

```<code>        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}
</code>```

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>
</code>```

答:
As I suspect there seems to be an error in connect printer method. I have used this SDK once so better follow the documentation properly (means don't skip steps). Make sure you have defined permission as mentioned in the SDK.

```<code><uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<activity android:name=".MainActivity" android:label="@string/app_title"  android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter"/>
</code>```

As I see you haven't mentioned what type of connection you are making thus, in that case, there must be problem in selecting target

Check out the function from SDK:

Public void connect(String target, int timeout) throws Epos2Exception;

You might be using wrong target parameter.

Note: if you are using USB or any other mode make sure run discoverability service as per the docs.

```<code> Discovery.start(this, mFilterOption, mDiscoveryListener);
</code>```

It will return you the required target name. And I am sure no connection failure will occur. Good Luck \o

Body:
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

mPrinter.addFeedLine(2);

        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>

Body:
As I suspect there seems to be an error in connect printer method. I have used this SDK once so better follow the documentation properly (means don't skip steps). Make sure you have defined permission as mentioned in the SDK.

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<activity android:name=".MainActivity" android:label="@string/app_title"  android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter"/>

As I see you haven't mentioned what type of connection you are making thus, in that case, there must be problem in selecting target

Check out the function from SDK:

Public void connect(String target, int timeout) throws Epos2Exception;

You might be using wrong target parameter.

Note: if you are using USB or any other mode make sure run discoverability service as per the docs.

 Discovery.start(this, mFilterOption, mDiscoveryListener);

It will return you the required target name. And I am sure no connection failure will occur. Good Luck \o


问:
Is there any way to combine Funcs into a Func has one more dimension?
I started to learn Halide from last month.
And finally encounterd big problem for me.

I'm trying to implement function like following C-like code in Halide.

```<code>for( int y = 0; y < 3; ++y ){
    for( int x = 0; x < 3; ++x ){
        out(x, y) = out(x-1, y-1) + 1;
    }
}
</code>```

so assuming initial image is below.

0 0 0

 0 0 0

 0 0 0

output image will be …(0 out of bound)

1 1 1

 1 2 2

 1 2 3

so I thought two possible solutions.

・Solution1

Define above algorithm like this recursive function.

```<code>Func algorithm1(Func input, int n)
{
    Func src, clamped, dst;
    Var x, y;

    if(n == 1){
            src = input;
    }else{
            src = algorithm1(input, n-1);
            src.compute_root();
    }

    clamped = BoundaryConditions::constant_exterior(src, 0, 0, SIZE, 0, SIZE);
    dst(x, y) = clamped(x-1, y-1) + 1;

    return dst;
}
</code>```

And use above function like following code.

```<code>Func input, output;
input(x, y) = src(x, y);
output = algorithm1(input, SIZE);
output.realize(src);
</code>```

This implementation barely works. But obviously rebundunt.
Because most of the computation result of the each stage(Func) are not match the final result although each Func computes across over entire image.
And I need to handle more large(normal) images.
So I thought another possible solution.

・Solution2

At first of second solution.

Declare a function defines relationship between one column and another one.

```<code>Func algorithm2(Func src)
{
    Func clamped, dst;
    Var x;

    clamped = BoundaryConditions::constant_exterior(src, 0, 0, SIZE);
    dst(x) = clamped(x-1) + 1;

    return dst;
}
</code>```

Then, let's combine this.

```<code>Func output[3];
output[0](x) = cast<uint32_t>(0);
for(int i = 1; i < SIZE; ++i){
    output[i] = algorithm2(output[i-1]);
}
</code>```

Alright... Here's the problem. How can I combine this array of Funcs as a Func?

Of cource, I can get an Image if I realize this array of Funcs at each func to an pointer of the column's head. But What if I want to pass it to the next Func?

I looked around entire Halide examples(test, apps) these days. But I think there's no similar example.
And you might already noticed my discomfort of English, actually I'm a japanese. So if there are useful example for this problem, I'm so sorry in advance. If so, please tell me where it is. If there's another good implementation idea, please teach me. Anyway I need someone's help!

I appreciate for your reading.

[edit 2]

edit 1 is my foolish question. I can schedule it compute_root().
I've decided to left them on here, really embarrassing though.
I hope this will be helpful to another foolish man.

[edit 1]

I'm appreciate to your fast and detailed response from bottom of my heart!

I'm sorry for late response, I wanted to reply to you after succeeding to implement my algorithm. However, my Halide code still doesn't work what I wanna do and got some things to confirm.

First off, I would like to tell you I realized my misunderstanding of Halide thanks to you. At first of my algorithm's implementation step, I wrote definition using only pure 'Var's.
So I got following error.

```<code>All of a functions recursive references to itself must contain the same pure variables in the same places as on the left-hand-side.
</code>```

I thought this error occured because of scheduling flexibility. If such definition is allowed and schedule it to split, It means that scheduling changes algorithm. This comprehension is correct? From such comprehension, although I already read reduction part of Tutorials and blur example, I misunderstood that I cannot access neighbor pixels in all of Func definitions. I don't know why though.

And reduction domain couldn't be split because of same reason. I think I got it now.

Here's another question to your code. Thanks to your Halide implementation example, I've almost succeeded to implement what I wanna do with no consideration. However, this implementation is desperately slow although I'm handling 20x20 cropped image for ease of debugging.

I'm considering this slowness is caused by reduction domain. In your example, for example when calculating the value g(10, 10), Halide calculation is scheduled from f(0, 0) to f(0, 0) and finally get there value. In the other hand, C implementation just loads the value at g(9, 9) and just increment it though. We can confirm such calculation from printing loop nest.

```<code>produce g:
  for y:
    for x:
      produce f:
        for y:
          for x:
            f(...) = ...
        for range:
          for range:
            f(...) = ...
      consume f:
        g(...) = ...
</code>```

I would like to confirm that Avoiding this recomputation is impossible? and so you suggested it?

And I would like to ask you another simple question. If there is reverse-dependency like this,

```<code>for( int y = 2; y > 0; --y ){
    for( int x = 2; x > 0; --x ){
        out(x, y) = out(x+1, y+1) + 1;
    }
}
</code>```

Is Halide able to express this code?

答:
The algorithm1 and algorithm2 parts here are not very clear to me. I understand the initial problem statement and the English seems fine so I will endeavor to provide some help answering the question I think you are asking. I'll do this by illustrating a few Halide mechanisms you may not know about or that aren't obvious for use here. Hopefully this will be helpful.

First off, to map a dimension of a Halide Func to different expressions, you pretty much have to use a select statement:

```<code>Var x, y, n;
Func f_0, f_1, f_both;
f_0(x, y) = ...;
f_1(x, y) = ...;
f_both(x, y, n) = select(n == 0, f_zero, f_one);
</code>```

This can be expanded to more cases via adding arguments to the select. This is more useful for piecewise computations than for recursive structures but seems the most direct answer to the question in the title.

The second mechanism is Tuple. This allows a Func to have more than one value, which can be indexed with compile time constants. I don't think this is the answer you are looking for, but i tis convered in tutorial/lesson_13_tuples.cpp .

Finally, Halide supports reductions, which are designed to handle the case in the first code example. This looks like so:

```<code>Var x, y;
Func f, g;
RDom range(0, 3, 0, 3); // Form is min/extent, not start/end

f(x, y) = 0; // Initial condition
f(range.x, range.y) = f(range.x - 1, range.y - 1) + 1;

g(x, y) = f(x, y);

Buffer<int32t> result = g.realize(3, 3);
</code>```

This should produce the output from your first example. Reductions, or "update definitions" are covered in tutorial/lesson_09_update_definitions.cpp .

Body:
I started to learn Halide from last month.
And finally encounterd big problem for me.

I'm trying to implement function like following C-like code in Halide.

for( int y = 0; y < 3; ++y ){
    for( int x = 0; x < 3; ++x ){
        out(x, y) = out(x-1, y-1) + 1;
    }
}

so assuming initial image is below.

0 0 0

 0 0 0

 0 0 0

output image will be …(0 out of bound)

1 1 1

 1 2 2

 1 2 3

so I thought two possible solutions.

・Solution1

Define above algorithm like this recursive function.

Func algorithm1(Func input, int n)
{
    Func src, clamped, dst;
    Var x, y;

    if(n == 1){
            src = input;
    }else{
            src = algorithm1(input, n-1);
            src.compute_root();
    }

    clamped = BoundaryConditions::constant_exterior(src, 0, 0, SIZE, 0, SIZE);
    dst(x, y) = clamped(x-1, y-1) + 1;

    return dst;
}

And use above function like following code.

Func input, output;
input(x, y) = src(x, y);
output = algorithm1(input, SIZE);
output.realize(src);

This implementation barely works. But obviously rebundunt.
Because most of the computation result of the each stage(Func) are not match the final result although each Func computes across over entire image.
And I need to handle more large(normal) images.
So I thought another possible solution.

・Solution2

At first of second solution.

Declare a function defines relationship between one column and another one.

Func algorithm2(Func src)
{
    Func clamped, dst;
    Var x;

    clamped = BoundaryConditions::constant_exterior(src, 0, 0, SIZE);
    dst(x) = clamped(x-1) + 1;

    return dst;
}

Then, let's combine this.

Func output[3];
output[0](x) = cast<uint32_t>(0);
for(int i = 1; i < SIZE; ++i){
    output[i] = algorithm2(output[i-1]);
}

Alright... Here's the problem. How can I combine this array of Funcs as a Func?

Of cource, I can get an Image if I realize this array of Funcs at each func to an pointer of the column's head. But What if I want to pass it to the next Func?

I looked around entire Halide examples(test, apps) these days. But I think there's no similar example.
And you might already noticed my discomfort of English, actually I'm a japanese. So if there are useful example for this problem, I'm so sorry in advance. If so, please tell me where it is. If there's another good implementation idea, please teach me. Anyway I need someone's help!

I appreciate for your reading.

[edit 2]

edit 1 is my foolish question. I can schedule it compute_root().
I've decided to left them on here, really embarrassing though.
I hope this will be helpful to another foolish man.

[edit 1]

I'm appreciate to your fast and detailed response from bottom of my heart!

I'm sorry for late response, I wanted to reply to you after succeeding to implement my algorithm. However, my Halide code still doesn't work what I wanna do and got some things to confirm.

First off, I would like to tell you I realized my misunderstanding of Halide thanks to you. At first of my algorithm's implementation step, I wrote definition using only pure 'Var's.
So I got following error.

All of a functions recursive references to itself must contain the same pure variables in the same places as on the left-hand-side.

I thought this error occured because of scheduling flexibility. If such definition is allowed and schedule it to split, It means that scheduling changes algorithm. This comprehension is correct? From such comprehension, although I already read reduction part of Tutorials and blur example, I misunderstood that I cannot access neighbor pixels in all of Func definitions. I don't know why though.

And reduction domain couldn't be split because of same reason. I think I got it now.

Here's another question to your code. Thanks to your Halide implementation example, I've almost succeeded to implement what I wanna do with no consideration. However, this implementation is desperately slow although I'm handling 20x20 cropped image for ease of debugging.

I'm considering this slowness is caused by reduction domain. In your example, for example when calculating the value g(10, 10), Halide calculation is scheduled from f(0, 0) to f(0, 0) and finally get there value. In the other hand, C implementation just loads the value at g(9, 9) and just increment it though. We can confirm such calculation from printing loop nest.

produce g:
  for y:
    for x:
      produce f:
        for y:
          for x:
            f(...) = ...
        for range:
          for range:
            f(...) = ...
      consume f:
        g(...) = ...

I would like to confirm that Avoiding this recomputation is impossible? and so you suggested it?

And I would like to ask you another simple question. If there is reverse-dependency like this,

for( int y = 2; y > 0; --y ){
    for( int x = 2; x > 0; --x ){
        out(x, y) = out(x+1, y+1) + 1;
    }
}

Is Halide able to express this code?

Body:
The algorithm1 and algorithm2 parts here are not very clear to me. I understand the initial problem statement and the English seems fine so I will endeavor to provide some help answering the question I think you are asking. I'll do this by illustrating a few Halide mechanisms you may not know about or that aren't obvious for use here. Hopefully this will be helpful.

First off, to map a dimension of a Halide Func to different expressions, you pretty much have to use a select statement:

Var x, y, n;
Func f_0, f_1, f_both;
f_0(x, y) = ...;
f_1(x, y) = ...;
f_both(x, y, n) = select(n == 0, f_zero, f_one);

This can be expanded to more cases via adding arguments to the select. This is more useful for piecewise computations than for recursive structures but seems the most direct answer to the question in the title.

The second mechanism is Tuple. This allows a Func to have more than one value, which can be indexed with compile time constants. I don't think this is the answer you are looking for, but i tis convered in tutorial/lesson_13_tuples.cpp .

Finally, Halide supports reductions, which are designed to handle the case in the first code example. This looks like so:

Var x, y;
Func f, g;
RDom range(0, 3, 0, 3); // Form is min/extent, not start/end

f(x, y) = 0; // Initial condition
f(range.x, range.y) = f(range.x - 1, range.y - 1) + 1;

g(x, y) = f(x, y);

Buffer<int32t> result = g.realize(3, 3);

This should produce the output from your first example. Reductions, or "update definitions" are covered in tutorial/lesson_09_update_definitions.cpp .


问:
Core data matched date in swift
I am using UITextField date picker to save date in Core Data.

On date picker sender i got the date in this format: 2017-04-02 14:56:41.

I want to convert it to this format 02 April 2017.

How can i do it? Below is my code:

```<code>     var scheduledPickDate: NSDate!

      @IBAction func scheduleDateTextFieldBeginEditing(_ sender: UITextField) {

            let datePickerView:UIDatePicker = UIDatePicker()

            datePickerView.minimumDate = NSDate() as Date

            datePickerView.datePickerMode = UIDatePickerMode.date

            sender.inputView = datePickerView

            datePickerView.addTarget(self, action: #selector(WalkIn.ScheduledDateChanged), for: UIControlEvents.valueChanged)
        }

      func ScheduledDateChanged(sender:UIDatePicker){

            let dateFormatter = DateFormatter()

            dateFormatter.dateStyle = DateFormatter.Style.long

            dateFormatter.timeStyle = DateFormatter.Style.none

            dateFormatter.dateFormat = "dd MMMM yyyy"

             //print(sender.date)

            scheduledPickDate = scheduledPickDate as NSDate!

            //print(scheduledPickDate)

            scheduledDateWalkinPatient.text = dateFormatter.string(from: sender.date)

        }

// on save function

 managedObj.setValue(scheduledPickDate, forKey: "dateSchedule") // 2017-04-02 14:56:41
</code>```

How can I convert var scheduledPickDate into this format 02 April 2017?

答:
You're already formatting the date with:

```<code>dateFormatter.string(from: sender.date)
</code>```

You just can't store in Coredata a date in the format you want (unless you're using a String as attribute). If then you need to retrieve that date and show it to the user, you need to format it again

Title: Core data matched date in swift

Body:
I am using UITextField date picker to save date in Core Data.

On date picker sender i got the date in this format: 2017-04-02 14:56:41.

I want to convert it to this format 02 April 2017.

How can i do it? Below is my code:

     var scheduledPickDate: NSDate!

      @IBAction func scheduleDateTextFieldBeginEditing(_ sender: UITextField) {

            let datePickerView:UIDatePicker = UIDatePicker()

            datePickerView.minimumDate = NSDate() as Date

            datePickerView.datePickerMode = UIDatePickerMode.date

            sender.inputView = datePickerView

            datePickerView.addTarget(self, action: #selector(WalkIn.ScheduledDateChanged), for: UIControlEvents.valueChanged)
        }

      func ScheduledDateChanged(sender:UIDatePicker){

            let dateFormatter = DateFormatter()

            dateFormatter.dateStyle = DateFormatter.Style.long

            dateFormatter.timeStyle = DateFormatter.Style.none

            dateFormatter.dateFormat = "dd MMMM yyyy"

             //print(sender.date)

            scheduledPickDate = scheduledPickDate as NSDate!

            //print(scheduledPickDate)

            scheduledDateWalkinPatient.text = dateFormatter.string(from: sender.date)

        }

// on save function

 managedObj.setValue(scheduledPickDate, forKey: "dateSchedule") // 2017-04-02 14:56:41

How can I convert var scheduledPickDate into this format 02 April 2017?

Body:
You're already formatting the date with:

dateFormatter.string(from: sender.date)

You just can't store in Coredata a date in the format you want (unless you're using a String as attribute). If then you need to retrieve that date and show it to the user, you need to format it again


问:
How to translate strings in JS
I have a project which I want to translate into multiple languages for the PHP Part I use Zend Frameworks Zend_Translate with GetText. Now I want to translate the JS part too.

I am using the jQuery JS Framework and would love to hear your thoughts on translation for JS files

答:
I have successfully used GetText for translation of JavaScript files in three projects.

Of course GetText natively doesn't support JavaScript and JavaScript also doesn't support GetText. My solution has been the following.

In JavaScript I surround translatable strings with gettext("your text here").

Then I have a script that pulls the strings out of JavaScript files and creates a C file, because C is supported by gettext.

Then I use xgettext on the generated C files and on any other files in my project to produce POT and PO files.

After translating PO files, I have to get the translations back to JavaScript...

I parse the JavaScript files again, remembering the list of translatable strings, then for every locale:

Using a language with GetText support (in my case PHP) I translate all the strings and output JavaScript file.

For example a locale file for Estonian (e.g. et_EE.js) might look like this:

```<code>var LOCALE = {
  "Hello": "Tere",
  "My name is %s": "Minu nimi on %s",
  "Enter your credit card number": "Sisesta oma krediitkaardi number"
};

function gettext(string) {
  return LOCALE[string] ? LOCALE[string] : string;
}
</code>```

Depending on the selected locale you either include et_EE.js or en_US.js or ...

en_US.js will probably contain just the following:

```<code>function gettext(string) {
  return string;
}
</code>```

A bit trickier for ngettext(), but you should get the general idea.

The great thing is that I can use all the gettext tools already available. Especially when I have translatable texts in both PHP and JavaScript - I can use the same tool for translating both of them and also ensure that the same string is translated the same way both in JavaScript and PHP.

NOTE: If you aren't dealing with a JavaScript-intensive web-app, you should think twice before having page content created by JavaScript in the first place.

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 2.5

Title: How to translate strings in JS

Body:
I have successfully used GetText for translation of JavaScript files in three projects.

Of course GetText natively doesn't support JavaScript and JavaScript also doesn't support GetText. My solution has been the following.

In JavaScript I surround translatable strings with gettext("your text here").

Then I have a script that pulls the strings out of JavaScript files and creates a C file, because C is supported by gettext.

Then I use xgettext on the generated C files and on any other files in my project to produce POT and PO files.

After translating PO files, I have to get the translations back to JavaScript...

I parse the JavaScript files again, remembering the list of translatable strings, then for every locale:

Using a language with GetText support (in my case PHP) I translate all the strings and output JavaScript file.

For example a locale file for Estonian (e.g. et_EE.js) might look like this:

var LOCALE = {
  "Hello": "Tere",
  "My name is %s": "Minu nimi on %s",
  "Enter your credit card number": "Sisesta oma krediitkaardi number"
};

function gettext(string) {
  return LOCALE[string] ? LOCALE[string] : string;
}

Depending on the selected locale you either include et_EE.js or en_US.js or ...

en_US.js will probably contain just the following:

function gettext(string) {
  return string;
}

A bit trickier for ngettext(), but you should get the general idea.

The great thing is that I can use all the gettext tools already available. Especially when I have translatable texts in both PHP and JavaScript - I can use the same tool for translating both of them and also ensure that the same string is translated the same way both in JavaScript and PHP.

NOTE: If you aren't dealing with a JavaScript-intensive web-app, you should think twice before having page content created by JavaScript in the first place.

OwnerDisplayName: Rene Saarsoo

LastEditorDisplayName: Rene Saarsoo


问:
Install Xcode 3.2.4, get "Base SDK Missing"
When you update Xcode to 3.2.4, your previously working Xcode iOS project gives you the message "Base SDK Missing". Something like this:

What gives? How to fix?

答: I ran into the same problems for 3.2.5 and followed the same instructions.  It didn't work for me, but I noticed that new projects would work properly.  When I grepped ShareKit.xcodeproj/project.pbxproj, I noticed that there were still stray references to iphoneos4.0 in the file for SDKROOT param even after changing it in xcode.  Manually editing this file and changing all references of SDKROOT to iphoneos fixed the problem.  Hope that helps someone.</p>

ContentLicense: CC BY-SA 4.0


问:
Auto Scrolling to Div
I have a button within an anchor tag in which when I click on the button, I want it to smoothly scroll to the div with the id "bodycontainer".

The problem is with the javascript I think, any ideas?

$(function(){
  $('.icon-menu').click(function() {
    $('.menu').animate({
      left: "0px"
    }, 200);

    $('body').animate({
      left: "285px"
    }, 200);
  });

  $('.icon-close').click(function() {
    $('.menu').animate({
      left: "-285px"
    }, 200);

    $('body').animate({
      left: "0px"
    }, 200);
  });

  $('#bodycontainer').click(function() {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top
      }, 1000);
      return false;
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Nunito', sans-serif;
  padding: 0;
  margin: 0;
  display: block;
}

head {
  font-family: 'Nunito', sans-serif;
  height: 0px;
  width: 0px;
  margin: 0;
}

#wrapper{
  overflow: auto;
}
.introcontainer {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: linear-gradient(rgba(0, 0, 0, .3), rgba(0, 0, 0, .3)),
    url("images/image.png") no-repeat;
  background-size: 100% auto;
}

#text {
  position: absolute;
  top: 30%;
  left: 35%;
  font-family: 'Nunito', sans-serif;
  text-align: center;
  color: white;
}

.introcontainer button {
  position: absolute;
  left: 22%;
  top: 100%;
  width: 250px;
  height: 47px;
  color: white;
  font-family: 'Nunito', sans-serif;
  font-size: 30px;
  text-align: center;
  text-decoration: none;
  background-color: Transparent;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
}

.introcontainer button:hover {
  background: rgba(255, 255, 255, 0.35);
}

.menu {
  font-family: 'Nunito', sans-serif;
  background: #202024 url('images/menu-background.png') repeat left top;
  left: -285px;
  height: 100%;
  position: fixed;
  width: 285px;
  font-size: 15px;
}

.menu ul {
  border-top: 1px solid #636366;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  border-bottom: 1px solid #636366;
  font-family: 'Open Sans', sans-serif;
  line-height: 45px;
  padding-bottom: 3px;
  padding-left: 20px;
  padding-top: 3px;
}

.menu a {
  color: #fff;
  font-size: 15px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-close {
  cursor: pointer;
  padding-left: 225px;
  padding-top: 10px;
}

.icon-menu {
  width: 75px;
  color: #fff;
  cursor: pointer;
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  padding-bottom: 25px;
  padding-left: 25px;
  padding-top: 25px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-menu i {
  margin-right: 5px;
  top: 20:
}

#bar {
  text-align: center;
}

#bodycontainer {
  position: absolute;
  top: 100vh;
  left: 0;
  height: 100vh;
  width: 100%;
  background: red;
}</code>```

<!Doctype html>

<meta charset="utf-8">

<title>J-Coding</title>
<meta name="author" content="John Murray">
<link href="https://fonts.googleapis.com/css?family=Nunito"
  rel="stylesheet">
<link rel="stylesheet" type="text/css" href="homepage-menu.css">

Home

About

Map

Contact

Hi, Welcome to J-Coding.

      My name is John.
 On my free time I like to fly my drone, code, and game.

      <button id="start">Lets get Started</button>

testing testing testing

```

答:
very much over complicated it,
JS should look like </p>

```<code>$('#start').click(function() {
    $('html,body').animate({
        scrollTop: $('#bodycontainer').position().top
    }, 1000 );

});
</code>```

Title: Auto Scrolling to Div

Body:
I have a button within an anchor tag in which when I click on the button, I want it to smoothly scroll to the div with the id "bodycontainer".

The problem is with the javascript I think, any ideas?

$(function(){
  $('.icon-menu').click(function() {
    $('.menu').animate({
      left: "0px"
    }, 200);

    $('body').animate({
      left: "285px"
    }, 200);
  });

  $('.icon-close').click(function() {
    $('.menu').animate({
      left: "-285px"
    }, 200);

    $('body').animate({
      left: "0px"
    }, 200);
  });

  $('#bodycontainer').click(function() {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top
      }, 1000);
      return false;
    }
  });
});

body {
  font-family: 'Nunito', sans-serif;
  padding: 0;
  margin: 0;
  display: block;
}

head {
  font-family: 'Nunito', sans-serif;
  height: 0px;
  width: 0px;
  margin: 0;
}

#wrapper{
  overflow: auto;
}
.introcontainer {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: linear-gradient(rgba(0, 0, 0, .3), rgba(0, 0, 0, .3)),
    url("images/image.png") no-repeat;
  background-size: 100% auto;
}

#text {
  position: absolute;
  top: 30%;
  left: 35%;
  font-family: 'Nunito', sans-serif;
  text-align: center;
  color: white;
}

.introcontainer button {
  position: absolute;
  left: 22%;
  top: 100%;
  width: 250px;
  height: 47px;
  color: white;
  font-family: 'Nunito', sans-serif;
  font-size: 30px;
  text-align: center;
  text-decoration: none;
  background-color: Transparent;
  -webkit-transition-duration: 0.6s;
  transition-duration: 0.6s;
  cursor: pointer;
}

.introcontainer button:hover {
  background: rgba(255, 255, 255, 0.35);
}

.menu {
  font-family: 'Nunito', sans-serif;
  background: #202024 url('images/menu-background.png') repeat left top;
  left: -285px;
  height: 100%;
  position: fixed;
  width: 285px;
  font-size: 15px;
}

.menu ul {
  border-top: 1px solid #636366;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  border-bottom: 1px solid #636366;
  font-family: 'Open Sans', sans-serif;
  line-height: 45px;
  padding-bottom: 3px;
  padding-left: 20px;
  padding-top: 3px;
}

.menu a {
  color: #fff;
  font-size: 15px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-close {
  cursor: pointer;
  padding-left: 225px;
  padding-top: 10px;
}

.icon-menu {
  width: 75px;
  color: #fff;
  cursor: pointer;
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  padding-bottom: 25px;
  padding-left: 25px;
  padding-top: 25px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-menu i {
  margin-right: 5px;
  top: 20:
}

#bar {
  text-align: center;
}

#bodycontainer {
  position: absolute;
  top: 100vh;
  left: 0;
  height: 100vh;
  width: 100%;
  background: red;
}

<!Doctype html>

<meta charset="utf-8">

<title>J-Coding</title>
<meta name="author" content="John Murray">
<link href="https://fonts.googleapis.com/css?family=Nunito"
  rel="stylesheet">
<link rel="stylesheet" type="text/css" href="homepage-menu.css">

Home

About

Map

Contact

Hi, Welcome to J-Coding.

      My name is John.
 On my free time I like to fly my drone, code, and game.

      <button id="start">Lets get Started</button>

testing testing testing

Body:
very much over complicated it,
JS should look like

$('#start').click(function() {
    $('html,body').animate({
        scrollTop: $('#bodycontainer').position().top
    }, 1000 );

});


问:
Python - Bytes impicity converted to int when iterating in zip()
My bytes is getting converted to an int but I don't know exactly where?

Take this example

```<code>Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32

>>> a = 'a'
>>> b = b'b'
>>> type(b)
<class 'bytes'>
>>> z = zip(a,b)
>>> type(b)
<class 'bytes'>
>>> for a,b in z:
    print(type(a),type(b))
<class 'str'> <class 'int'>
>>> type(b)
<class 'int'>
</code>```

I guess this is some kind of coercion but what triggers it? is doesn't appear to be using the zip iterator? as calling z.__next__() does not cause the conversion.

Thanks

答:
The documentation (here) says a bytes is a sequence of integers. Further down the documentation of zip (here) says, that zip iterates over sequences. That is why b becomes of type int.

You can see that by doing the following:

```<code>>>> b = b'b'
>>> for i in b:
...    print(type(i), i)
<class 'int'> 98
</code>```

Notice please, that by using a and b as loop variables you overwrite the original a and b.

Body:
My bytes is getting converted to an int but I don't know exactly where?

Take this example

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32

>>> a = 'a'
>>> b = b'b'
>>> type(b)
<class 'bytes'>
>>> z = zip(a,b)
>>> type(b)
<class 'bytes'>
>>> for a,b in z:
    print(type(a),type(b))
<class 'str'> <class 'int'>
>>> type(b)
<class 'int'>

I guess this is some kind of coercion but what triggers it? is doesn't appear to be using the zip iterator? as calling z.__next__() does not cause the conversion.

Thanks

Body:
The documentation (here) says a bytes is a sequence of integers. Further down the documentation of zip (here) says, that zip iterates over sequences. That is why b becomes of type int.

You can see that by doing the following:

>>> b = b'b'
>>> for i in b:
...    print(type(i), i)
<class 'int'> 98

Notice please, that by using a and b as loop variables you overwrite the original a and b.


问:
upgrading php 5.6.3 to 5.6.4 or higher (branch 5.6)
I have a Centos 7, with a php 5.6.3 installed on it.

```<code>php -v
PHP 5.6.30 (cli) (built: Jan 19 2017 07:08:58)
</code>```

Now I want to install an open source project that requires minimum php version 5.6.4.

```<code>(*) PHP 5.6.0 - 5.6.3 are not compatible caused by a session bug
</code>```

How can I do the upgrade?
I tried many howto's found with google, but none of them work. For example:
https://www.centos.org/forums/viewtopic.php?t=52586
Of course I have the latest (I think) repos:

package webtatic-release-7-3.noarch is already installed

package epel-release-7-9.noarch already installed and latest version

When I run

```<code>yum update php
</code>```

I get:

```<code>...
Package(s) php available, but not installed.
No packages marked for update
</code>```

or:

```<code>yum -y upgrade php*
</code>```

I get:

```<code>Loaded plugins: fastestmirror, replace
Loading mirror speeds from cached hostfile
 * base: mirrors.hostingfuze.net
 * extras: centos.mirrors.telekom.ro
 * ius: ftp.astral.ro
 * remi-safe: mirrors.neterra.net
 * updates: centos.mirrors.telekom.ro
No packages marked for update
</code>```

So basically my question is: how can I install the PHP 5.6.4 or higher on my system that already has PHP 5.6.3

答: As seen in the changelog, 5.6.30 is (as of today) the newest version of the 5.6 branch, 5.6.4 came out December 2014.

Body:
I have a Centos 7, with a php 5.6.3 installed on it.

php -v
PHP 5.6.30 (cli) (built: Jan 19 2017 07:08:58)

Now I want to install an open source project that requires minimum php version 5.6.4.

(*) PHP 5.6.0 - 5.6.3 are not compatible caused by a session bug

How can I do the upgrade?
I tried many howto's found with google, but none of them work. For example:
https://www.centos.org/forums/viewtopic.php?t=52586
Of course I have the latest (I think) repos:

package webtatic-release-7-3.noarch is already installed

package epel-release-7-9.noarch already installed and latest version

When I run

yum update php

I get:

...
Package(s) php available, but not installed.
No packages marked for update

or:

yum -y upgrade php*

I get:

Loaded plugins: fastestmirror, replace
Loading mirror speeds from cached hostfile
 * base: mirrors.hostingfuze.net
 * extras: centos.mirrors.telekom.ro
 * ius: ftp.astral.ro
 * remi-safe: mirrors.neterra.net
 * updates: centos.mirrors.telekom.ro
No packages marked for update

So basically my question is: how can I install the PHP 5.6.4 or higher on my system that already has PHP 5.6.3


问:
Java JFrame/Swing alignment
I'm new and learning JFrame currently and I'm running into a problem with the alignment of my ComboBox, checkboxes and buttons. The listeners are not hooked up yet and this is just a test to see if it's aligned properly. My question is why doesn't the alignment function seem to be working? I want the combo box to be at the top the checkboxes in the middle and the buttons on the bottom.

```<code>import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;

public class CheckBoxFrame extends JFrame
{

private final JComboBox<String> colorComboBox;
private final JCheckBox backgroundColorCheckBox;
private final JCheckBox foregroundColorCheckBox;
private final JButton okButton;
private final JButton cancelButton;

private static final String[] color =
{"Red", "Blue", "Green", "Purple"};

public CheckBoxFrame()
{
  super("ColorSelect");
  setLayout(new FlowLayout());

  colorComboBox = new JComboBox<String>(color);
  colorComboBox.setAlignmentX(SwingConstants.TOP);
  add(colorComboBox);

  backgroundColorCheckBox = new JCheckBox("Background");
  foregroundColorCheckBox = new JCheckBox("Foreground");
  foregroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  backgroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  add(backgroundColorCheckBox); // add bold checkbox to JFrame
  add(foregroundColorCheckBox); // add italic checkbox to JFrame

  okButton = new JButton("Ok");
  cancelButton = new JButton("Cancel");
  okButton.setVerticalAlignment(SwingConstants.BOTTOM);
  cancelButton.setVerticalAlignment(SwingConstants.BOTTOM);
  add(okButton);
  add(cancelButton);

  // register listeners for JCheckBoxes
  CheckBoxHandler handler = new CheckBoxHandler();
  backgroundColorCheckBox.addItemListener(handler);
  foregroundColorCheckBox.addItemListener(handler);
  }

private class CheckBoxHandler implements ItemListener
{
  // respond to checkbox events
  @Override
  public void itemStateChanged(ItemEvent event)
  {

  }
 }
} // end class CheckBoxFrame
</code>```

答:
Refer to the official docs on Layout Managers for Java Swing: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html.

FlowLayout is one of the more basic Layout Managers so I would suggest looking into the GridBagLayout.

Try this:

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;

public class CheckBoxFrame extends JFrame
{

private final JComboBox<String> colorComboBox;
private final JCheckBox backgroundColorCheckBox;
private final JCheckBox foregroundColorCheckBox;
private final JButton okButton;
private final JButton cancelButton;

private static final String[] color = {"Red", "Blue", "Green", "Purple"};

public CheckBoxFrame()
{
  super("ColorSelect");
  setLayout(new GridBagLayout());

  GridBagConstraints c = new GridBagConstraints();
  colorComboBox = new JComboBox<String>(color);
  c.fill = GridBagConstraints.HORIZONTAL;
  c.gridx = 0;
  c.gridy = 0;
  c.gridwidth = 2;
  add(colorComboBox, c);

  backgroundColorCheckBox = new JCheckBox("Background");
  c.fill = GridBagConstraints.HORIZONTAL;
  c.gridx = 0;
  c.gridy = 1;
  c.gridwidth = 1;
  add(backgroundColorCheckBox, c); // add bold checkbox to JFrame

  foregroundColorCheckBox = new JCheckBox("Foreground");
  c.fill = GridBagConstraints.HORIZONTAL;
  c.gridx = 1;
  c.gridy = 1;
  c.gridwidth = 1;
  add(foregroundColorCheckBox, c); // add italic checkbox to JFrame

  okButton = new JButton("Ok");
  c.fill = GridBagConstraints.HORIZONTAL;
  c.gridx = 0;
  c.gridy = 2;
  c.gridwidth = 1;
  add(okButton, c);

  cancelButton = new JButton("Cancel");
  c.fill = GridBagConstraints.HORIZONTAL;
  c.gridx = 1;
  c.gridy = 2;
  c.gridwidth = 1;
  add(cancelButton, c);

  // register listeners for JCheckBoxes
  CheckBoxHandler handler = new CheckBoxHandler();
  backgroundColorCheckBox.addItemListener(handler);
  foregroundColorCheckBox.addItemListener(handler);
  }

private class CheckBoxHandler implements ItemListener
{
  // respond to checkbox events
  @Override
  public void itemStateChanged(ItemEvent event)
  {

  }
 }
} // end class CheckBoxFrame
```

Title: Java JFrame/Swing alignment

Body:
I'm new and learning JFrame currently and I'm running into a problem with the alignment of my ComboBox, checkboxes and buttons. The listeners are not hooked up yet and this is just a test to see if it's aligned properly. My question is why doesn't the alignment function seem to be working? I want the combo box to be at the top the checkboxes in the middle and the buttons on the bottom.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;

public class CheckBoxFrame extends JFrame
{

private final JComboBox<String> colorComboBox;
private final JCheckBox backgroundColorCheckBox;
private final JCheckBox foregroundColorCheckBox;
private final JButton okButton;
private final JButton cancelButton;

private static final String[] color =
{"Red", "Blue", "Green", "Purple"};

public CheckBoxFrame()
{
  super("ColorSelect");
  setLayout(new FlowLayout());

  colorComboBox = new JComboBox<String>(color);
  colorComboBox.setAlignmentX(SwingConstants.TOP);
  add(colorComboBox);

  backgroundColorCheckBox = new JCheckBox("Background");
  foregroundColorCheckBox = new JCheckBox("Foreground");
  foregroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  backgroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  add(backgroundColorCheckBox); // add bold checkbox to JFrame
  add(foregroundColorCheckBox); // add italic checkbox to JFrame

  okButton = new JButton("Ok");
  cancelButton = new JButton("Cancel");
  okButton.setVerticalAlignment(SwingConstants.BOTTOM);
  cancelButton.setVerticalAlignment(SwingConstants.BOTTOM);
  add(okButton);
  add(cancelButton);

  // register listeners for JCheckBoxes
  CheckBoxHandler handler = new CheckBoxHandler();
  backgroundColorCheckBox.addItemListener(handler);
  foregroundColorCheckBox.addItemListener(handler);
  }

private class CheckBoxHandler implements ItemListener
{
  // respond to checkbox events
  @Override
  public void itemStateChanged(ItemEvent event)
  {

  }
 }
} // end class CheckBoxFrame


问:
Footer content not showing in mobile view
still very new to this so apologies in advance.

In my footer, the desktop view works fine. As does the landscape mobile view. Heres how it looks on  those two views

Landscape views

But in mobile portrait, the social media icons are missing, where have i gone wrong?

Portrait View

HTML code for my footer

```<code><footer class="nav navbar-fixed-bottom navbar-default">
                <div class="container-fluid">
                    <p>© 2017 Example Example</p>
                    <ul>
                        <li><a href=""><span class="fa fa-twitter"></span></a></li>
                        <li><a href=""><span class="fa fa-facebook"></span></a></li>
                        <li><a href=""><span class="fa fa-instagram"></span></a></li>
                        <li><a href=""><span class="fa fa-snapchat"></span></a></li>
                        <li><a href=""><span class="fa fa-youtube"></span></a></li>
                    </ul>
                </div>
            </footer>
</code>```

CSS for footer styling

```<code>footer {
    background-color: #000000;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
}

footer p {
    float: left;
    text-align: center;
    margin-top: 15px;
}

footer ul {
    list-style: none;
    display: flex;
    flex: 1;
    flex-direction: row;
    float: right;
    font-size:35px;
    margin-top: 2px;
}

.fa-twitter {
    margin-right:10px;
    color: #fff;
}

.fa-twitter:hover{
    color: #00aced;
}

.fa-facebook {
    margin-right:10px;
    color: #fff;
}

.fa-facebook:hover{
    color: #3b5998;
}

.fa-instagram {
    margin-right:10px;
    color: #fff;
}

.fa-instagram:hover{

    background-image: linear-gradient(45deg, #fccc63, #fbad50, #e95950, #cd486b, #8a3ab9, #4c68d7);
    color: transparent;
    background-clip: text;
    -webkit-background-clip: text;
}

.fa-snapchat {
    margin-right:10px;
    color: #fff;
}

.fa-snapchat:hover{
    color: #fffc00;
}

.fa-youtube {
    margin-right:5px;
    color: #fff;
}

.fa-youtube:hover{
    color: #cb2027;
}
</code>```

Any help would be appreciated!

答: Most likely the ulwith the social icons simply doesn't fit into the width of the footer next to the text of the p tag and is pushed below into a new line (both are floated). But since the height is fixed (50px), it's hidden. Try to change the height of footer to sonething like 100px for testing, then you'll see if this is what's happening. If yes, you have to make everything a little bit smaller (within a media query) so that it can fit into one line.

Body:
still very new to this so apologies in advance.

In my footer, the desktop view works fine. As does the landscape mobile view. Heres how it looks on  those two views

Landscape views

But in mobile portrait, the social media icons are missing, where have i gone wrong?

Portrait View

HTML code for my footer

© 2017 Example Example

CSS for footer styling

footer {
    background-color: #000000;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
}

footer p {
    float: left;
    text-align: center;
    margin-top: 15px;
}

footer ul {
    list-style: none;
    display: flex;
    flex: 1;
    flex-direction: row;
    float: right;
    font-size:35px;
    margin-top: 2px;
}

.fa-twitter {
    margin-right:10px;
    color: #fff;
}

.fa-twitter:hover{
    color: #00aced;
}

.fa-facebook {
    margin-right:10px;
    color: #fff;
}

.fa-facebook:hover{
    color: #3b5998;
}

.fa-instagram {
    margin-right:10px;
    color: #fff;
}

.fa-instagram:hover{

    background-image: linear-gradient(45deg, #fccc63, #fbad50, #e95950, #cd486b, #8a3ab9, #4c68d7);
    color: transparent;
    background-clip: text;
    -webkit-background-clip: text;
}

.fa-snapchat {
    margin-right:10px;
    color: #fff;
}

.fa-snapchat:hover{
    color: #fffc00;
}

.fa-youtube {
    margin-right:5px;
    color: #fff;
}

.fa-youtube:hover{
    color: #cb2027;
}

Any help would be appreciated!


问:
FindByValue on ASP.NET DropDownList
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

```<code>public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}
</code>```

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}
</code>```

答:
The following code currently works, however I think it's a bit strange to DataBind twice. This confirms my earlier suspicion that the data was being binded AFTER FindByValue()?

Anyone have any ideas on how to clean this code up?

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindDdlAggerationUnitId();
    }
}

private void BindDdlAggerationUnitId()
{
    ddlAggerationUnitId.DataSource = SIGOpsGUI.App_Code.Business.ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        BindDdlAggerationUnitId();
        ddlAggerationUnitId.SelectedIndex = -1;
        ListItem item = ddlAggerationUnitId.Items.FindByValue(value.ToString());
        if (item != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}
</code>```

Title: FindByValue on ASP.NET DropDownList

Body:
I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}

Any help would be greatly appreciated! Thanks!

EDIT: Here is my Page_Load() event:

protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

Body:
The following code currently works, however I think it's a bit strange to DataBind twice. This confirms my earlier suspicion that the data was being binded AFTER FindByValue()?

Anyone have any ideas on how to clean this code up?

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindDdlAggerationUnitId();
    }
}

private void BindDdlAggerationUnitId()
{
    ddlAggerationUnitId.DataSource = SIGOpsGUI.App_Code.Business.ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        BindDdlAggerationUnitId();
        ddlAggerationUnitId.SelectedIndex = -1;
        ListItem item = ddlAggerationUnitId.Items.FindByValue(value.ToString());
        if (item != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}


答:
Your issue is that your social icons are too big, so the entire
 is wrapping to the next line, but since you have a defined height on the  it falls outside of the viewport. Try making your icons smaller, or maybe do something to your
 to have its text wrap two lines in a narrower width.

Title: Footer content not showing in mobile view

Body: Your issue is that your social icons are too big, so the entire <ul> is wrapping to the next line, but since you have a defined height on the <footer> it falls outside of the viewport. Try making your icons smaller, or maybe do something to your <p> to have its text wrap two lines in a narrower width.


问:
Bootstrap: centering content in Nav and changing default beavior on smaller screens
I have tried adding floats and using some Bootstrap classes to try and get it to work to no avail. Not sure what I'm missing. I would like to make the ul or all the items centered. Below is the nav markup:

http://jsfiddle.net/bdd9U/1489/

```<code><div class="container">
    <nav class="navbar navbar-default" role="navigation">
        <ul class="nav navbar-nav">
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
        </ul>
    </nav>
    <h1>Home</h1>
</div>
</code>```

Also, on smaller screens, the nav's default behavior is to stack on top of each other. I wanted to make it so that the active link is the only one shown (or maybe with another link), but it can be scrolled horizontally for the other links. I am planning on using Scrollspy so active links are updated automatically if that makes a difference. Not sure how to approach that - any ideas would be appreciated.

答:
i'd recommend using 'bootstrap navbar example'(http://getbootstrap.com/components/#navbar). Specifically, in your situation i'd use this modified version:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                  </button>
                  Brand

Link (current)

Link

Link

```

Body:
I have tried adding floats and using some Bootstrap classes to try and get it to work to no avail. Not sure what I'm missing. I would like to make the ul or all the items centered. Below is the nav markup:

http://jsfiddle.net/bdd9U/1489/

Link

Link

Link

Link

Home

Also, on smaller screens, the nav's default behavior is to stack on top of each other. I wanted to make it so that the active link is the only one shown (or maybe with another link), but it can be scrolled horizontally for the other links. I am planning on using Scrollspy so active links are updated automatically if that makes a difference. Not sure how to approach that - any ideas would be appreciated.

Body:
i'd recommend using 'bootstrap navbar example'(http://getbootstrap.com/components/#navbar). Specifically, in your situation i'd use this modified version:

<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>
  <body>
      <nav class="navbar navbar-default">
          <div class="container-fluid">
              <div class="navbar-header">
                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                  </button>
                  <a class="navbar-brand" href="#">Brand</a>
              </div>
              <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
                  <li><a href="#">Link</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                  <li><a href="#">Link</a></li>
                </ul>
              </div><!-- /.navbar-collapse -->
          </div><!-- /.container-fluid -->
      </nav>
  </body>
</html>


问:
i want to compare a time input from user to make sure its in the right format in python
I am writing a program that accepts time input from the user in am/pm format. I want to make sure if the user enters something else, it would bring out an error and not just crash the program.
what I am saying is this, the user must enter the time in HH:MM am/pm format. e.g "2:00 pm" or "11:00 am" and any other thing else calls for an error.

The best I could do is

```<code>print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers  e.g 3 ==> 03" )
while True:
   start = input("At what is the start time?: ")
   end = input("At what is the end time?: ")
   if len(start) != 8:
      print("error! wrong value/format entered as the start time")
   elif len(end) != 8:
      print("error! wrong value/format entered as the end time")
   else:
      break
</code>```

答:
Here's two ways of doing it, I personally prefer the Date Conversion Method.

Date Conversion Method

I would check if I can convert them to a date Python object.  I used %H:%M %p, it goes hour:minute am/pm (as your prompt specifies).

```<code>import time
print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers  e.g 3 ==> 03" )
while True:
  start = input("At what is the start time?: ")
  end = input("At what is the end time?: ")

  try:
      time.strptime(start,'%H:%M %p')
      time.strptime(end,'%H:%M %p')
      print("Good Strings")
  except:
      print("Bad Strings")
</code>```

Regex Method

I'd use the following regex:

```<code>r"^(?:1?[012]|[0-9]):[0-5][0-9]\s*(?:am|pm)$"i
</code>```

Here's a Regex101:

https://regex101.com/r/Z1YMap/2

Body:
I am writing a program that accepts time input from the user in am/pm format. I want to make sure if the user enters something else, it would bring out an error and not just crash the program.
what I am saying is this, the user must enter the time in HH:MM am/pm format. e.g "2:00 pm" or "11:00 am" and any other thing else calls for an error.

The best I could do is

print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers  e.g 3 ==> 03" )
while True:
   start = input("At what is the start time?: ")
   end = input("At what is the end time?: ")
   if len(start) != 8:
      print("error! wrong value/format entered as the start time")
   elif len(end) != 8:
      print("error! wrong value/format entered as the end time")
   else:
      break

Body:
Here's two ways of doing it, I personally prefer the Date Conversion Method.

Date Conversion Method

I would check if I can convert them to a date Python object.  I used %H:%M %p, it goes hour:minute am/pm (as your prompt specifies).

import time
print("Make all inputs using the format 'hh:mm am/pm' e.g 10:00 am ... and add 0 before single numbers  e.g 3 ==> 03" )
while True:
  start = input("At what is the start time?: ")
  end = input("At what is the end time?: ")

  try:
      time.strptime(start,'%H:%M %p')
      time.strptime(end,'%H:%M %p')
      print("Good Strings")
  except:
      print("Bad Strings")

Regex Method

I'd use the following regex:

r"^(?:1?[012]|[0-9]):[0-5][0-9]\s*(?:am|pm)$"i

Here's a Regex101:

https://regex101.com/r/Z1YMap/2


问:
Avoid object with null fields using Jackson
If I try to deserialize a JSON string that is missing a field from the object class, that field is set to null when the object is created. I need Jackson to throw an exception when this happens so I don't have to implement an assertNotNullFields() method in every object; i.e the JSON string input must have defined all the fields in the class or a JsonProcessingException is thrown.

Object mapper configuration:

```<code>objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
</code>```

JSON object:

```<code>public class LogInUser {
    public String identifier, password;
    public LogInUser() {}
}
</code>```

Is this possible given my configuration?

答:
You could try using JsonCreator within your LogInUser class as mentioned here. When introduced into the code you posed in your quesion, it would look something like this:

```<code>public class LogInUser {

    @JsonCreator
    public LogInUser(@JsonProperty(value = "identifier", required = true) String identifier, @JsonProperty(value = "password", required = true) String password) {
    this.identifier = identifier;
    this.password = password;
    }

    public String identifier, password;
    public LogInUser() {}

}
</code>```

When one or more of the values are null, it should throw an exception.

Body:
If I try to deserialize a JSON string that is missing a field from the object class, that field is set to null when the object is created. I need Jackson to throw an exception when this happens so I don't have to implement an assertNotNullFields() method in every object; i.e the JSON string input must have defined all the fields in the class or a JsonProcessingException is thrown.

Object mapper configuration:

objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

JSON object:

public class LogInUser {
    public String identifier, password;
    public LogInUser() {}
}

Is this possible given my configuration?

Body:
You could try using JsonCreator within your LogInUser class as mentioned here. When introduced into the code you posed in your quesion, it would look something like this:

public class LogInUser {

    @JsonCreator
    public LogInUser(@JsonProperty(value = "identifier", required = true) String identifier, @JsonProperty(value = "password", required = true) String password) {
    this.identifier = identifier;
    this.password = password;
    }

    public String identifier, password;
    public LogInUser() {}

}

When one or more of the values are null, it should throw an exception.


问:
MSG_READALL is to recv() as ?? is to send()
From the recv(2) man page:

MSG_WAITALL

This flag requests that the operation block until the full request is satisfied. However, the call may still return less data than requested if a signal is caught, an error or disconnect occurs, or the next data to be received is of a different type than that returned.

It doesn't look like there's an equivalent flag for send(2), which strikes me as strange.  Maybe send()s are guaranteed to always accept the whole buffer, but I don't see that written anywhere (and anyway, that seems unlikely to me).

Is there a way to tell send() to wait until it's sent the whole buffer before returning, equivalently to recv()'s MSG_WAITALL?

Edit: I understand that send() just copies data into a buffer in the operating system and that I can't force send() to put data onto the wire.  My question is: Can I force send() to block until all the data I gave it has been copied into the OS's buffer?

答:
send(2) for TCP does not actually "send" anything on the wire, but places your bytes into the socket send buffer. It tells you how many bytes it was able to copy there in the return value.

Make the send buffer bigger (see setsockopt(2) and tcp(7)), pay attention to the syscall return value. In any case, TCP is a stream. You need to manage application-level protocol yourself.


问:
Get very specific url
I want to get very specific string over my url to add as parameter in js:

```<code> function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
            completado,
            fallo);
        }
</code>```

URL

```<code>http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb
</code>```

I want to get only Guid afrer Token= like:

```<code>e12009cf-d48d-42e7-ba43-83b5082019bb
</code>```

I try using:

```<code>   var url = (location.pathname + location.search).substr(1);
    function cambiarContrasena(usuario, completado, fallo) {
        apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
        completado,
        fallo);
    }
</code>```

But I get

```<code>http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/
</code>```

I try too:

```<code>var guid = url.substr(url.indexOf('Token=') + 6);
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
            completado,
            fallo);
        }
</code>```

But I get

Uncaught ReferenceError: url is not defined

What I need to do to get only parameters after Token= ?

I try as this question:

```<code> function getParameterByName(name, url) {
            if (!url) {
                url = window.location.href;
            }
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
            completado,
            fallo);
        }
</code>```

But I get an error:

POST
  http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
  400 (Bad Request)

答:
just try this :</p>

```<code>var url = window.location.hash.split('?Token=')[1];
var guid = url || '';
</code>```

Title: Get very specific url

Body:
I want to get very specific string over my url to add as parameter in js:

 function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
            completado,
            fallo);
        }

URL

http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb

I want to get only Guid afrer Token= like:

e12009cf-d48d-42e7-ba43-83b5082019bb

I try using:

   var url = (location.pathname + location.search).substr(1);
    function cambiarContrasena(usuario, completado, fallo) {
        apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
        completado,
        fallo);
    }

But I get

http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/

I try too:

var guid = url.substr(url.indexOf('Token=') + 6);
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
            completado,
            fallo);
        }

But I get

Uncaught ReferenceError: url is not defined

What I need to do to get only parameters after Token= ?

I try as this question:

 function getParameterByName(name, url) {
            if (!url) {
                url = window.location.href;
            }
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
        function cambiarContrasena(usuario, completado, fallo) {
            apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
            completado,
            fallo);
        }

But I get an error:

POST
  http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
  400 (Bad Request)

Body:
just try this :

var url = window.location.hash.split('?Token=')[1];
var guid = url || '';


问:
How to reformat a text file - awk
I have a text file containing 3 columns:

broke   banana    192

  broke   apple    175

  broke   avocado   20

  fixed   banana    117

  fixed   apple    89

I need the output below:

Issue,banana,apple,avocado

    broke,192,175,20

    fixed,117,90,0

I am new to this and have no idea how to get this result.

I appreciate any help,
Thanks

答:
```<code>$ cat tst.awk
BEGIN { OFS="," }
{
    states[$1]
    fruits[$2]
    count[$1,$2] += $NF
}
END {
    printf "%s", "Issue"
    for (fruit in fruits) {
        printf "%s%s", OFS, fruit
    }
    print ""

    for (state in states) {
        printf "%s", state
        for (fruit in fruits) {
            printf "%s%s", OFS, count[state,fruit]+0
        }
        print ""
    }
}

$ awk -f tst.awk file
Issue,apple,banana,avocado
fixed,89,117,0
broke,175,192,20
</code>```

Title: How to reformat a text file - awk


问:
Python Sqlite UPDATE multiple values
Is there a way to do these two updates in a single instruction?

```<code>cur.execute("UPDATE table_name1 SET email = 'foo@bar.com' WHERE id = 4")
cur.execute("UPDATE table_name1 SET phone = '0400-123-456' WHERE id = 4")
</code>```

I've tried all sort of variations but can't get it to work.

Edit: I want to pass email, phone and I'd as parameters.

答:
The following works:   Its just standard SQL at this point. </p>

```<code>cur.execute("""UPDATE table_name1
            SET email = 'foo@bar.com', phone = '0400-123-456'
            WHERE id = 4""")
</code>```

Title: Python Sqlite UPDATE multiple values

Body:
Is there a way to do these two updates in a single instruction?

cur.execute("UPDATE table_name1 SET email = 'foo@bar.com' WHERE id = 4")
cur.execute("UPDATE table_name1 SET phone = '0400-123-456' WHERE id = 4")

I've tried all sort of variations but can't get it to work.

Edit: I want to pass email, phone and I'd as parameters.

Body:
The following works:   Its just standard SQL at this point.

cur.execute("""UPDATE table_name1
            SET email = 'foo@bar.com', phone = '0400-123-456'
            WHERE id = 4""")


问:
When is the thread pool used?
So I have an understanding of how Node.js works: it has a single listener thread that receives an event and then delegates it to a worker pool. The worker thread notifies the listener once it completes the work, and the listener then returns the response to the caller.

My question is this: if I stand up an HTTP server in Node.js and call sleep on one of my routed path events (such as "/test/sleep"), the whole system comes to a halt. Even the single listener thread. But my understanding was that this code is happening on the worker pool.

Now, by contrast, when I use Mongoose to talk to MongoDB, DB reads are an expensive I/O operation. Node seems to be able to delegate the work to a thread and receive the callback when it completes; the time taken to load from the DB does not seem to block the system.

How does Node.js decide to use a thread pool thread vs the listener thread? Why can't I write event code that sleeps and only blocks a thread pool thread?

答:
This misunderstanding is merely the difference between pre-emptive multi-tasking and cooperative multitasking...

The sleep turns off the entire carnival because there is really one line to all the rides, and you closed the gate.  Think of it as "a JS interpreter and some other things" and ignore the threads...for you, there is only one thread, ...

...so don't block it.

Title: When is the thread pool used?