问:
Client player not visible in server unity 5
Here I am trying to instantiate Player in client with button click. Here is my script. I can see server in client but can not see client player in server. Anyone can help.?

I am Instantiate player with custom script. Player instantiate after button click.

By pressing btnPlayer button Player instantiate.

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Network_Manager_Custom : NetworkManager {

    private Animator anim;
    //[SerializeField]private GameObject btnDisconnect;
    [SerializeField]private GameObject _player, SpawnPointsParent, btnPlayer;
    [SerializeField]private List<GameObject> sPoints;
    private bool checkState = false;
    private int iPos = 0;

    GameObject ga;

    public void StartupHost()
    {
        setPort ();
        NetworkManager.singleton.StartHost ();
        sPoints = new List<GameObject> ();
    }

    public void JoinGame()
    {
        setIPAddress ();
        setPort ();
        NetworkManager.singleton.StartClient ();
        iPos = iPos + 1;
    }

    public void setIPAddress()
    {
        string IPAddress = GameObject.Find ("InputFieldIPAddress").transform.FindChild("Text").GetComponent<Text>().text;
        NetworkManager.singleton.networkAddress = IPAddress;
        Debug.Log ("IPAddress : "+ IPAddress);
    }
    void setPort()
    {
        NetworkManager.singleton.networkPort = 7777;
    }

    void OnLevelWasLoaded(int level)
    {
        if (level == 0) {
            SetupMenuScreenButtons ();
        } else {
            SetupOtherSceneButtons ();
        }
    }
    void SetupMenuScreenButtons()
    {
        GameObject.Find ("btnStartHost").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnStartHost").GetComponent<Button> ().onClick.AddListener (StartupHost);

        GameObject.Find ("btnJoinGame").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnJoinGame").GetComponent<Button> ().onClick.AddListener (JoinGame);

    }
    void SetupOtherSceneButtons()
    {
        //btnDisconnect = GameObject.Find ("btnDisconnect");
        //if (btnDisconnect != null) {
        GetListOfPlayer ();

        GameObject.Find ("btnDisconnect").GetComponent<Button> ().onClick.RemoveAllListeners ();
        GameObject.Find ("btnDisconnect").GetComponent<Button> ().onClick.AddListener (NetworkManager.singleton.StopHost);

        GameObject.Find ("btnPlayer").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnPlayer").GetComponent<Button> ().onClick.AddListener (PlayerInstantiateHere);

        //} else {
        //  Debug.Log("btnDisconnect not available.!");
        //}
    }
    void GetListOfPlayer()
    {
        if(SpawnPointsParent == null)
            SpawnPointsParent = GameObject.Find ("SpawnPoints");

        foreach(Transform t in SpawnPointsParent.transform)
        {
            sPoints.Add (t.gameObject);
        }
    }

    public void PlayerInstantiateHere()
    {
        if (_player != null) {
            //NetworkManager.Instantiate (_player, sPoints [iPos].transform.position, sPoints [iPos].transform.rotation);
            GameObject ga = (GameObject) NetworkBehaviour.Instantiate(_player, sPoints [iPos].transform.position, sPoints [iPos].transform.rotation);
            ClientScene.RegisterPrefab (ga);
            NetworkServer.Spawn (ga);

        }
        Debug.Log ("Player button clicked.!");
    }

}
</code>```

答:
Your code seems ok, I guess you both player are spawning at the same position. Make it radomize by provide different position for this reason:
Please add some empty gameobject (position) and add NetworkStartPosition Component. Finally also set PlayerSpawnMethod to round robin.</p>

Body:
Here I am trying to instantiate Player in client with button click. Here is my script. I can see server in client but can not see client player in server. Anyone can help.?

I am Instantiate player with custom script. Player instantiate after button click.

By pressing btnPlayer button Player instantiate.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Network_Manager_Custom : NetworkManager {

    private Animator anim;
    //[SerializeField]private GameObject btnDisconnect;
    [SerializeField]private GameObject _player, SpawnPointsParent, btnPlayer;
    [SerializeField]private List<GameObject> sPoints;
    private bool checkState = false;
    private int iPos = 0;

    GameObject ga;

    public void StartupHost()
    {
        setPort ();
        NetworkManager.singleton.StartHost ();
        sPoints = new List<GameObject> ();
    }

    public void JoinGame()
    {
        setIPAddress ();
        setPort ();
        NetworkManager.singleton.StartClient ();
        iPos = iPos + 1;
    }

    public void setIPAddress()
    {
        string IPAddress = GameObject.Find ("InputFieldIPAddress").transform.FindChild("Text").GetComponent<Text>().text;
        NetworkManager.singleton.networkAddress = IPAddress;
        Debug.Log ("IPAddress : "+ IPAddress);
    }
    void setPort()
    {
        NetworkManager.singleton.networkPort = 7777;
    }

    void OnLevelWasLoaded(int level)
    {
        if (level == 0) {
            SetupMenuScreenButtons ();
        } else {
            SetupOtherSceneButtons ();
        }
    }
    void SetupMenuScreenButtons()
    {
        GameObject.Find ("btnStartHost").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnStartHost").GetComponent<Button> ().onClick.AddListener (StartupHost);

        GameObject.Find ("btnJoinGame").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnJoinGame").GetComponent<Button> ().onClick.AddListener (JoinGame);

    }
    void SetupOtherSceneButtons()
    {
        //btnDisconnect = GameObject.Find ("btnDisconnect");
        //if (btnDisconnect != null) {
        GetListOfPlayer ();

        GameObject.Find ("btnDisconnect").GetComponent<Button> ().onClick.RemoveAllListeners ();
        GameObject.Find ("btnDisconnect").GetComponent<Button> ().onClick.AddListener (NetworkManager.singleton.StopHost);

        GameObject.Find ("btnPlayer").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find ("btnPlayer").GetComponent<Button> ().onClick.AddListener (PlayerInstantiateHere);

        //} else {
        //  Debug.Log("btnDisconnect not available.!");
        //}
    }
    void GetListOfPlayer()
    {
        if(SpawnPointsParent == null)
            SpawnPointsParent = GameObject.Find ("SpawnPoints");

        foreach(Transform t in SpawnPointsParent.transform)
        {
            sPoints.Add (t.gameObject);
        }
    }

    public void PlayerInstantiateHere()
    {
        if (_player != null) {
            //NetworkManager.Instantiate (_player, sPoints [iPos].transform.position, sPoints [iPos].transform.rotation);
            GameObject ga = (GameObject) NetworkBehaviour.Instantiate(_player, sPoints [iPos].transform.position, sPoints [iPos].transform.rotation);
            ClientScene.RegisterPrefab (ga);
            NetworkServer.Spawn (ga);

        }
        Debug.Log ("Player button clicked.!");
    }

}


来源: stackexchange

问:
WPF hide slider track
I'm using WPF (and the MVVM framework) to create an interface which has a slider on it.

```<code><Slider Value="{Binding MotorDemandSpeed}" Maximum="3500" />
</code>```

I'm trying to hide the track part on the slider so that you are left with just the 'thumb tack'. This is what the slider currently looks like (styles are controlled by a theme):

I've looked around at various methods, however I can't find a method that changes only a single slider.

Help is appreciated.

答:
You need to set the Template property of this particular Slider instance to be able to override its ControlTemplate:

```<code><Slider Value="{Binding MotorDemandSpeed}" Maximum="3500">
    <Slider.Template>
        <ControlTemplate TargetType="Slider">
            <!-- define the custom template without a track here... -->
        </ControlTemplate>
    </Slider.Template>
</Slider>
</code>```

ContentLicense: CC BY-SA 3.0

Title: WPF hide slider track

Body:
I'm using WPF (and the MVVM framework) to create an interface which has a slider on it.

<Slider Value="{Binding MotorDemandSpeed}" Maximum="3500" />

I'm trying to hide the track part on the slider so that you are left with just the 'thumb tack'. This is what the slider currently looks like (styles are controlled by a theme):

I've looked around at various methods, however I can't find a method that changes only a single slider.

Help is appreciated.

Body:
You need to set the Template property of this particular Slider instance to be able to override its ControlTemplate:

<Slider Value="{Binding MotorDemandSpeed}" Maximum="3500">
    <Slider.Template>
        <ControlTemplate TargetType="Slider">
            <!-- define the custom template without a track here... -->
        </ControlTemplate>
    </Slider.Template>
</Slider>


问:
CIFilter not working
I'm trying to add a blur effect to a layer with following code.

 But it doesn't work, any advise?

```<code>let layer = CALayer()
layer.frame = CGRect(x: 150, y: 150, width: 150, height: 150)
layer.backgroundColor = UIColor.blue.cgColor
layer.contents = UIImage(named: "D1")?.cgImage

if let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius": 15]) {
filter.setDefaults()
layer.filters = [filter]
}
view.layer.addSublayer(layer)
</code>```

It just displayed the image without filter effect. I'm really confused. Thank you for any advise.

答:
This doesn't work on iOS. From the Apple documentation:

Special Considerations

This property is not supported on layers in iOS.

You'll need to do it the "long" way:

```<code>let ciInput = CIImage(image: UIImage(named: "D1")!)
let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputImage": ciInput, "inputRadius": 15])
let ciOutput = filter?.outputImage
let ciContext = CIContext(options: nil)
let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)
layer.contents = cgImage
</code>```

Please note that my Swift 4 code is untested. One or two build issues (unwrapping in particular) may be there and (of course) due to this a nil may happen at runtime. I'm providing the Swift code as a good translation of the accepted answer in the question linked to above.

Title: CIFilter not working

Body:
I'm trying to add a blur effect to a layer with following code.

 But it doesn't work, any advise?

let layer = CALayer()
layer.frame = CGRect(x: 150, y: 150, width: 150, height: 150)
layer.backgroundColor = UIColor.blue.cgColor
layer.contents = UIImage(named: "D1")?.cgImage

if let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius": 15]) {
filter.setDefaults()
layer.filters = [filter]
}
view.layer.addSublayer(layer)

It just displayed the image without filter effect. I'm really confused. Thank you for any advise.

Body:
This doesn't work on iOS. From the Apple documentation:

Special Considerations

This property is not supported on layers in iOS.

You'll need to do it the "long" way:

let ciInput = CIImage(image: UIImage(named: "D1")!)
let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputImage": ciInput, "inputRadius": 15])
let ciOutput = filter?.outputImage
let ciContext = CIContext(options: nil)
let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)
layer.contents = cgImage

Please note that my Swift 4 code is untested. One or two build issues (unwrapping in particular) may be there and (of course) due to this a nil may happen at runtime. I'm providing the Swift code as a good translation of the accepted answer in the question linked to above.


问:
Returning undefined in output
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));```

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?

答:
You need to push only i to the newArray. i here is already a Number.

Also since number variable inside the function is a primitive and not an object or an array, therefore number[i] gives you undefined because it has no property corresponding to value of i.

Also, the last else is not required as it is doing nothing.

```<code>function solution(number){
 var newarray = []
 for ( var i = 0 ; i < number - 1 ; i++ ) {
    if (i % 3 === 0) {
       newarray.push(i);
    } else if (i % 5 === 0) {
       newarray.push(i);
    }
  }
  return newarray
}

solution(10);//returns [0, 3, 5, 6]
</code>```

Title: Returning undefined in output

Body:
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?

Body:
You need to push only i to the newArray. i here is already a Number.

Also since number variable inside the function is a primitive and not an object or an array, therefore number[i] gives you undefined because it has no property corresponding to value of i.

Also, the last else is not required as it is doing nothing.

function solution(number){
 var newarray = []
 for ( var i = 0 ; i < number - 1 ; i++ ) {
    if (i % 3 === 0) {
       newarray.push(i);
    } else if (i % 5 === 0) {
       newarray.push(i);
    }
  }
  return newarray
}

solution(10);//returns [0, 3, 5, 6]


问:
Firebase database load data into Listview
I have this DB structure:

```<code>{
    "customers" : {
       "-L-OcgJ0kwTNSm6HoSvG" : {
         "address" : "Test Alamat",
         "birthday" : "1990-12-03",
         "email" : "Dodi@gmail.com",
         "name" : "Dodi",
         "outletID" : "2673",
         "phone" : "09888777111"
       }
    }
}
</code>```

Now i want to load all data of "customers" into ListView using FirebaseUI-Android library. And here is the codes:

```<code>Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50);

FirebaseListOptions<Customers> options = new FirebaseListOptions.Builder<Customers>()
                    .setLayout(R.layout.row_customer)
                    .setQuery(query, Customers.class)
                    .build();

FirebaseListAdapter<Customers> adapter = new FirebaseListAdapter<Customers>(options) {
                @Override
                protected void populateView(View view, Customers customer, int position) {
                    ((TextView) view.findViewById(R.id.txtCustomerName)).setText(customer.name);
                    ((TextView) view.findViewById(R.id.txtCustomerAddress)).setText(customer.address);
                    ((TextView) view.findViewById(R.id.txtCustomerPhone)).setText(customer.phone);

  //and i've set the adapter into ListView
  ((ListView)layout.findViewById(R.id.lvCustomerList)).setAdapter(adapter);
</code>```

And here is Customers.java:

```<code>@IgnoreExtraProperties
public class Customers {
    public String name, outletID, address, phone, birthday, email;

    public Customers() {
    }

    public Customers(String name, String outletID, String address, String phone, String birthday, String email) {
       this.name = name;
       this.outletID = outletID;
       this.address = address;
       this.phone = phone;
       this.birthday = birthday;
       this.email = email;
    }
}
</code>```

Please help me what is the problem with my source code?
i've run it and the data failed to display (only blank on my listview). There's no errors on my Android Studio logs.

答:
Change this line of code:

```<code>Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50)
</code>```

with

```<code>Query query = FirebaseDatabase.getInstance().getReference()
    .child("customers")
    .orderByChild("name")
    .limitToLast(50);
</code>```

Body:
I have this DB structure:

{
    "customers" : {
       "-L-OcgJ0kwTNSm6HoSvG" : {
         "address" : "Test Alamat",
         "birthday" : "1990-12-03",
         "email" : "Dodi@gmail.com",
         "name" : "Dodi",
         "outletID" : "2673",
         "phone" : "09888777111"
       }
    }
}

Now i want to load all data of "customers" into ListView using FirebaseUI-Android library. And here is the codes:

Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50);

FirebaseListOptions<Customers> options = new FirebaseListOptions.Builder<Customers>()
                    .setLayout(R.layout.row_customer)
                    .setQuery(query, Customers.class)
                    .build();

FirebaseListAdapter<Customers> adapter = new FirebaseListAdapter<Customers>(options) {
                @Override
                protected void populateView(View view, Customers customer, int position) {
                    ((TextView) view.findViewById(R.id.txtCustomerName)).setText(customer.name);
                    ((TextView) view.findViewById(R.id.txtCustomerAddress)).setText(customer.address);
                    ((TextView) view.findViewById(R.id.txtCustomerPhone)).setText(customer.phone);

  //and i've set the adapter into ListView
  ((ListView)layout.findViewById(R.id.lvCustomerList)).setAdapter(adapter);

And here is Customers.java:

@IgnoreExtraProperties
public class Customers {
    public String name, outletID, address, phone, birthday, email;

    public Customers() {
    }

    public Customers(String name, String outletID, String address, String phone, String birthday, String email) {
       this.name = name;
       this.outletID = outletID;
       this.address = address;
       this.phone = phone;
       this.birthday = birthday;
       this.email = email;
    }
}

Please help me what is the problem with my source code?
i've run it and the data failed to display (only blank on my listview). There's no errors on my Android Studio logs.

Body:
Change this line of code:

Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50)

with

Query query = FirebaseDatabase.getInstance().getReference()
    .child("customers")
    .orderByChild("name")
    .limitToLast(50);


问:
Bash script: Turn on errors?
After designing a simple shell/bash based backup script on my Ubuntu engine and making it work, I've uploaded it to my Debian server, which outputs a number of errors while executing it.

What can I do to turn on "error handling" in my Ubuntu machine to make it easier to debug?

答:
Change your shebang line to include the trace option:

```<code>#!/bin/bash -x
</code>```

You can also have Bash scan the file for errors without running it:

```<code>$ bash -n scriptname
</code>```

ContentLicense: CC BY-SA 2.5

Title: Bash script: Turn on errors?

Body:
Change your shebang line to include the trace option:

#!/bin/bash -x

You can also have Bash scan the file for errors without running it:

$ bash -n scriptname


问:
best practice for trigger a method by user's input in angular2
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

```<code><div class="col-md-8">
   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>
</code>```

My ts file:

```<code>populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}
</code>```

答:
Try RxJs, if you looking for a best practice. check this angular documentation
Template

```<code><input #searchBox type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate(searchBox.value)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</code>```

Component

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

import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';
import { of }         from 'rxjs/observable/of';

import {
   debounceTime, distinctUntilChanged, switchMap
 } from 'rxjs/operators';

searchResult : Observable<any>;
private searchTerms = new Subject<string>();

ngOnInit(): void {
this.searchResult = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(300),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) =>   this._lookup.getIcrData(term)),
);
}

populate(term: string){
this.searchTerms.next(term);
}
</code>```

Body:
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

My ts file:

populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}

Body:
Try RxJs, if you looking for a best practice. check this angular documentation
Template

<input #searchBox type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate(searchBox.value)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

Component

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

import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';
import { of }         from 'rxjs/observable/of';

import {
   debounceTime, distinctUntilChanged, switchMap
 } from 'rxjs/operators';

searchResult : Observable<any>;
private searchTerms = new Subject<string>();

ngOnInit(): void {
this.searchResult = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(300),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) =>   this._lookup.getIcrData(term)),
);
}

populate(term: string){
this.searchTerms.next(term);
}


问:
run powershell in VBA access
I need to change a string in multiple text files

I have written the script below in ACCESS VBA but the error is TYPE MISMATCH

```<code>Dim str As String
str = "N=maher"
Call Shell("c:\windows\system32\powershell.exe" - Command("get-content -Path e:\temptest.txt") - Replace(str, "maher", "ali"))
</code>```

答:
The syntax for calling PowerShell is way off. Suggestion: get it working from the command line yourself first, and then run from Access (an odd choice: it just makes this more complicated).

A PowerShell script to do this (.ps1 file) would need to contain something like:

```<code>Get-Content -Path "E:\temptest.txt" | ForEach-Object { $_ -Replace 'maher', 'ali' } | do-something-with-the-updated-content
</code>```

You need to define:

What you are replacing (you pass N=maher in but then hard code two strings for Replace.

What do to with the strings after doing the replacement (Get-Content only reads files).

Title: run powershell in VBA access

Body:
I need to change a string in multiple text files

I have written the script below in ACCESS VBA but the error is TYPE MISMATCH

Dim str As String
str = "N=maher"
Call Shell("c:\windows\system32\powershell.exe" - Command("get-content -Path e:\temptest.txt") - Replace(str, "maher", "ali"))

Body:
The syntax for calling PowerShell is way off. Suggestion: get it working from the command line yourself first, and then run from Access (an odd choice: it just makes this more complicated).

A PowerShell script to do this (.ps1 file) would need to contain something like:

Get-Content -Path "E:\temptest.txt" | ForEach-Object { $_ -Replace 'maher', 'ali' } | do-something-with-the-updated-content

You need to define:

What you are replacing (you pass N=maher in but then hard code two strings for Replace.

What do to with the strings after doing the replacement (Get-Content only reads files).


问:
css editor in php like wordpress's css editor
I want to make css manager for my site like wordpress's css manager.
I want to open css file in textarea so I can edit it than after pressing submit button, changes in css file should be saved.
Please help me. Sorry for my bad english. </p>

答:
You should learn PHP's filesystem functions (fopen , fwrite etc. )

But if your question is emergency , basically you can get a file's content with :

```<code>file_get_contents("file.css");
</code>```

and then you can put new content to file with :

```<code>file_put_contents("file.css");
</code>```

Body:
You should learn PHP's filesystem functions (fopen , fwrite etc. )

But if your question is emergency , basically you can get a file's content with :

file_get_contents("file.css");

and then you can put new content to file with :

file_put_contents("file.css");


问:
ArcLayout pixelize
I use https://github.com/florent37/ArcLayout for arc to layout

But my layout pixelize

```<code><com.github.florent37.arclayout.ArcLayout
                android:layout_width="match_parent"
                android:layout_height="200dp"
                app:arc_height="20dp"
                app:arc_cropDirection="cropOutside"
                app:arc_position="bottom">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:background="#fff">
                </LinearLayout>
            </com.github.florent37.arclayout.ArcLayout>
</code>```

I found this topic : https://github.com/florent37/ArcLayout/issues/8

But i dont understand how use below code:

```<code>@override
protected void dispatchDraw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
canvas.drawPath(clipPath, paint);
canvas.restoreToCount(saveCount);
paint.setXfermode(null);
}
</code>```

答:
Go to this file in your project  : https://github.com/florent37/ArcLayout/blob/master/arclayout/src/main/java/com/github/florent37/arclayout/ArcLayout.java

Update dispatchDraw method with your code suggested in issue.

EDIT

Replace your ArcLayout.java with this file:

```<code>public class ArcLayout extends FrameLayout {

    private ArcLayoutSettings settings;

    private int height = 0;

    private int width = 0;

    private Path clipPath;

    public ArcLayout(Context context) {
        super(context);
        init(context, null);
    }

    public ArcLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public void init(Context context, AttributeSet attrs) {
        settings = new ArcLayoutSettings(context, attrs);
        settings.setElevation(ViewCompat.getElevation(this));

        /**
         * If hardware acceleration is on (default from API 14), clipPath worked correctly
         * from API 18.
         *
         * So we will disable hardware Acceleration if API < 18
         *
         * https://developer.android.com/guide/topics/graphics/hardware-accel.html#unsupported
         * Section #Unsupported Drawing Operations
         */
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

    private Path createClipPath() {
        final Path path = new Path();

        float arcHeight = settings.getArcHeight();

        switch (settings.getPosition()){
            case ArcLayoutSettings.POSITION_BOTTOM:{
                if (settings.isCropInside()) {
                    path.moveTo(0, 0);
                    path.lineTo(0, height);
                    path.quadTo(width / 2, height - 2 * arcHeight, width, height);
                    path.lineTo(width, 0);
                    path.close();
                } else {
                    path.moveTo(0, 0);
                    path.lineTo(0, height - arcHeight);
                    path.quadTo(width / 2, height + arcHeight, width, height - arcHeight);
                    path.lineTo(width, 0);
                    path.close();
                }
                break;
            }
            case ArcLayoutSettings.POSITION_TOP:
                if (settings.isCropInside()) {
                    path.moveTo(0, height);
                    path.lineTo(0, 0);
                    path.quadTo(width / 2, 2 * arcHeight, width, 0);
                    path.lineTo(width, height);
                    path.close();
                } else {
                    path.moveTo(0, arcHeight);
                    path.quadTo(width / 2, -arcHeight, width, arcHeight);
                    path.lineTo(width, height);
                    path.lineTo(0, height);
                    path.close();
                }
                break;
            case ArcLayoutSettings.POSITION_LEFT:
                if (settings.isCropInside()) {
                    path.moveTo(width, 0);
                    path.lineTo(0, 0);
                    path.quadTo(arcHeight * 2, height / 2, 0, height);
                    path.lineTo(width, height);
                    path.close();
                } else {
                    path.moveTo(width, 0);
                    path.lineTo(arcHeight, 0);
                    path.quadTo(-arcHeight, height / 2, arcHeight, height);
                    path.lineTo(width, height);
                    path.close();
                }
                break;
            case ArcLayoutSettings.POSITION_RIGHT:
                if (settings.isCropInside()) {
                    path.moveTo(0, 0);
                    path.lineTo(width, 0);
                    path.quadTo(width - arcHeight * 2, height / 2, width, height);
                    path.lineTo(0, height);
                    path.close();
                } else {
                    path.moveTo(0, 0);
                    path.lineTo(width - arcHeight, 0);
                    path.quadTo(width + arcHeight, height / 2, width - arcHeight, height);
                    path.lineTo(0, height);
                    path.close();
                }
                break;
        }

        return path;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            calculateLayout();
        }
    }

    private void calculateLayout() {
        if (settings == null) {
            return;
        }
        height = getMeasuredHeight();
        width = getMeasuredWidth();
        if (width > 0 && height > 0) {

            clipPath = createClipPath();
            ViewCompat.setElevation(this, settings.getElevation());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !settings.isCropInside()) {
                ViewCompat.setElevation(this, settings.getElevation());
                setOutlineProvider(new ViewOutlineProvider() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void getOutline(View view, Outline outline) {
                        outline.setConvexPath(clipPath);
                    }
                });
            }
        }
    }

       @Override
        protected void dispatchDraw(Canvas canvas) {
        Paint paint= new Paint();
       paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
        canvas.drawPath(clipPath, paint);
        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}
</code>```

Title: ArcLayout pixelize

Body:
I use https://github.com/florent37/ArcLayout for arc to layout

But my layout pixelize

<com.github.florent37.arclayout.ArcLayout
                android:layout_width="match_parent"
                android:layout_height="200dp"
                app:arc_height="20dp"
                app:arc_cropDirection="cropOutside"
                app:arc_position="bottom">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:background="#fff">
                </LinearLayout>
            </com.github.florent37.arclayout.ArcLayout>

I found this topic : https://github.com/florent37/ArcLayout/issues/8

But i dont understand how use below code:

@override
protected void dispatchDraw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
canvas.drawPath(clipPath, paint);
canvas.restoreToCount(saveCount);
paint.setXfermode(null);
}

Body:
Go to this file in your project  : https://github.com/florent37/ArcLayout/blob/master/arclayout/src/main/java/com/github/florent37/arclayout/ArcLayout.java

Update dispatchDraw method with your code suggested in issue.

EDIT

Replace your ArcLayout.java with this file:

public class ArcLayout extends FrameLayout {

    private ArcLayoutSettings settings;

    private int height = 0;

    private int width = 0;

    private Path clipPath;

    public ArcLayout(Context context) {
        super(context);
        init(context, null);
    }

    public ArcLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public void init(Context context, AttributeSet attrs) {
        settings = new ArcLayoutSettings(context, attrs);
        settings.setElevation(ViewCompat.getElevation(this));

        /**
         * If hardware acceleration is on (default from API 14), clipPath worked correctly
         * from API 18.
         *
         * So we will disable hardware Acceleration if API < 18
         *
         * https://developer.android.com/guide/topics/graphics/hardware-accel.html#unsupported
         * Section #Unsupported Drawing Operations
         */
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

    private Path createClipPath() {
        final Path path = new Path();

        float arcHeight = settings.getArcHeight();

        switch (settings.getPosition()){
            case ArcLayoutSettings.POSITION_BOTTOM:{
                if (settings.isCropInside()) {
                    path.moveTo(0, 0);
                    path.lineTo(0, height);
                    path.quadTo(width / 2, height - 2 * arcHeight, width, height);
                    path.lineTo(width, 0);
                    path.close();
                } else {
                    path.moveTo(0, 0);
                    path.lineTo(0, height - arcHeight);
                    path.quadTo(width / 2, height + arcHeight, width, height - arcHeight);
                    path.lineTo(width, 0);
                    path.close();
                }
                break;
            }
            case ArcLayoutSettings.POSITION_TOP:
                if (settings.isCropInside()) {
                    path.moveTo(0, height);
                    path.lineTo(0, 0);
                    path.quadTo(width / 2, 2 * arcHeight, width, 0);
                    path.lineTo(width, height);
                    path.close();
                } else {
                    path.moveTo(0, arcHeight);
                    path.quadTo(width / 2, -arcHeight, width, arcHeight);
                    path.lineTo(width, height);
                    path.lineTo(0, height);
                    path.close();
                }
                break;
            case ArcLayoutSettings.POSITION_LEFT:
                if (settings.isCropInside()) {
                    path.moveTo(width, 0);
                    path.lineTo(0, 0);
                    path.quadTo(arcHeight * 2, height / 2, 0, height);
                    path.lineTo(width, height);
                    path.close();
                } else {
                    path.moveTo(width, 0);
                    path.lineTo(arcHeight, 0);
                    path.quadTo(-arcHeight, height / 2, arcHeight, height);
                    path.lineTo(width, height);
                    path.close();
                }
                break;
            case ArcLayoutSettings.POSITION_RIGHT:
                if (settings.isCropInside()) {
                    path.moveTo(0, 0);
                    path.lineTo(width, 0);
                    path.quadTo(width - arcHeight * 2, height / 2, width, height);
                    path.lineTo(0, height);
                    path.close();
                } else {
                    path.moveTo(0, 0);
                    path.lineTo(width - arcHeight, 0);
                    path.quadTo(width + arcHeight, height / 2, width - arcHeight, height);
                    path.lineTo(0, height);
                    path.close();
                }
                break;
        }

        return path;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            calculateLayout();
        }
    }

    private void calculateLayout() {
        if (settings == null) {
            return;
        }
        height = getMeasuredHeight();
        width = getMeasuredWidth();
        if (width > 0 && height > 0) {

            clipPath = createClipPath();
            ViewCompat.setElevation(this, settings.getElevation());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !settings.isCropInside()) {
                ViewCompat.setElevation(this, settings.getElevation());
                setOutlineProvider(new ViewOutlineProvider() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void getOutline(View view, Outline outline) {
                        outline.setConvexPath(clipPath);
                    }
                });
            }
        }
    }

       @Override
        protected void dispatchDraw(Canvas canvas) {
        Paint paint= new Paint();
       paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        super.dispatchDraw(canvas);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
        canvas.drawPath(clipPath, paint);
        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    }
}

ContentLicense: CC BY-SA 4.0


问:
Webpack: "there are multiple modules with names that only differ in casing" but modules referenced are identical
I'm using webpack 3.8.1 and am receiving several instances of the following build warning:

```<code>WARNING in ./src/Components/NavBar/MainMenuItemMobile.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* /Users/path/to/babel-loader/lib/index.js!/Users/path/to/NavBar/MainMenuItemMobile.js
    Used by 1 module(s), i. e.
    /Users/path/to/babel-loader/lib/index.js!/Users/path/to/NavBar/ConstructedMainMenuItems.js
* /Users/path/to/babel-loader/lib/index.js!/Users/path/to/Navbar/MainMenuItemMobile.js
    Used by 1 module(s), i. e.
    /Users/path/to/babel-loader/lib/index.js!/Users/path/to/Navbar/ConstructedMainMenuItems.js
.....
(webpack)-hot-middleware/client.js ./src/index.js
</code>```

What's confusing is that the 'two' files referenced are just one file—there are no two files in the directory whose names differ only in case.

I've also noticed that my hot reloader often doesn't pick up changes to a file if it is affected by these warnings.

What could be causing this issue?

答:
This is usually the result of a minuscule typo by wrongly using either an capital first letter or a lower case first letter when the opposite was needed.

For instance, if you are importing your modules like this:

```<code>import Vue from 'vue'
</code>```

or:

```<code>import Vuex from 'vuex'
</code>```

Go through your files and check where you used phrases like from 'Vue' or from 'Vuex' and make sure to use the exact same capitals (uppercase letters) as in your import statements.

Background:

The error basically says that there are multiple modules of a similar name only differing in casing in our code which seems to indicate that on the time you refer to your "import" module but don't use the correct casing, Vue will try to create another module with the aforementioned name difference yet both are pointing to the same module reference. So Vue could have been more resilient by jut ignoring the casing of the module reference name in our code.

What I explained has been the cause of my problem each time for this error on webpack commands.

Body:
I'm using webpack 3.8.1 and am receiving several instances of the following build warning:

WARNING in ./src/Components/NavBar/MainMenuItemMobile.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* /Users/path/to/babel-loader/lib/index.js!/Users/path/to/NavBar/MainMenuItemMobile.js
    Used by 1 module(s), i. e.
    /Users/path/to/babel-loader/lib/index.js!/Users/path/to/NavBar/ConstructedMainMenuItems.js
* /Users/path/to/babel-loader/lib/index.js!/Users/path/to/Navbar/MainMenuItemMobile.js
    Used by 1 module(s), i. e.
    /Users/path/to/babel-loader/lib/index.js!/Users/path/to/Navbar/ConstructedMainMenuItems.js
.....
(webpack)-hot-middleware/client.js ./src/index.js

What's confusing is that the 'two' files referenced are just one file—there are no two files in the directory whose names differ only in case.

I've also noticed that my hot reloader often doesn't pick up changes to a file if it is affected by these warnings.

What could be causing this issue?

Body:
This is usually the result of a minuscule typo by wrongly using either an capital first letter or a lower case first letter when the opposite was needed.

For instance, if you are importing your modules like this:

import Vue from 'vue'

or:

import Vuex from 'vuex'

Go through your files and check where you used phrases like from 'Vue' or from 'Vuex' and make sure to use the exact same capitals (uppercase letters) as in your import statements.

Background:

The error basically says that there are multiple modules of a similar name only differing in casing in our code which seems to indicate that on the time you refer to your "import" module but don't use the correct casing, Vue will try to create another module with the aforementioned name difference yet both are pointing to the same module reference. So Vue could have been more resilient by jut ignoring the casing of the module reference name in our code.

What I explained has been the cause of my problem each time for this error on webpack commands.


问:
Running Ansible from Jenkins as [user]
I have a running Ansible environment (with environment variable, dynamic inventory) and multiple scripts. Recently I added Jenkins to this same server in order to make the automation easier.

When I run the plays from within Jenkins however I noticed that the ansible playbooks are now run as 'jenkins' instead of the 'ansible' user.

The 'jenkins' user does not have full access to ansible environment variables or dynamic inventory (which was written for 'ansible' user). I would like to run all playbooks as 'ansible' as originally coded.

Does such a concept exist in Jenkins, and if so how?

The following URL gives a way around it. But this looks more like a hack.
https://issues.jenkins-ci.org/browse/JENKINS-37063

I dont want to change any environment variables or move files around.

答:
I think on that server you can create a linux group and add both Jenkins and Ansible users to it.

This may give Jenkins user access to run ansible playbooks.

But regarding this scenario, I think the best way is to keep Jenkins and Ansible in different servers, and then you can Add Ansible as a slave to Jenkins, thereafter you can configure jenkins to run plabooks using ansible user.

Title: Running Ansible from Jenkins as [user]


问:
Can not read umlauts with boost read_json
I can't solve my problem with boost::property_tree::read_json. I have MFC project with MBCS encoding(multi byte character set). I'm getting error during reading data with ä character. This is my example:

```<code>namespace pt = boost::property_tree;

pt::ptree rootRequest;

//Save data in property tree
rootRequest.put("test", "Test ä");

//create stringstream
std::stringstream ss;

//Write rootRequest to stringstream
try
{
    pt::write_json(ss, rootRequest);
}
catch (std::exception const &e)
{
    TRACE("Error: [%s]\n", e.what());
}

//Get string from stringstream
std::string strRequest = ss.str();
TRACE("data: [%s]\n", CString(strRequest.c_str()));

//Clear stringstream
ss.str(std::string());

//Sate data to stringstream
ss << strRequest;

//Save string data in ptree value
pt::ptree rootResponse;
try
{
    pt::read_json(ss, rootResponse);   //Here I'm getting error

}
catch (std::exception const &e)
{
    TRACE("Error: [%s]\n", e.what());
}
</code>```

I'm getting the following exception:

```<code><unspecified file>(2): invalid code sequence
</code>```

Which is the proper way to read data like that? I hope somebody can help me with this. I need to save data in string and then read this again to stringstream. This part can't be changed.

答:
JSON cannot store MBCS strings.  Meaning one must convert all labels and values to UTF-8 or UTF-16 before saving.

UTF-8 is the usual choice for JSON, not only because that uses less string memory, but also because UTF-8 encoding has 1-to-1 unique glyph encoding, which UTF-16 doesn't.

Here's how you'd convert your strings:

MBCS to Unicode:

```<code>#include <windows.h>
#include <string>

std::wstring MBCS_to_UTF16(LPCSTR sz)
{
    // MBCS to UNICODE
    std::wstring strResult;

    size_t nCharsDone = 0;
    const size_t nMaxsWords = 6 * strlen(sz);

    strResult.resize(nMaxsWords + 1);

    if (S_OK == ::mbstowcs_s(&nCharsDone, &strResult[0], nMaxsWords + 1, sz, nMaxsWords))
        strResult.resize(nCharsDone);
    else
        strResult.clear();
    return strResult;
}
</code>```

UTF16 <-> UTF8:

```<code>#include <boost/locale.hpp>

std::string strUTF8 = boost::locale::conv::utf_to_utf<char>(L"hello"); //
std::wstring strUTF16 = boost::locale::conv::utf_to_utf<wchar_t>("hello");
</code>```

UTF16 to MBCS:

```<code>std::string UTF16_to_MBCS(LPCWSTR wsz)
{
    // MBCS to UNICODE
    std::string strResult;

    size_t nCharsDone = 0;
    const size_t nMaxWords = 2 * wcslen(wsz);

    strResult.resize(nMaxWords + 1);

    if (S_OK == ::wcstombs_s(&nCharsDone, &strResult[0], nMaxWords + 1, wsz, nMaxWords))
        strResult.resize(nCharsDone);
    else
        strResult.clear();
    return strResult;
}
</code>```

Body:
I can't solve my problem with boost::property_tree::read_json. I have MFC project with MBCS encoding(multi byte character set). I'm getting error during reading data with ä character. This is my example:

namespace pt = boost::property_tree;

pt::ptree rootRequest;

//Save data in property tree
rootRequest.put("test", "Test ä");

//create stringstream
std::stringstream ss;

//Write rootRequest to stringstream
try
{
    pt::write_json(ss, rootRequest);
}
catch (std::exception const &e)
{
    TRACE("Error: [%s]\n", e.what());
}

//Get string from stringstream
std::string strRequest = ss.str();
TRACE("data: [%s]\n", CString(strRequest.c_str()));

//Clear stringstream
ss.str(std::string());

//Sate data to stringstream
ss << strRequest;

//Save string data in ptree value
pt::ptree rootResponse;
try
{
    pt::read_json(ss, rootResponse);   //Here I'm getting error

}
catch (std::exception const &e)
{
    TRACE("Error: [%s]\n", e.what());
}

I'm getting the following exception:

<unspecified file>(2): invalid code sequence

Which is the proper way to read data like that? I hope somebody can help me with this. I need to save data in string and then read this again to stringstream. This part can't be changed.

Body:
JSON cannot store MBCS strings.  Meaning one must convert all labels and values to UTF-8 or UTF-16 before saving.

UTF-8 is the usual choice for JSON, not only because that uses less string memory, but also because UTF-8 encoding has 1-to-1 unique glyph encoding, which UTF-16 doesn't.

Here's how you'd convert your strings:

MBCS to Unicode:

#include <windows.h>
#include <string>

std::wstring MBCS_to_UTF16(LPCSTR sz)
{
    // MBCS to UNICODE
    std::wstring strResult;

    size_t nCharsDone = 0;
    const size_t nMaxsWords = 6 * strlen(sz);

    strResult.resize(nMaxsWords + 1);

    if (S_OK == ::mbstowcs_s(&nCharsDone, &strResult[0], nMaxsWords + 1, sz, nMaxsWords))
        strResult.resize(nCharsDone);
    else
        strResult.clear();
    return strResult;
}

UTF16 <-> UTF8:

#include <boost/locale.hpp>

std::string strUTF8 = boost::locale::conv::utf_to_utf<char>(L"hello"); //
std::wstring strUTF16 = boost::locale::conv::utf_to_utf<wchar_t>("hello");

UTF16 to MBCS:

std::string UTF16_to_MBCS(LPCWSTR wsz)
{
    // MBCS to UNICODE
    std::string strResult;

    size_t nCharsDone = 0;
    const size_t nMaxWords = 2 * wcslen(wsz);

    strResult.resize(nMaxWords + 1);

    if (S_OK == ::wcstombs_s(&nCharsDone, &strResult[0], nMaxWords + 1, wsz, nMaxWords))
        strResult.resize(nCharsDone);
    else
        strResult.clear();
    return strResult;
}


问:
What's better to use for Django?
Django-rest or Django Pistons?

What's better plugin for API stuff?

答:
I've not used django-rest, but I have used django-piston and found it really effective and pretty easy to get up and running quickly.

It also seems to be a popular choice with a lot of devs I know - and it powers the API for bitbucket, which I take as a good sign.

For me, the primary pinch-points are:

if you're looking to create hybrid representations of your data models (eg you want the standard User resource representation to show all the fields, but (as an example - I don't want to start a REST war here) you also want your Foo representation to show a limited, nested subset of User fields) then you have to write more complicated Resource definition code to do that, because the class-based setup only allows one representation of a given model that automatically gets reused whenever that resource is needed. (Which is actually a good thing, but can be a constraint if you have to bend the output a bit.)

if any of your models store actual XML, you'll have to write a smart/non-escaping emitter to handle it, which is more about punching getting busy with your favourite XML library (tip: ElementTree)

Even with those two things in mind, piston has been my go-to resource for knocking up a quick API, and I've been very happy so far. I am tempted to try django-tastypie next, though

Title: What's better to use for Django?


问:
One ZeroMQ socket per thread or per call?
As we all know, a ZeroMQ socket shall not be shared among application threads.
context_t instances however can.

I have a multi-threaded-application and I'd like to have each thread exchange messages from time to time with a REQ/REP-socket counterparty ( event, exceptions and the like ), depending on what they are doing ( they are doing non-ZeroMQ-stuff ).

To send messages to my REQ/REP-socket I use the following function
( a half-C++ half-pseudo-code ):

sendMessage:

```<code>bool sendMessage(std::string s)
{
    zmq::socket_t socket(globalContext(), ZMQ_REQ);
    socket.connect("ipc://http-concentrator");

    zmq::message_t message(s.size());
    memcpy(message.data(), s.data(), s.size());
    if (!socket.send(message))
        return false;

    // poll on socket for POLLIN with timeout

    socket.recv(&message);
    // do something with message

    return true;
}
</code>```

This function is called from every thread when needed. It creates a local socket, connects, sends the message, and receives a response. At exit, the socket is disconnected and removed ( at least I'm assuming that it is closed ).

This way, I don't need to bother to maintain a socket in each of my threads. This comes at the cost of creating and connecting each time I call this function.

I have stressed this code and I didn't see much difference between reusing one socket and this reconnect-implementation. ( I have 20k REP/REQ transactions per second, including a JSON-decode/encode, on both side of the use-case )

Q: Is there a more correct ZeroMQ-way of doing this?

答:
An alternative could be having one dedicated thread for the ZeroMQ communication with some FIFO queue (must be guarded with a mutex or similar, of course...). This dedicated thread should be sleeping as long as the queue is empty and wake up (being signalled appropriately) whenever this state changes.

Depending on general needs, whenever the response for some outgoing message is received, the dedicated thread could simply call some callback (at some dedicated object per thread); be aware that you have a different thread context then, so you might need some means of synchronisation to prevent race conditions.

Alternatively, the sending threads could just wait for the response, being signalled by the ZeroMQ thread on received response (well, this actually is one of those means to prevent race conditions...).

Body:
As we all know, a ZeroMQ socket shall not be shared among application threads.
context_t instances however can.

I have a multi-threaded-application and I'd like to have each thread exchange messages from time to time with a REQ/REP-socket counterparty ( event, exceptions and the like ), depending on what they are doing ( they are doing non-ZeroMQ-stuff ).

To send messages to my REQ/REP-socket I use the following function
( a half-C++ half-pseudo-code ):

sendMessage:

bool sendMessage(std::string s)
{
    zmq::socket_t socket(globalContext(), ZMQ_REQ);
    socket.connect("ipc://http-concentrator");

    zmq::message_t message(s.size());
    memcpy(message.data(), s.data(), s.size());
    if (!socket.send(message))
        return false;

    // poll on socket for POLLIN with timeout

    socket.recv(&message);
    // do something with message

    return true;
}

This function is called from every thread when needed. It creates a local socket, connects, sends the message, and receives a response. At exit, the socket is disconnected and removed ( at least I'm assuming that it is closed ).

This way, I don't need to bother to maintain a socket in each of my threads. This comes at the cost of creating and connecting each time I call this function.

I have stressed this code and I didn't see much difference between reusing one socket and this reconnect-implementation. ( I have 20k REP/REQ transactions per second, including a JSON-decode/encode, on both side of the use-case )

Q: Is there a more correct ZeroMQ-way of doing this?


问:
ADD Constraint to ALTER DOMAIN ERROR
When I execute:

```<code>ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (remainingAmount > 0);
</code>```

I recevied the following message in pgAdmin 4:

ERROR:  column "remainingamount" does not exist SQL state: 42703

The column exists. I can see it in de sidebar! As evidence, when I execute te following line:

```<code>ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (remainingAmount > 0);
</code>```

I receive the message:

ERROR:  type "remainingamount" already exists SQL state: 42710

How can I add a new constraint to an existing domain?

答:
The only variable you can use in CHECK constraint of a DOMAIN is VALUE. Assuming that the base type is money:

```<code>ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (VALUE > 0::money);

</code>```

Per the documentation:

CHECK (expression)

(...)

Currently, CHECK expressions cannot contain subqueries nor refer to variables other than VALUE.

Title: ADD Constraint to ALTER DOMAIN ERROR

Body:
When I execute:

ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (remainingAmount > 0);

I recevied the following message in pgAdmin 4:

ERROR:  column "remainingamount" does not exist SQL state: 42703

The column exists. I can see it in de sidebar! As evidence, when I execute te following line:

ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (remainingAmount > 0);

I receive the message:

ERROR:  type "remainingamount" already exists SQL state: 42710

How can I add a new constraint to an existing domain?

Body:
The only variable you can use in CHECK constraint of a DOMAIN is VALUE. Assuming that the base type is money:

ALTER DOMAIN public.remainingamount
    ADD CONSTRAINT "chk_remainingAmount" CHECK (VALUE > 0::money);

Per the documentation:

CHECK (expression)

(...)

Currently, CHECK expressions cannot contain subqueries nor refer to variables other than VALUE.


问:
SSL for custom client domains
I have an app (hosted in heroku) where customers have an individual subdomain e.g. client1.myapp.com, client2.myapp.com I am using a wildcard SSL cert here.

If however a client wants to use their own custom domain e.g. CNAME app.client1.com

How can i automatically provide an SSL cert (I'm guessing using Lets Encrypt) for the client without them providing me a certificate to upload in a similar way to firebase etc.. provides SSL certs for  domains.

答:
As long as app.client1.com is reachable from the internet, you are free to set up a lets-encrypt certificate.

If your applications run on unix-like system, then the cerbot docs describe all the steps for automating the renewal.

You basically have to set up a cronjob that launches the renewal command.
You can edit the crons in you linux machine with the command crontab -e and place something like this at the end of the file:

```<code>0 15 1 * * certbot renew
</code>```

This will run the command the first day of each month and attempt the renewal of your certificate. Check crontab.guru if you need different settings.

If you want to call the cerbot command from a custom script, you can add such script to your cronjob (and save the output to a custom file).

E.g:

```<code>0 15 1 * * python cert_autorenew.py >> cron.log 2>&1
</code>```

Keep in mind that if you want a certificate for app.client1.com, then the renewal request you send, must resolve to the server app.client1.com.
That's how you demonstrate the control over your domain to letsencrypt.

Title: SSL for custom client domains

Body:
As long as app.client1.com is reachable from the internet, you are free to set up a lets-encrypt certificate.

If your applications run on unix-like system, then the cerbot docs describe all the steps for automating the renewal.

You basically have to set up a cronjob that launches the renewal command.
You can edit the crons in you linux machine with the command crontab -e and place something like this at the end of the file:

0 15 1 * * certbot renew

This will run the command the first day of each month and attempt the renewal of your certificate. Check crontab.guru if you need different settings.

If you want to call the cerbot command from a custom script, you can add such script to your cronjob (and save the output to a custom file).

E.g:

0 15 1 * * python cert_autorenew.py >> cron.log 2>&1

Keep in mind that if you want a certificate for app.client1.com, then the renewal request you send, must resolve to the server app.client1.com.
That's how you demonstrate the control over your domain to letsencrypt.


问:
handlerbars.js check if list is empty
Is there a way in Handlebars.js templating to check if the collection or list is null or empty, before going and iterating through the list/collection?</p>

```<code>// if list is empty do some rendering ... otherwise do the normal
{{#list items}}

{{/list}}

{{#each items}}

{{/each}}
</code>```

答:
For anyone who needs to use an {{#each}} on top of {{#if}} (i.e. an if loop inside a for loop). Is they have three different list of arrays.

Using a lookup inside a if statement solves the issue for me. As, the above answers did not solve my issue.

Here is my code,

```<code>{{#each OtherRandomItems}}

  {{this}}

  {{lookup ../AnotherRandomItems @index}}

  {{#if (lookup ../RandomItems @index)}}
  // render items
  {{else}}
  // render empty
  {{/if}}

{{/each}}
</code>```

Title: handlerbars.js check if list is empty

Body:
Is there a way in Handlebars.js templating to check if the collection or list is null or empty, before going and iterating through the list/collection?

// if list is empty do some rendering ... otherwise do the normal
{{#list items}}

{{/list}}

{{#each items}}

{{/each}}

Body:
For anyone who needs to use an {{#each}} on top of {{#if}} (i.e. an if loop inside a for loop). Is they have three different list of arrays.

Using a lookup inside a if statement solves the issue for me. As, the above answers did not solve my issue.

Here is my code,

{{#each OtherRandomItems}}

  {{this}}

  {{lookup ../AnotherRandomItems @index}}

  {{#if (lookup ../RandomItems @index)}}
  // render items
  {{else}}
  // render empty
  {{/if}}

{{/each}}


问:
Problem setting div height in Internet Explorer 7
I have a div with a pretty curve background image so it does rounded corners on all browsers.

The problem is that in Internet explorer, the background image is followed by a background-coloured line. If I set the div's height, Firefox and Chrome will both shrink the height of the div, however IE will not adjust anything.

Here's my CSS. Note that the rest of the CSS is applied in IE (and FF/Chrome) fine.

```<code>#MSBottomSlot .topCurve {
    background:url("images/topCurve.jpg");
    background-repeat:no-repeat;
    height:10px; /* Changing this value does nothing in IE */
    width:100%;
}
</code>```

Is there some IE 'gotcha' regarding height that I'm missing?

Here are some additional details:

The line does not appear in FF or Chrome.

There's little javascript on the page, nothing that would impact how this renders.

Other changes to the css get applied to the div.

答:
if i could understand right, the height is not effected becasue of the line-height and font-size. so you must add</p>

```<code>line-height: 0;
font-size: 0;
</code>```

Body:
I have a div with a pretty curve background image so it does rounded corners on all browsers.

The problem is that in Internet explorer, the background image is followed by a background-coloured line. If I set the div's height, Firefox and Chrome will both shrink the height of the div, however IE will not adjust anything.

Here's my CSS. Note that the rest of the CSS is applied in IE (and FF/Chrome) fine.

#MSBottomSlot .topCurve {
    background:url("images/topCurve.jpg");
    background-repeat:no-repeat;
    height:10px; /* Changing this value does nothing in IE */
    width:100%;
}

Is there some IE 'gotcha' regarding height that I'm missing?

Here are some additional details:

The line does not appear in FF or Chrome.

There's little javascript on the page, nothing that would impact how this renders.

Other changes to the css get applied to the div.

Body:
if i could understand right, the height is not effected becasue of the line-height and font-size. so you must add

line-height: 0;
font-size: 0;


问:
What are the disadvantages of double ended dynamic array data structure?
Dynamic array is a well-known data structure: we allocate, for example, an array for 8 elements and use these slots while inserting to the end of the array. When we are out of slots, we allocate an array of size 16 and so on. And we get O(1) amortized complexity of inserting to the end. Dynamic arrays are implemented in a lot of languages and their standard libraries.

One of the limitations here is that inserting to the beginning of the array is O(n) because there are no free slots at the beginning. But why not to have some free slots both at the beginning and at the end of the array? It makes inserting on both ends O(1) and if we run out of free slots on either side we allocate a bigger array as usual.

It will be less memory efficient than one ended dynamic array (because we need to maintain free slots on both sides), but it's not a bad tradeoff for having O(1) inserts on both sides. Or is it? Are there any other disadvantages? I haven't seen this data structure implemented anywhere, what is its fatal flaw?

答:
Actually Some languages have implemented this kind of data-structure, e.g. deque in C++ STL.

The complexity (efficiency) of common operations on deques is as
  follows:

Random access - constant O(1)

Insertion or removal of elements at the end or beginning - constant O(1)

Insertion or removal of other elements - linear O(n)


问:
ArrayList with formatting
Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)

I tried this:

```<code>    System.out.printf("%10.4", num[0]);
</code>```

which works for the formatting but I can't seem to get the whole arraylist to work.

My array is this:

```<code>    ArrayList<Number> num = new ArrayList<Number>();

    for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        }
</code>```

It works like I said for getting and listing the numbers -- but not in the "correct" way.

I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.

Any help would be amazing!!!

[EDIT]
This worked (from Ole V.V.):

```<code>        for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        System.out.printf("%10.4f%n", num.get(i));
</code>```

[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **

I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!

I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).

答:
Here are a couple of options. First, you may use a for loop like the one you already have:

```<code>    for (int i = 0; i < 20; i++) {
        System.out.printf("%10.4f%n", num.get(i));
    }
</code>```

A terser option is:

```<code>    num.forEach(n -> System.out.printf("%10.4f%n", n));
</code>```

In both case the output goes like

```<code>  186.8143
  129.4201
  169.7405
  ...
</code>```

Your format string, %10.4, was almost correct. You need to add f for formatting a floating-point number. I also added %n for a line break after the number. In Java num[i] works only for arrays, not for ArrayList, you need num.get(i).

Title: ArrayList with formatting

Body:
Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)

I tried this:

    System.out.printf("%10.4", num[0]);

which works for the formatting but I can't seem to get the whole arraylist to work.

My array is this:

    ArrayList<Number> num = new ArrayList<Number>();

    for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        }

It works like I said for getting and listing the numbers -- but not in the "correct" way.

I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.

Any help would be amazing!!!

[EDIT]
This worked (from Ole V.V.):

        for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        System.out.printf("%10.4f%n", num.get(i));

[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **

I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!

I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).

Body:
Here are a couple of options. First, you may use a for loop like the one you already have:

    for (int i = 0; i < 20; i++) {
        System.out.printf("%10.4f%n", num.get(i));
    }

A terser option is:

    num.forEach(n -> System.out.printf("%10.4f%n", n));

In both case the output goes like

  186.8143
  129.4201
  169.7405
  ...

Your format string, %10.4, was almost correct. You need to add f for formatting a floating-point number. I also added %n for a line break after the number. In Java num[i] works only for arrays, not for ArrayList, you need num.get(i).


问:
Localizing extension descriptions before Gecko 1.9
I'm trying to build an extension for Firefox with localized name basing on information from https://developer.mozilla.org/en/Localizing_extension_descriptions (Localizing before Gecko 1.9), but it doesn't work. The error in the browser's Javascript console is:

```
Błąd: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIRDFService.GetLiteral]"  nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)"  location: "JS frame :: file:///C:/Program%20Files/Mozilla%20Firefox%201.5/components/nsExtensionManager.js :: EM_L :: line 225"  data: no]
Plik źródłowy: file:///C:/Program%20Files/Mozilla%20Firefox%201.5/components/nsExtensionManager.js
Wiersz: 225
```

My extension files hierarchy is:

```
gemgecko.xpi:
              /install.rdf
              /components/gemgecko.dll
              /defaults/preferences/prefs.js
              /chrome.manifest
              /chrome/locale/pl/install.properties
              /chrome/locale/en/install.properties
```

/defaults/preferences/prefs.js:

```
pref("extensions.gemgecko@gemius.pl.name", "chrome://gemgecko/locale/en/install.properties");
```

/chrome/locale/en/install.properties:

```
extensions.gemgecko@gemius.pl.name=gemiusAudience study
```

/chrome/locale/pl/install.properties:

```
extensions.gemgecko@gemius.pl.name=Badanie Megapanel PBI/Gemius
```

Can anybody help me to find an error in my extension?

Edit

I'm adding install manifest...

/install.rdf:

```<code><?xml version="1.0" encoding="UTF-8"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
    <em:id>gemgecko@gemius.pl</em:id>
    <em:version>2.01</em:version>
    <em:name>nazwa</em:name>
    <em:creator>tworca</em:creator>
    <em:description>opis</em:description>
    <em:homepageURL>http://www.test.pl</em:homepageURL>

    <em:targetApplication>
        <Description>
            <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox -->
            <em:minVersion>1.5.0</em:minVersion>
            <em:maxVersion>*</em:maxVersion>
        </Description>
    </em:targetApplication>

</Description>

</RDF>
</code>```

I've tested it on Firefox 1.5 and 3.6. On 3.6 everything seems to work OK, but on 1.5 doesn't - the extension manager displays the extension's name from install.rdf not from chrome://gemgecko/locale/install.properties...

答:
chrome://gemgecko/locale/en/install.properties looks to be wrong to me, the /en/ is not part of the chrome: URL, it is substituted when the chrome: URL is converted.

EDIT:

I don't see any chrome registration entries in your chrome.manifest. They should look something like this:

```<code>locale gemgecko pl chrome/locale/pl
locale gemgecko en chrome/locale/en
</code>```

Body:
I'm trying to build an extension for Firefox with localized name basing on information from https://developer.mozilla.org/en/Localizing_extension_descriptions (Localizing before Gecko 1.9), but it doesn't work. The error in the browser's Javascript console is:

Błąd: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIRDFService.GetLiteral]"  nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)"  location: "JS frame :: file:///C:/Program%20Files/Mozilla%20Firefox%201.5/components/nsExtensionManager.js :: EM_L :: line 225"  data: no]
Plik źródłowy: file:///C:/Program%20Files/Mozilla%20Firefox%201.5/components/nsExtensionManager.js
Wiersz: 225

My extension files hierarchy is:

gemgecko.xpi:
              /install.rdf
              /components/gemgecko.dll
              /defaults/preferences/prefs.js
              /chrome.manifest
              /chrome/locale/pl/install.properties
              /chrome/locale/en/install.properties

/defaults/preferences/prefs.js:

pref("extensions.gemgecko@gemius.pl.name", "chrome://gemgecko/locale/en/install.properties");

/chrome/locale/en/install.properties:

extensions.gemgecko@gemius.pl.name=gemiusAudience study

/chrome/locale/pl/install.properties:

extensions.gemgecko@gemius.pl.name=Badanie Megapanel PBI/Gemius

Can anybody help me to find an error in my extension?

Edit

I'm adding install manifest...

/install.rdf:

<?xml version="1.0" encoding="UTF-8"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
    gemgecko@gemius.pl
    2.01
    nazwa
    tworca
    opis
    http://www.test.pl

        <Description>
            {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
            1.5.0
            *
        </Description>

</Description>

</RDF>

I've tested it on Firefox 1.5 and 3.6. On 3.6 everything seems to work OK, but on 1.5 doesn't - the extension manager displays the extension's name from install.rdf not from chrome://gemgecko/locale/install.properties...

Body:
chrome://gemgecko/locale/en/install.properties looks to be wrong to me, the /en/ is not part of the chrome: URL, it is substituted when the chrome: URL is converted.

EDIT:

I don't see any chrome registration entries in your chrome.manifest. They should look something like this:

locale gemgecko pl chrome/locale/pl
locale gemgecko en chrome/locale/en


问:
How to get the http get response data value to outer scope
```<code>.config([
    '$provide',
    function ($provide) {
        'use strict';

        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/')

       .then(function (response) {
            console.log("dddd" + response.data.url);

            apiUrl = response.data.url;

          });

       console.log(apiUrl);
</code>```

//This print as Undefined

```<code>        $provide.constant('GLOBAL', global);
    }
]);
</code>```

when i print the apiUrl value tetrived from http get service print as undefined.

can some one hep me to get the value of response.data.url to outer scope.

Edit:

```<code>    var apiUrl;

    var initInjector = angular.injector(['ng']);

    var self = this;

    initInjector.get('$http').get('customer/api/')

    .then(function(response) {

        console.log("ddddd" + response.data.url); //print value
        self.apiUrl = response.data.url;

        console.log("selff" +self.apiUrl); //print value
    });

    console.log("outerr" +self.apiUrl); // print undefined
</code>```

答:
Promises can't be used like synchronous code because they return a promise immediately. You should wait for the promise to complete before setting your global values.

Instead of doing

```<code>a = {}
a.key1 = Promise().then(()=>{
  return 1
})
a.key2 = Promise().then(()=>{
  return 2
})
</code>```

Do something like this instead (with bluebird):

```<code>Promise.all([
    Promise().then(()=>{
      return 1
    }),
    Promise().then(()=>{
      return 2
    }),
]).then(result => {
  a.key1 = result[0]
  a.key2 = result[1]
})
</code>```

Alternatively you can look into the async/await syntax es7 provides

Body:
.config([
    '$provide',
    function ($provide) {
        'use strict';

        var initInjector = angular.injector(['ng']);

        var apiUrl;

        initInjector.get('$http').get('customer/api/')

       .then(function (response) {
            console.log("dddd" + response.data.url);

            apiUrl = response.data.url;

          });

       console.log(apiUrl);

//This print as Undefined

        $provide.constant('GLOBAL', global);
    }
]);

when i print the apiUrl value tetrived from http get service print as undefined.

can some one hep me to get the value of response.data.url to outer scope.

Edit:

    var apiUrl;

    var initInjector = angular.injector(['ng']);

    var self = this;

    initInjector.get('$http').get('customer/api/')

    .then(function(response) {

        console.log("ddddd" + response.data.url); //print value
        self.apiUrl = response.data.url;

        console.log("selff" +self.apiUrl); //print value
    });

    console.log("outerr" +self.apiUrl); // print undefined

Body:
Promises can't be used like synchronous code because they return a promise immediately. You should wait for the promise to complete before setting your global values.

Instead of doing

a = {}
a.key1 = Promise().then(()=>{
  return 1
})
a.key2 = Promise().then(()=>{
  return 2
})

Do something like this instead (with bluebird):

Promise.all([
    Promise().then(()=>{
      return 1
    }),
    Promise().then(()=>{
      return 2
    }),
]).then(result => {
  a.key1 = result[0]
  a.key2 = result[1]
})

Alternatively you can look into the async/await syntax es7 provides


问:
SpannableString is not working in a Dialog
I want to show the spanString in Bold style and rest of the string in normal style in TextView. But the whole TextView showed in normal style only.   Please help me.

```<code>if ((mStoreListValue.get(pos).getStoreStatus().equals("CLOSED"))){

   final Dialog dialog = new Dialog(v.getRootView().getContext(), android.R.style.Theme_Translucent_NoTitleBar);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   dialog.getWindow().setContentView(R.layout.resclosed_dialog);
   ImageView btn_close =  dialog.findViewById(R.id.close_btn);
   TextView txt_close =  dialog.findViewById(R.id.tv_closed);

   SpannableString spanString = new SpannableString(sname);
   spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

   txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));

   btn_close.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
              dialog.dismiss();
         }
    });
  dialog.show();
</code>```

答:
Thats because you just concat SpannableString with String which will be result as toString()(a Normal String with hash code of object). Use a single String with multiple Span.

See the following example.

```<code>    String s1="My app";
    String s2= "Close";
    SpannableString spanString = new SpannableString(s1+s2);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spanString.setSpan(new StyleSpan(Typeface.NORMAL), s1.length(), (s1+s2).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spanString);
</code>```

Body:
I want to show the spanString in Bold style and rest of the string in normal style in TextView. But the whole TextView showed in normal style only.   Please help me.

if ((mStoreListValue.get(pos).getStoreStatus().equals("CLOSED"))){

   final Dialog dialog = new Dialog(v.getRootView().getContext(), android.R.style.Theme_Translucent_NoTitleBar);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   dialog.getWindow().setContentView(R.layout.resclosed_dialog);
   ImageView btn_close =  dialog.findViewById(R.id.close_btn);
   TextView txt_close =  dialog.findViewById(R.id.tv_closed);

   SpannableString spanString = new SpannableString(sname);
   spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

   txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));

   btn_close.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
              dialog.dismiss();
         }
    });
  dialog.show();

Body:
Thats because you just concat SpannableString with String which will be result as toString()(a Normal String with hash code of object). Use a single String with multiple Span.

See the following example.

    String s1="My app";
    String s2= "Close";
    SpannableString spanString = new SpannableString(s1+s2);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spanString.setSpan(new StyleSpan(Typeface.NORMAL), s1.length(), (s1+s2).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spanString);


问:
Moving array to charsequence using BIFs in (free)RPGLE
Can someone tell me how to convert a char array to a character?

I've defined

```<code> D  charseq                     100a   value
</code>```

and

```<code> D  chrseq         s              1a   dim(100)
</code>```

Now I reversed charseq and stored each character using BIF %subst(string:index:length) in the corresponding field in chrseq:

```<code> C     1             do        101           x
 C                   eval      chrseq(101-x) = %subst(charseq:x:1)
 C                   enddo
</code>```

But now here is my problem: How do I convert the chrseq to my charseq?
In good old RPG/400 I'd done this via MOVEA but is there any (modern) RPGLE version??

Here's the code:

```<code> P*            -------------------------------------------------------------
 P*            getLastChar - Get last non-blank char in parameter
 P*            -------------------------------------------------------------
 P getLastChar     b                   export
 D getLastChar     pi             1a
 D*  Input-parameter
 D  charseq                     100a   value
 D*  Local fields
 D  lastChar       s              1a   inz(' ')
 D  chrseq         s              1a   dim(100)
 C
 C*            -------------------------------------------------------------
 C*            Error handling
 C*            -------------------------------------------------------------
 C     charseq       ifeq      *blanks
 C                   return    x'00'
 C                   endif
 C
 C*            -------------------------------------------------------------
 C*            Reverse input char sequence
 C*            -------------------------------------------------------------
 C     1             do        101           x
 C                   eval      chrseq(101-x) = %subst(charseq:x:1)
 C                   enddo
 C*  Now: How do I get chrseq(1) to chrseq(100) into charseq back?
 C*            -------------------------------------------------------------
 C*            Get last non-blank char
 C*            -------------------------------------------------------------
 C                   eval      charseq = %triml(charseq)
 C                   eval      lastChar = %subst(charseq:1:1)
 C
 C
 C                   return    lastChar
 C
 P getLastChar     e
</code>```

Thanks in advance!

答:
This trick seems to work for me

```<code>charseq = %Str(%Addr(chrseq));
</code>```

But there are a couple of other options to this. First, you could use a pointer and the based keyword over charseq

```<code>Dcl-S charptr Pointer Inz(%Addr(charseq));
Dcl-S charseq Char(100);
Dcl-S chrseq  Char(1) Dim(100) Based(charptr);
</code>```

Or you could remove the pointer and based keyword to use a data-structure and the pos keyword instead

```<code>Dcl-Ds memoryDS;
  charseq Char(100);
  chrseq Char(1) Dim(100) Pos(1);
End-ds;
</code>```

Then, anytime you assign to a chrseq index it will be over charseq memory

```<code>//Any changes to chrseq will happen in charseq memory
chrseq(1) = 'H';
chrseq(2) = 'e';
chrseq(3) = 'l';
chrseq(4) = 'l';
chrseq(5) = 'o';

Dsply %Subst(charseq:1:52);
</code>```

Body:
Can someone tell me how to convert a char array to a character?

I've defined

 D  charseq                     100a   value

and

 D  chrseq         s              1a   dim(100)

Now I reversed charseq and stored each character using BIF %subst(string:index:length) in the corresponding field in chrseq:

 C     1             do        101           x
 C                   eval      chrseq(101-x) = %subst(charseq:x:1)
 C                   enddo

But now here is my problem: How do I convert the chrseq to my charseq?
In good old RPG/400 I'd done this via MOVEA but is there any (modern) RPGLE version??

Here's the code:

 P*            -------------------------------------------------------------
 P*            getLastChar - Get last non-blank char in parameter
 P*            -------------------------------------------------------------
 P getLastChar     b                   export
 D getLastChar     pi             1a
 D*  Input-parameter
 D  charseq                     100a   value
 D*  Local fields
 D  lastChar       s              1a   inz(' ')
 D  chrseq         s              1a   dim(100)
 C
 C*            -------------------------------------------------------------
 C*            Error handling
 C*            -------------------------------------------------------------
 C     charseq       ifeq      *blanks
 C                   return    x'00'
 C                   endif
 C
 C*            -------------------------------------------------------------
 C*            Reverse input char sequence
 C*            -------------------------------------------------------------
 C     1             do        101           x
 C                   eval      chrseq(101-x) = %subst(charseq:x:1)
 C                   enddo
 C*  Now: How do I get chrseq(1) to chrseq(100) into charseq back?
 C*            -------------------------------------------------------------
 C*            Get last non-blank char
 C*            -------------------------------------------------------------
 C                   eval      charseq = %triml(charseq)
 C                   eval      lastChar = %subst(charseq:1:1)
 C
 C
 C                   return    lastChar
 C
 P getLastChar     e

Thanks in advance!

Body:
This trick seems to work for me

charseq = %Str(%Addr(chrseq));

But there are a couple of other options to this. First, you could use a pointer and the based keyword over charseq

Dcl-S charptr Pointer Inz(%Addr(charseq));
Dcl-S charseq Char(100);
Dcl-S chrseq  Char(1) Dim(100) Based(charptr);

Or you could remove the pointer and based keyword to use a data-structure and the pos keyword instead

Dcl-Ds memoryDS;
  charseq Char(100);
  chrseq Char(1) Dim(100) Pos(1);
End-ds;

Then, anytime you assign to a chrseq index it will be over charseq memory

//Any changes to chrseq will happen in charseq memory
chrseq(1) = 'H';
chrseq(2) = 'e';
chrseq(3) = 'l';
chrseq(4) = 'l';
chrseq(5) = 'o';

Dsply %Subst(charseq:1:52);


答:
Use this

```<code>SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString spanString = new SpannableString(sname);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(spanString);
builder.append(mContext.getResources().getString(R.string.closed));
txt_close.setText(builder);
</code>```

Instead of this

```<code>txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));
</code>```

Title: SpannableString is not working in a Dialog

Body:
Use this

SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString spanString = new SpannableString(sname);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(spanString);
builder.append(mContext.getResources().getString(R.string.closed));
txt_close.setText(builder);

Instead of this

txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));


问:
VB Script date formats "YYYYMMDDHHMMSS"
As title surgest I need to fomat the now () function to display on the format "YYYYMMDDHHMMSS"

I did have a play about trying to split it out but this drops leading zeros that I need to retain

example below mydt was "27/02/2015 13:02:27"

```<code>mydt = now()

MSGBOX Year(mydt)& Month(mydt)& Day(mydt)& Hour(mydt)& Minute(mydt)& second(mydt)
</code>```

this returns "201522713227"

i need it to return "20150227130227" i could use a if < 10 but there must be a slicker way

答:
Here is my full method I used to make it nice.
Good for parsing the data for SQL.</p>

```<code>function getDateFormatedWithDash(DateVal)
    rtnDateStr = year(DateVal)
    m=month(DateVal)
    d=day(DateVal)
    h=Hour(DateVal)
    Min=Minute(DateVal)
    sec=second(DateVal)

    if month(DateVal)<10 then
        m="0"&month(DateVal)
    end if

    if day(DateVal)<10 then
        d="0"&day(DateVal)
    end if

    if Hour(DateVal)<10 then
        h="0"&Hour(DateVal)
    end if

    if Minute(DateVal)<10 then
        Min="0"&Minute(DateVal)
    end if

    if second(DateVal)<10 then
        sec="0"&second(DateVal)
    end if

    rtnDateStr = rtnDateStr&"-"&m&"-"&d&" "&h&":"&Min&":"&sec
    getDateFormatedWithDash=rtnDateStr
end function
</code>```

Title: VB Script date formats "YYYYMMDDHHMMSS"

Body:
As title surgest I need to fomat the now () function to display on the format "YYYYMMDDHHMMSS"

I did have a play about trying to split it out but this drops leading zeros that I need to retain

example below mydt was "27/02/2015 13:02:27"

mydt = now()

MSGBOX Year(mydt)& Month(mydt)& Day(mydt)& Hour(mydt)& Minute(mydt)& second(mydt)

this returns "201522713227"

i need it to return "20150227130227" i could use a if < 10 but there must be a slicker way

Body:
Here is my full method I used to make it nice.
Good for parsing the data for SQL.

function getDateFormatedWithDash(DateVal)
    rtnDateStr = year(DateVal)
    m=month(DateVal)
    d=day(DateVal)
    h=Hour(DateVal)
    Min=Minute(DateVal)
    sec=second(DateVal)

    if month(DateVal)<10 then
        m="0"&month(DateVal)
    end if

    if day(DateVal)<10 then
        d="0"&day(DateVal)
    end if

    if Hour(DateVal)<10 then
        h="0"&Hour(DateVal)
    end if

    if Minute(DateVal)<10 then
        Min="0"&Minute(DateVal)
    end if

    if second(DateVal)<10 then
        sec="0"&second(DateVal)
    end if

    rtnDateStr = rtnDateStr&"-"&m&"-"&d&" "&h&":"&Min&":"&sec
    getDateFormatedWithDash=rtnDateStr
end function


问:
ASP.net using a form to insert data into an sql server table
Hi
in php i would do a form with an action to lets say a process.php page and in that page i would take the post values and using a mysql_query would do an insertion.
now i am lost ,i am trying to create a from and do an inserstion in ASP.net with sql server 2008 using visual studio 2010.

i have defined a sql db in the App_Data folder.
basicly what i need (unless there is a better way) is:

how do i get the post values.

how do i insert them into the db.

thanks.

答:
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

```<code><body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>
</code>```

Great, now every asp object IS an object. So you can access it in the asp's CS code.
The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

```<code>void Button1Click(Object sender,EventArgs e) { }
</code>```

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

```<code>String firstBox = TextBox1.Text;
</code>```

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Body:
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code.
The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.


问:
Missing .jar in Java Build Path with backslaches in path
I am adding new version of TestNG library. So I downloaded new testng-6.13.1.jar to the folder .../tools/testng, and trying to add reference to it the same way I did for previous version. But new jar is added with backslashes in path and is defined as (missing) by the IDE:

Why is it so?

答:
As .jar file was inside of the project, IDE could not see it untill I did refresh in Package Explorer:

So simply right click on the destination folder of library and select Refresh or press F5.


问:
Ansible: How to pip install with --upgrade
I want to pip install with --upgrade, using Ansible.

What's the syntax?

答:
```<code>- name: install the package, force upgrade
  pip:
    name: <your package name>
    state: latest
</code>```

Or with:

```<code>- name: install the package, force reinstall to the latest version
  pip:
    name: <your package name>
    state: forcereinstall
</code>```

Body:
- name: install the package, force upgrade
  pip:
    name: <your package name>
    state: latest

Or with:

- name: install the package, force reinstall to the latest version
  pip:
    name: <your package name>
    state: forcereinstall