Title: Interpolating data points in Curve Fitting Tool in Matlab 2017

Body: I have a set of 13 experimental points with X ranging from 0 to 100 in unequal intervals and corresponding values of Y. Using curve fitting tool (Interpolant, PCHIP) I can get a graph and also get values of intermittent points using data cursor. However I need 1000 values spaced at an equal interval of 0.1 from 0 to 100. How can I get these 1000 values from the tool? There used to be an 'evaluate' option in older matlab, but I do not see that in this one.

Body:
Here's how to get the equally-spaced interpolation data in the script:

% Your data
x = [0;4;6;10;11;13;17;23;24;34;35;37;39;40;49;58;78;82;90;94;100];
y = sin([0.51;1.15;1.19;1.86;1.92;2.32;2.74;2.81;2.83;3.44;3.93;...
     4.07;4.08;4.32;4.6;4.68;4.87;4.9;4.99;5.14;5.84]*3);

% Create new equally-distant baseline
x2 = linspace(0,100,1000);

% Fit your data, compute new values of y for x2
y2 = pchip(x,y,x2);

% Plot everything
figure
hold all
plot(x,y,'kx')
plot(x2,y2,'r-');


来源: stackexchange

问:
Java consrtuctor and toString function
Could you please provide the answer for the below problem

Create a class named Shipment with the following private member variables / attributes

```<code>int id
String shipperName
String modeOfTransportation
Float totalWeight
String arrivalPort
String departurePort
</code>```

Create a private static variable nextShipmentId in Shipment class and initialise it to 1000.

Create a Constructor which accepts 6 arguments in the argument order (id,shipperName,modeOfTransportation,totalWeight,arrivalPort,departurePort)

Create a static method createNewShipment() - which accepts the shipment details in the parameter and generates the shipment object and assigns the shipment id and return the shipment object. For returning the object pass the values in the constructor and return it.

Display the shipment details by overriding the toString() method in Shipment class.

Use String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort)  to format the string.

Sample Input and Output :

Enter the number of shipments :
2
Enter the shipment 1 details
Enter the shipper name :
AGCI
Enter the mode of transportation :
Air
Enter the total weight :
300
Enter the arrival port :
India
Enter the departure port :
America
Enter the shipment 2 details
Enter the shipper name :
DHL Services
Enter the mode of transportation :
Water
Enter the total weight :
500
Enter the arrival port :
Cochin
Enter the departure port :
Srilanka

Shipment details are
Id   Shippername  Mode of transportation  Total weight  Arrival port  Departure port

1001 AGCI         Air                     300Kg         India         America

1002 DHL Services Water                   500Kg         Cochin        Srilanka

答:
```<code>public class Shipment{

    Shipment(int id, String shipperName, String modeOfTransportation,
                Double totalWeight, String arrivalPort, String departurePort){
        this.nextShipment = 1000;
        this.shipperName = shipperName;
        this.modeOfTransportation = modeOfTransportation;
        this.totalWeight = totalWeight;
        this.arrivalPort = arrivalPort;
        this.departurePort = departurePort;
    }

    public static Shipment createNewShipment(int id, String shipperName, String modeOfTransportation,
                Double totalWeight, String arrivalPort, String departurePort){

        Shipment shipment = new Shipment(id, shipperName, modeOfTransportation, totalWeight, arrivalPort, departurePort);

        return shipment;
    }

    @Override
    public String toString(){
        return String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort);
    }

    private int id;
    private String shipperName;
    private String modeOfTransportation;
    private Double totalWeight;
    private String arrivalPort;
    private String departurePort;
    private static int nextShipment;
}
</code>```

Normally Stackoverflow is no code-writing service, but i had nothing to do so here is your code :)

ContentLicense: CC BY-SA 3.0

Title: Java consrtuctor and toString function

Body:
Could you please provide the answer for the below problem

Create a class named Shipment with the following private member variables / attributes

int id
String shipperName
String modeOfTransportation
Float totalWeight
String arrivalPort
String departurePort

Create a private static variable nextShipmentId in Shipment class and initialise it to 1000.

Create a Constructor which accepts 6 arguments in the argument order (id,shipperName,modeOfTransportation,totalWeight,arrivalPort,departurePort)

Create a static method createNewShipment() - which accepts the shipment details in the parameter and generates the shipment object and assigns the shipment id and return the shipment object. For returning the object pass the values in the constructor and return it.

Display the shipment details by overriding the toString() method in Shipment class.

Use String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort)  to format the string.

Sample Input and Output :

Enter the number of shipments :
2
Enter the shipment 1 details
Enter the shipper name :
AGCI
Enter the mode of transportation :
Air
Enter the total weight :
300
Enter the arrival port :
India
Enter the departure port :
America
Enter the shipment 2 details
Enter the shipper name :
DHL Services
Enter the mode of transportation :
Water
Enter the total weight :
500
Enter the arrival port :
Cochin
Enter the departure port :
Srilanka

Shipment details are
Id   Shippername  Mode of transportation  Total weight  Arrival port  Departure port

1001 AGCI         Air                     300Kg         India         America

1002 DHL Services Water                   500Kg         Cochin        Srilanka

Body:
public class Shipment{

    Shipment(int id, String shipperName, String modeOfTransportation,
                Double totalWeight, String arrivalPort, String departurePort){
        this.nextShipment = 1000;
        this.shipperName = shipperName;
        this.modeOfTransportation = modeOfTransportation;
        this.totalWeight = totalWeight;
        this.arrivalPort = arrivalPort;
        this.departurePort = departurePort;
    }

    public static Shipment createNewShipment(int id, String shipperName, String modeOfTransportation,
                Double totalWeight, String arrivalPort, String departurePort){

        Shipment shipment = new Shipment(id, shipperName, modeOfTransportation, totalWeight, arrivalPort, departurePort);

        return shipment;
    }

    @Override
    public String toString(){
        return String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort);
    }

    private int id;
    private String shipperName;
    private String modeOfTransportation;
    private Double totalWeight;
    private String arrivalPort;
    private String departurePort;
    private static int nextShipment;
}

Normally Stackoverflow is no code-writing service, but i had nothing to do so here is your code :)


问:
Why is the state of one UICollectionViewCell affecting another?
I have an app written in swift in which i have cells that display products. I have a button to add the item to cart. When a product is out of stock, in the UICollectionViewCell's subclass, I use this code to disable the 'Add to Cart' button.

```<code>class Product: UICollectionViewCell {
    //Some code here
    //And here

    if(data.stock < 0){
      addToCartButton.isHidden = true;
    }

 }
</code>```

When i scroll through the page, the Add to Cart button in other cells also get hidden, even if they don't satisfy the condition data.stock < 0. What is happening and how do I overcome this?

答:
What you missed is else condition buddy :)

```<code>    if(data.stock < 0){
        addToCartButton.isHidden = true;
    }
    else {
        addToCartButton.isHidden = false;
    }
</code>```

OR

In collectionView cells gets reused when you scroll. You should make use of prepareForReuse to reset the state of UIComponents before they get reused.

```<code>override func prepareForReuse() {
    //reset all the fields of cell
    addToCartButton.isHidden = false
}
</code>```

Using prepareForReuse is just a best practice and will solve your problem. But the real cause of the issue was missing else condition

Body:
I have an app written in swift in which i have cells that display products. I have a button to add the item to cart. When a product is out of stock, in the UICollectionViewCell's subclass, I use this code to disable the 'Add to Cart' button.

class Product: UICollectionViewCell {
    //Some code here
    //And here

    if(data.stock < 0){
      addToCartButton.isHidden = true;
    }

 }

When i scroll through the page, the Add to Cart button in other cells also get hidden, even if they don't satisfy the condition data.stock < 0. What is happening and how do I overcome this?

Body:
What you missed is else condition buddy :)

    if(data.stock < 0){
        addToCartButton.isHidden = true;
    }
    else {
        addToCartButton.isHidden = false;
    }

OR

In collectionView cells gets reused when you scroll. You should make use of prepareForReuse to reset the state of UIComponents before they get reused.

override func prepareForReuse() {
    //reset all the fields of cell
    addToCartButton.isHidden = false
}

Using prepareForReuse is just a best practice and will solve your problem. But the real cause of the issue was missing else condition


问:
php file_get_contents() converts html entities like ö to ö
I try to display the contents of a php file in a textarea with

```<code><textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>
</code>```

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

答:
```<code><textarea ...>
<?php echo htmlentities(file_get_contents("file.php")); ?>
</textarea>
</code>```

Example

Convert some characters to HTML entities:

```<code><?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';
echo htmlentities($str);
?>
</code>```

The HTML output of the code above will be (View Source):

```<code><a href="https://www.w3schools.com">Go to w3schools.com</a>
</code>```

The browser output of the code above will be:

```<code><a href="https://www.w3schools.com">Go to w3schools.com</a>
</code>```

Body:
I try to display the contents of a php file in a textarea with

<textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

Body:
<textarea ...>
<?php echo htmlentities(file_get_contents("file.php")); ?>
</textarea>

Example

Convert some characters to HTML entities:

<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a>';
echo htmlentities($str);
?>

The HTML output of the code above will be (View Source):

&lt;a href=&quot;https://www.w3schools.com&quot;&gt;Go to w3schools.com&lt;/a&gt;

The browser output of the code above will be:

<a href="https://www.w3schools.com">Go to w3schools.com</a>


问:
Tensorflow object detection API:Sample program not working as expected
I am running sample program which comes packaged with Tensorflow object detection API(object_detection_tutorial.ipynb).
Program runs fine with no error, but bounding boxes are not diaplayed at all.

My environment is as follows:

Windows 10

Python 3.6.3

What can be the reason?

With regards

Manish

答:
It seems that the latest version of the model ssd_mobilenet_v1_coco_2017_11_08 doesn't work and outputs abnormally low value. Replacing it in the Jupyter Notebook with an older version of the model works fine for me:

```<code># What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
</code>```

Ref: https://github.com/tensorflow/models/issues/2773

Body:
It seems that the latest version of the model ssd_mobilenet_v1_coco_2017_11_08 doesn't work and outputs abnormally low value. Replacing it in the Jupyter Notebook with an older version of the model works fine for me:

# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'

Ref: https://github.com/tensorflow/models/issues/2773


问:
Django error: UNIQUE constraint failed: auth_user.username
I need to register a user by sending an activation token to her Email address. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register her using custom built-in functions register and activate.

My code is as follows:

forms.py

```<code>class UserRegisterForm(forms.Form, UserCreationForm):

username = forms.CharField(max_length=20)
date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField()

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old and above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2
</code>```

views.py

```<code>def register(request):
if request.method == 'POST':
    form = UserRegisterForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password1')
        new_user = User.objects.create(username=username, email=email, password=password)
        new_user = form.save(commit=False)
        #new_user.set_password(password) # hashes the password
        new_user.is_active = False
        new_user.save()
        current_site = get_current_site(request)
        message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
        })
        mail_subject = 'Activate your Frac account.'
        #to_email = form.cleaned_data.get('email')
        email = form.cleaned_data.get('email')
        to_email = EmailMessage(mail_subject, message, to=[email])#[to_email])
        to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
else:
    form = UserRegisterForm()

return render(request, 'register.html', {'form': form})

spec_backend = 'django.contrib.auth.backends.ModelBackend'

def activate(request, uidb64, token):
try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    new_user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
    new_user = None
if new_user is not None and account_activation_token.check_token(new_user, token):
    new_user.is_active = True
    new_user.save()
    return render(request, 'register_complete.html', {})
else:
    return render(request, 'registration_incomplete.html', {})
</code>```

What is causing such an error? I researched similar posts on this platform but each case is unique.

答:
You are getting the unique constraint error because you are trying to create the same user twice:

```<code>new_user = User.objects.create(username=username, email=email, password=password)
new_user = form.save(commit=False)
...
new_user.save()
</code>```

Since you are using a model form, you don't need to call User.objects.create() manually. Remove that line. You can also remove the three lines above that fetch username, email and password from the cleaned data.

ContentLicense: CC BY-SA 4.0

Body:
I need to register a user by sending an activation token to her Email address. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register her using custom built-in functions register and activate.

My code is as follows:

forms.py

class UserRegisterForm(forms.Form, UserCreationForm):

username = forms.CharField(max_length=20)
date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField()

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old and above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

views.py

def register(request):
if request.method == 'POST':
    form = UserRegisterForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password1')
        new_user = User.objects.create(username=username, email=email, password=password)
        new_user = form.save(commit=False)
        #new_user.set_password(password) # hashes the password
        new_user.is_active = False
        new_user.save()
        current_site = get_current_site(request)
        message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
        })
        mail_subject = 'Activate your Frac account.'
        #to_email = form.cleaned_data.get('email')
        email = form.cleaned_data.get('email')
        to_email = EmailMessage(mail_subject, message, to=[email])#[to_email])
        to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
else:
    form = UserRegisterForm()

return render(request, 'register.html', {'form': form})

spec_backend = 'django.contrib.auth.backends.ModelBackend'

def activate(request, uidb64, token):
try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    new_user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
    new_user = None
if new_user is not None and account_activation_token.check_token(new_user, token):
    new_user.is_active = True
    new_user.save()
    return render(request, 'register_complete.html', {})
else:
    return render(request, 'registration_incomplete.html', {})

What is causing such an error? I researched similar posts on this platform but each case is unique.

Body:
You are getting the unique constraint error because you are trying to create the same user twice:

new_user = User.objects.create(username=username, email=email, password=password)
new_user = form.save(commit=False)
...
new_user.save()

Since you are using a model form, you don't need to call User.objects.create() manually. Remove that line. You can also remove the three lines above that fetch username, email and password from the cleaned data.


问:
ansible: how to share varibles between roles
I need to permform few task on same hosts but wanted to group the tasks into the different roles which need to share some output to each other. Consider below example

```<code>│── hosts
├── playbooks
│   ├── Playbook1.yml
│
├── roles
│   └── role1
│       ├── files
│       │   └── project1.conf
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [Creates variable role1_a, role1_b]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role2
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_a and creates variable role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role3
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_b and role2 role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│
</code>```

Is there any way to collect output of role1 and pass it to role2 and role3 like

```<code>- hosts: localhost
  roles:
    - role: role1_a, role1_b = {role1}
    - role: role2_c = {role2 role1_a: role1_a, role1_b: role1_b}
    - role: {role2 role1_b: role1_b role2_c: role2_c}
</code>```

or anyother mechanism to share the variable between the roles ?

答:
What about including tasks in role1 to store the value of role1_a and role1_b into the variable definition of role2 and role3, by combining local_action with lineinfile

```<code>- name: Copy value of role1_a to var definition of role2
  local_action:
    module: lineinfile
    path: ~/ansible/roles/role2/vars/main.yml
    regexp: '^role1_a'
    line: "role1_a: {{ role1_a }}"

- name: Copy value of role1_b to var definition of role3
  local_action:
    module: lineinfile
    dest: ~/ansible/roles/role3/vars/main.yml
    regexp: '^role1_b'
    line: "role1_b: {{ role1_b }}"
</code>```

Body:
I need to permform few task on same hosts but wanted to group the tasks into the different roles which need to share some output to each other. Consider below example

│── hosts
├── playbooks
│   ├── Playbook1.yml
│
├── roles
│   └── role1
│       ├── files
│       │   └── project1.conf
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [Creates variable role1_a, role1_b]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role2
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_a and creates variable role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role3
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_b and role2 role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│

Is there any way to collect output of role1 and pass it to role2 and role3 like

- hosts: localhost
  roles:
    - role: role1_a, role1_b = {role1}
    - role: role2_c = {role2 role1_a: role1_a, role1_b: role1_b}
    - role: {role2 role1_b: role1_b role2_c: role2_c}

or anyother mechanism to share the variable between the roles ?

Body:
What about including tasks in role1 to store the value of role1_a and role1_b into the variable definition of role2 and role3, by combining local_action with lineinfile

- name: Copy value of role1_a to var definition of role2
  local_action:
    module: lineinfile
    path: ~/ansible/roles/role2/vars/main.yml
    regexp: '^role1_a'
    line: "role1_a: {{ role1_a }}"

- name: Copy value of role1_b to var definition of role3
  local_action:
    module: lineinfile
    dest: ~/ansible/roles/role3/vars/main.yml
    regexp: '^role1_b'
    line: "role1_b: {{ role1_b }}"


问:
Oracle forms 11: Changing label of tab page very slow
I have a tab page in oracle forms. On the first tab, I have a master table. The master table has a few detail tables, which I show on other tab pages.

I would like to show the amount of records of the detail table, in the label of the tab page.

I change the labels in the when new record instance trigger of the master table. The problem is that

```<code>set_tab_page_property('CANVAS.DETAIL', label, 'Detail (' || amount || ')');
</code>```

is extremely slow.

In Oracle Forms 6i, the change happens in a blink of an eye, in Oracle Forms 11, it takes about 8 seconds to load the new lables of the tab pages.

Does anyone have an idea how I can improve the performance of set_tab_page_property in Oracle Forms 11?

答:
I found the following solution:

```<code>hide_view('CANVAS_TAB');
set_tab_page_property('CANVAS_TAB.MY_TAB', label, 'TAB Label (' || :global.row_count || ')');
show_view('CANVAS_TAB');
</code>```

Principle is to hide canvas before to change label and display it again after. There is no blink effect at exec time. it works fine in my case.
Let try and revert.

Body:
I have a tab page in oracle forms. On the first tab, I have a master table. The master table has a few detail tables, which I show on other tab pages.

I would like to show the amount of records of the detail table, in the label of the tab page.

I change the labels in the when new record instance trigger of the master table. The problem is that

set_tab_page_property('CANVAS.DETAIL', label, 'Detail (' || amount || ')');

is extremely slow.

In Oracle Forms 6i, the change happens in a blink of an eye, in Oracle Forms 11, it takes about 8 seconds to load the new lables of the tab pages.

Does anyone have an idea how I can improve the performance of set_tab_page_property in Oracle Forms 11?

Body:
I found the following solution:

hide_view('CANVAS_TAB');
set_tab_page_property('CANVAS_TAB.MY_TAB', label, 'TAB Label (' || :global.row_count || ')');
show_view('CANVAS_TAB');

Principle is to hide canvas before to change label and display it again after. There is no blink effect at exec time. it works fine in my case.
Let try and revert.


问:
Cant access Postgres, getting an error about “/var/run/postgresql/.s.PGSQL.5432”
I was running a Django application with Postgres as backend database. It was working fine. All of a sudden, today I saw my database connection is refusing in the production server. So I logged into my server and tried to:

```<code>psql
</code>```

and then it was showing this error:

```<code> psql: could not connect to server: No such file or directory
 Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

The file listed above does not seem to exist.

I checked if my Postgres is running or not with:

```<code> /etc/init.d/postgresql status
</code>```

and it was returning with SUCCESS message.

```<code>postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Thu 2017-11-16 10:03:41 UTC; 55min ago
  Process: 4701 ExecReload=/bin/true (code=exited, status=0/SUCCESS)
  Process: 4899 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 4899 (code=exited, status=0/SUCCESS)

Nov 16 10:03:41 median systemd[1]: Starting PostgreSQL RDBMS...
Nov 16 10:03:41 median systemd[1]: Started PostgreSQL RDBMS.
</code>```

Still, I stopped and started postgres again.

I checked if there any other postgres task running or not with:

```<code>ps -ef | grep postgres
</code>```

And it returned:

```<code>root      5210  5117  0 10:21 pts/0    00:00:00 grep --color=auto postgres
</code>```

So there is no other Postgres.

I even checked if my Postgres accidentally got deleted or not with

```<code>dpkg -l | grep postgres
</code>```

and it returned

```<code>ii  postgresql                           9.5+173ubuntu0.1                             all          object-relational SQL database (supported version)
ii  postgresql-9.5                       9.5.10-0ubuntu0.16.04                        amd64        object-relational SQL database, version 9.5 server
ii  postgresql-client-9.5                9.5.10-0ubuntu0.16.04                        amd64        front-end programs for PostgreSQL 9.5
ii  postgresql-client-common             173ubuntu0.1                                 all          manager for multiple PostgreSQL client versions
ii  postgresql-common                    173ubuntu0.1                                 all          PostgreSQL database-cluster manager
ii  postgresql-contrib-9.5               9.5.10-0ubuntu0.16.04                        amd64        additional facilities for PostgreSQL
</code>```

So there is no rc instead of ii, which means it has not been uninstalled.

I have tried every other solution in the internet but uninstalling Postgres. Didn't work for me. I might be doing something very silly. I don't want to uninstall and lose my data.

答:
Run the following command to check which port your PostgreSQL server is actually running on:

```<code>[root@server ~]# netstat -a | grep .s.PGSQL
unix  2      [ ACC ]     STREAM     LISTENING     2534417 /var/run/postgresql/.s.PGSQL.5432
</code>```

I can see from this output that my server is listening on port 5432 and also that the file is created in /var/run/postgresql/.s.PGSQL.5432

You can then update /etc/init.d/postgresql to include the lines

```<code>PGPORT=5432
export PGPORT
</code>```

and update your postgresql.conf file which is located in your data directory and set the port key/value to port=5432

and then restart your PostgreSQL server

```<code>[root@server] service postgresql restart
</code>```

Body:
I was running a Django application with Postgres as backend database. It was working fine. All of a sudden, today I saw my database connection is refusing in the production server. So I logged into my server and tried to:

psql

and then it was showing this error:

 psql: could not connect to server: No such file or directory
 Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

The file listed above does not seem to exist.

I checked if my Postgres is running or not with:

 /etc/init.d/postgresql status

and it was returning with SUCCESS message.

postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Thu 2017-11-16 10:03:41 UTC; 55min ago
  Process: 4701 ExecReload=/bin/true (code=exited, status=0/SUCCESS)
  Process: 4899 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 4899 (code=exited, status=0/SUCCESS)

Nov 16 10:03:41 median systemd[1]: Starting PostgreSQL RDBMS...
Nov 16 10:03:41 median systemd[1]: Started PostgreSQL RDBMS.

Still, I stopped and started postgres again.

I checked if there any other postgres task running or not with:

ps -ef | grep postgres

And it returned:

root      5210  5117  0 10:21 pts/0    00:00:00 grep --color=auto postgres

So there is no other Postgres.

I even checked if my Postgres accidentally got deleted or not with

dpkg -l | grep postgres

and it returned

ii  postgresql                           9.5+173ubuntu0.1                             all          object-relational SQL database (supported version)
ii  postgresql-9.5                       9.5.10-0ubuntu0.16.04                        amd64        object-relational SQL database, version 9.5 server
ii  postgresql-client-9.5                9.5.10-0ubuntu0.16.04                        amd64        front-end programs for PostgreSQL 9.5
ii  postgresql-client-common             173ubuntu0.1                                 all          manager for multiple PostgreSQL client versions
ii  postgresql-common                    173ubuntu0.1                                 all          PostgreSQL database-cluster manager
ii  postgresql-contrib-9.5               9.5.10-0ubuntu0.16.04                        amd64        additional facilities for PostgreSQL

So there is no rc instead of ii, which means it has not been uninstalled.

I have tried every other solution in the internet but uninstalling Postgres. Didn't work for me. I might be doing something very silly. I don't want to uninstall and lose my data.

Body:
Run the following command to check which port your PostgreSQL server is actually running on:

[root@server ~]# netstat -a | grep .s.PGSQL
unix  2      [ ACC ]     STREAM     LISTENING     2534417 /var/run/postgresql/.s.PGSQL.5432

I can see from this output that my server is listening on port 5432 and also that the file is created in /var/run/postgresql/.s.PGSQL.5432

You can then update /etc/init.d/postgresql to include the lines

PGPORT=5432
export PGPORT

and update your postgresql.conf file which is located in your data directory and set the port key/value to port=5432

and then restart your PostgreSQL server

[root@server] service postgresql restart


问:
sql server 2012 copy database failed between two instances on the same host
I am learning the sql server 2012 and got stuck when using the copy datase, trying to figure out why.

I created two instances on the same host, using administrator, windows authentication.
(the default instance:iZp0w14yqtvxcmZ, the second instance: iZp0w14yqtvxcmZ\instance2, try to copy database from the default one to the second one)

It failed at the last step: execute sql server agent job.
here is the error log from windows event viewer:

```<code>Message: Failed to connect to server iZp0w14yqtvxcmZ.
StackTrace:    at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.OpenConnection(Server& server, ServerProperty serverProp)
InnerException-->Login failed for user 'NT Service\SQLAgent$INSTANCE2'.
</code>```

Then I tried to add the login 'NT Service\SQLAgent$INSTANCE2' in the default instance. Then tried again and got another error:

```<code>Event Name: OnError
 Message: An error occurred while transferring data. See the inner exception for details.
StackTrace:    at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
   at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferExtraObjectsViaSmoTransfer()
InnerException-->Windows NT user or group 'iZp0wd5ebkvswaZ\Administrator' not found. Check the name again.
</code>```

But the Adminitrator does exist in the computer management -> local user and groups -> group, so I don't know what to do now. NEED HELP !!!

Thanks a lot!

答: after two-day's struggling, I figured it out. The sql server agent service should use a domain-based account for a multi-server environment. Also that account should be able to log in and perform the job.</p>

Body:
I am learning the sql server 2012 and got stuck when using the copy datase, trying to figure out why.

I created two instances on the same host, using administrator, windows authentication.
(the default instance:iZp0w14yqtvxcmZ, the second instance: iZp0w14yqtvxcmZ\instance2, try to copy database from the default one to the second one)

It failed at the last step: execute sql server agent job.
here is the error log from windows event viewer:

Message: Failed to connect to server iZp0w14yqtvxcmZ.
StackTrace:    at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.OpenConnection(Server& server, ServerProperty serverProp)
InnerException-->Login failed for user 'NT Service\SQLAgent$INSTANCE2'.

Then I tried to add the login 'NT Service\SQLAgent$INSTANCE2' in the default instance. Then tried again and got another error:

Event Name: OnError
 Message: An error occurred while transferring data. See the inner exception for details.
StackTrace:    at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
   at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferExtraObjectsViaSmoTransfer()
InnerException-->Windows NT user or group 'iZp0wd5ebkvswaZ\Administrator' not found. Check the name again.

But the Adminitrator does exist in the computer management -> local user and groups -> group, so I don't know what to do now. NEED HELP !!!

Thanks a lot!


问:
Get specific objects from an Array in react-native
I have a static array something like

[apple, banana, orange, lemon, goa, grapes, berry, mango, black grapes]

with no changes in order(order will be fixed). Based on user selection dynamically i am getting two objects like (orange, mango).

Now i need to fetch objects between these two objects i.e.(lemon,goa,grapes,berry) into a different array. Thank you

答:
First find index of both the values.

Then use array splice function to get the desired array.


问:
Is there a way to convert integer to char in CAPL?
I try to write a integer variable into a file by using the filePutString() function in CAPL. Is there a way to convert the integer into char, since filePutString() only uses chars as parameter.</p>

答:
I suppose the best way would be to use snprintf.</p>

```<code>char buffer[100];
int number = 10;
snprintf(buffer, elcount(buffer), "Text: %d", number);
</code>```

Body:
I suppose the best way would be to use snprintf.

char buffer[100];
int number = 10;
snprintf(buffer, elcount(buffer), "Text: %d", number);


问:
Text rotate within Uncode theme
I am trying to attempt this pen that I found on code pen. It allows text to look like it is being typed and deleted.

I have attempted to put this is in the site, the html and java is in and I put the css in as well, but it doesn't seem to work any ideas?

I am using a theme within Wordpress called Uncode. I am able to put in raw Java and html blocks, but not css, I can put the css into the theme options or the page.

This page is a work in progress but here is the link to what is on the page: http://preview.geomedia.co.uk/whitelight-venues/about-us/

答:
Add css and javascript into footer.php at the end of file
also, you need to call jquery-mini.js

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var TxtRotate = function(el, toRotate, period) {
  this.toRotate = toRotate;
  this.el = el;
  this.loopNum = 0;
  this.period = parseInt(period, 10) || 2000;
  this.txt = '';
  this.tick();
  this.isDeleting = false;
};

TxtRotate.prototype.tick = function() {
  var i = this.loopNum % this.toRotate.length;
  var fullTxt = this.toRotate[i];

  if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
  } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
  }

  this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

  var that = this;
  var delta = 300 - Math.random() * 100;

  if (this.isDeleting) { delta /= 2; }

  if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
  } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 500;
  }

  setTimeout(function() {
    that.tick();
  }, delta);
};

window.onload = function() {
  var elements = document.getElementsByClassName('txt-rotate');
  for (var i=0; i<elements.length; i++) {
    var toRotate = elements[i].getAttribute('data-rotate');
    var period = elements[i].getAttribute('data-period');
    if (toRotate) {
      new TxtRotate(elements[i], JSON.parse(toRotate), period);
    }
  }
  // INJECT CSS
  var css = document.createElement("style");
  css.type = "text/css";
  css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
  document.body.appendChild(css);
};
</script>
<style>

h1,h2 {
  font-weight: 200;
  margin: 0.4em 0;
}
h1 { font-size: 3.5em; }
h2 {
  color: #888;
  font-size: 2em;
}

</style>
</code>```

After that create a template for your about us page it should be different from other pages and will going to use only this page.

Now into this template code, you can paste the HTML where you would like to show the text.

At the end, the result will look like this screenshot:  https://prnt.sc/hb69cf

It is working for me on my localshot website.

Thanks

Title: Text rotate within Uncode theme

Body:
Add css and javascript into footer.php at the end of file
also, you need to call jquery-mini.js

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var TxtRotate = function(el, toRotate, period) {
  this.toRotate = toRotate;
  this.el = el;
  this.loopNum = 0;
  this.period = parseInt(period, 10) || 2000;
  this.txt = '';
  this.tick();
  this.isDeleting = false;
};

TxtRotate.prototype.tick = function() {
  var i = this.loopNum % this.toRotate.length;
  var fullTxt = this.toRotate[i];

  if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
  } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
  }

  this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

  var that = this;
  var delta = 300 - Math.random() * 100;

  if (this.isDeleting) { delta /= 2; }

  if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
  } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 500;
  }

  setTimeout(function() {
    that.tick();
  }, delta);
};

window.onload = function() {
  var elements = document.getElementsByClassName('txt-rotate');
  for (var i=0; i<elements.length; i++) {
    var toRotate = elements[i].getAttribute('data-rotate');
    var period = elements[i].getAttribute('data-period');
    if (toRotate) {
      new TxtRotate(elements[i], JSON.parse(toRotate), period);
    }
  }
  // INJECT CSS
  var css = document.createElement("style");
  css.type = "text/css";
  css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
  document.body.appendChild(css);
};
</script>
<style>

h1,h2 {
  font-weight: 200;
  margin: 0.4em 0;
}
h1 { font-size: 3.5em; }
h2 {
  color: #888;
  font-size: 2em;
}

</style>

After that create a template for your about us page it should be different from other pages and will going to use only this page.

Now into this template code, you can paste the HTML where you would like to show the text.

At the end, the result will look like this screenshot:  https://prnt.sc/hb69cf

It is working for me on my localshot website.

Thanks


问:
angular2-jwt: AuthHttp causes an error 'Expected 0 type arguments, but got 1.'
when I use AuthHttp from angular2-jwt in code below, I see error:

"Expected 0 type arguments, but got 1."

```<code>public getData(): Observable<User[]>{
const url = environment.apiUrl + "users";

return this.authHttp
  .get<User[]>(url)
  .map((res: User[]) => res);
  }
</code>```

If I use http: HttpClient, code works well.

What to change in this code to run it with AuthHttp?

答:
I found a solution:</p>

```<code>   public getData(): Observable<User[]>{
    const url = environment.apiUrl + `users`;

    return this.authHttp
      .get(url)
      .map((res: Response) => <User[]>res.json());
  }
</code>```

Body:
when I use AuthHttp from angular2-jwt in code below, I see error:

"Expected 0 type arguments, but got 1."

public getData(): Observable<User[]>{
const url = environment.apiUrl + "users";

return this.authHttp
  .get<User[]>(url)
  .map((res: User[]) => res);
  }

If I use http: HttpClient, code works well.

What to change in this code to run it with AuthHttp?

Body:
I found a solution:

   public getData(): Observable<User[]>{
    const url = environment.apiUrl + `users`;

    return this.authHttp
      .get(url)
      .map((res: Response) => <User[]>res.json());
  }


问:
Want a counter in aws Dynamodb
I have a table with column "Name" and "Vote", I want to increase the Vote count whenever I do update_item. I tried the below query but no luck.

```<code>       db.update_item(Key={ "Name":"Dany"},
                      UpdateExpression='ADD #oldVote :newVote',
                      ExpressionAttributeNames={ '#oldVote' :'Vote'},
                      ExpressionAttributeValues={':newVote': {"N": "1"}}
                      )
</code>```

Getting error as:

"An error occurred (ValidationException) when calling the UpdateItem
  operation: Invalid UpdateExpression: Incorrect operand type for
  operator or function; operator: ADD, operand type: MAP"

error

答:
You could try the following:

```<code>db.update_item(Key={ "Name":"Dany"},
                  UpdateExpression='SET Vote = Vote + :incr',
                  ExpressionAttributeValues={':incr': {"N": "1"}}
                  )
</code>```

Source: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters

Title: Want a counter in aws Dynamodb

Body:
I have a table with column "Name" and "Vote", I want to increase the Vote count whenever I do update_item. I tried the below query but no luck.

       db.update_item(Key={ "Name":"Dany"},
                      UpdateExpression='ADD #oldVote :newVote',
                      ExpressionAttributeNames={ '#oldVote' :'Vote'},
                      ExpressionAttributeValues={':newVote': {"N": "1"}}
                      )

Getting error as:

"An error occurred (ValidationException) when calling the UpdateItem
  operation: Invalid UpdateExpression: Incorrect operand type for
  operator or function; operator: ADD, operand type: MAP"

error

Body:
You could try the following:

db.update_item(Key={ "Name":"Dany"},
                  UpdateExpression='SET Vote = Vote + :incr',
                  ExpressionAttributeValues={':incr': {"N": "1"}}
                  )

Source: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters


问:
Adding flat html/css/js to drupal - not maintaining styling
I'm developing some JS animated components to add to a Drupal site. I typically work in JS and never Drupal, so the framework is where I'm having confusion. When I add the code into a WYSIWYG and preview, the components lose a lot of their styling - spacing, text color, font, etc. Is there anything Drupal specific that I need to ensure I do to make it so my components look the same when I view them locally vs on Drupal? </p>

<p>I've also heard about 'iframing'. Would this be an alternative that could fix this issue? </p>

答:
Drupal has so called "text formats" and default ones are "Filtered html", "Full html", "Plain text"...but you can also add custom ones.

When you edit some text with WYSIWYG editor just bellow that editor should be drop-down for selecting text format.

The thing is that each text format defines set of filters which will be applied when you save the content. So when you save content in i.e. "Filtered html" some html tags will be filtered out (removed / stripped) from your content and that can cause your code to fail.

Try using "Full html". Or even define your own text format (Configuration -> Contant authoring -> Text format in D7) and exclude all the filters that may destroy your code.

Alternative, if you don't need wysiwyg editor why don't you use plain text area instead?

Body:
I'm developing some JS animated components to add to a Drupal site. I typically work in JS and never Drupal, so the framework is where I'm having confusion. When I add the code into a WYSIWYG and preview, the components lose a lot of their styling - spacing, text color, font, etc. Is there anything Drupal specific that I need to ensure I do to make it so my components look the same when I view them locally vs on Drupal?

I've also heard about 'iframing'. Would this be an alternative that could fix this issue?


问:
jqgrid guriddo - how to get all data after processed
Is it possible to return all data from my jqgrid??

This work great but I only get clear data.

```<code>this.element.jqGrid('getRowData')
</code>```

For example I have column approved with settings:

```<code>   {
        editoptions: {value: "t:Yes;f:No;null:No"},
        value: "t:Yes;f:No;null:No",
        edittype: "select",
        formatter: "select",
        index: "approved",
        label: "Approved",
        name: "approved",
        resizable: false,
        search: false
    }
</code>```

When I use "getRowData" I get value for this column "f" but I need "No".

I looked into documentation and I didnt find method which gave me data after processed only clear data.

Is there a way to do this?

答:
If your data comes from the server only and you want to get the text from select you will need to define your own custom unformat function. like this:

```<code>{
        editoptions: {value: "t:Yes;f:No;null:No"},
        value: "t:Yes;f:No;null:No",
        edittype: "select",
        formatter: "select",
        unformat : function( cellval, options, cell) {
            return cellval;
        },
        index: "approved",
        label: "Approved",
        name: "approved",
        resizable: false,
        search: false
    }
</code>```

and use the getRowData as of your code

in case of loadonce true or local datatype parameter you will nedd to query the data parameter

```<code>$("#jqGrid").jqGrid('getGridParam', data);
</code>```

or to use the second parameter in getRowData to return tha data array

```<code>this.element.jqGrid('getRowData', true);
</code>```

Body:
Is it possible to return all data from my jqgrid??

This work great but I only get clear data.

this.element.jqGrid('getRowData')

For example I have column approved with settings:

   {
        editoptions: {value: "t:Yes;f:No;null:No"},
        value: "t:Yes;f:No;null:No",
        edittype: "select",
        formatter: "select",
        index: "approved",
        label: "Approved",
        name: "approved",
        resizable: false,
        search: false
    }

When I use "getRowData" I get value for this column "f" but I need "No".

I looked into documentation and I didnt find method which gave me data after processed only clear data.

Is there a way to do this?

Body:
If your data comes from the server only and you want to get the text from select you will need to define your own custom unformat function. like this:

{
        editoptions: {value: "t:Yes;f:No;null:No"},
        value: "t:Yes;f:No;null:No",
        edittype: "select",
        formatter: "select",
        unformat : function( cellval, options, cell) {
            return cellval;
        },
        index: "approved",
        label: "Approved",
        name: "approved",
        resizable: false,
        search: false
    }

and use the getRowData as of your code

in case of loadonce true or local datatype parameter you will nedd to query the data parameter

$("#jqGrid").jqGrid('getGridParam', data);

or to use the second parameter in getRowData to return tha data array

this.element.jqGrid('getRowData', true);


问:
Should I be worried that my site crashes IE9 and how to fix?
I've downloaded the latest version of IE9 beta and my site wrecks it.  No problems on any other browser, but on IE9 it freezes on every page.  The thing is, many other sites also make it gag.

Should I worry?

IE's fault or do my site and I need to do some serious soul searching?

How does one debug this stuff and are there a list of common culprits?  Is it most likely a Javascript issue?  jQuery?

答:
Jonathan submitted a great answer about using jslint to verify the integrity of the JavaScript, and using other debug tools on other browsers to detect for a non-crash error.  I did both and thoroughly went through my site, only to find that IE9 was still crashing!

So I looked into it and here's what I found: the main cause of IE9 beta crashes are add-ons that are incompatible with the new release.  Adobe PDF viewers, printer add-ons, toolbars, etc.  Most everyone has at least one add-on in their browsers.  So I disabled all my add-ons and now my site works.

I'm not sure why my site seemed to crash more than others with IE9, but if people are having problems with there site, I'd suggest (1) disabling all add-ons just in case, and then (2) using Jonathan's answer (which I'll leave checked as the official answer since it has to do more with programming).

ContentLicense: CC BY-SA 2.5


问:
PHP line break inside of cell remove qoute
This is my PHP

```<code>$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}
</code>```

The result is

```<code>//this is inside of cell
sample
"sample
"sample
</code>```

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

答:
Well there you go :

```<code>$data = ['sample','sample','sample'];
$val = "";
foreach($data as $v){
  $val .= $v . "\n" ;
}
</code>```

Then you simply use fputcsv() like this :

```<code>$fp = fopen('file.csv', 'w');
fputcsv($fp, [$val]);
</code>```

And you get the result you want :

Body:
This is my PHP

$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}

The result is

//this is inside of cell
sample
"sample
"sample

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

Body:
Well there you go :

$data = ['sample','sample','sample'];
$val = "";
foreach($data as $v){
  $val .= $v . "\n" ;
}

Then you simply use fputcsv() like this :

$fp = fopen('file.csv', 'w');
fputcsv($fp, [$val]);

And you get the result you want :


问:
Tensorflow: extracting predictions from "Layer Module"
I am following the Tensorflow's "Layer Module" from this tutorial link https://www.tensorflow.org/tutorials/layers. You might be able to help me how can I get the results of the predictions and its respective probabilities.
I need to see it for further understanding the model. And if there is a way I can save the results - predictions and probabilities to csv.

Thank you so much for your time.

答:
I have actually found a way on this and it is very simple as I thought. I was thinking some might have similar question so here it is. Tensorflow is kind a new framework to work on machine learning models but I eventually realize that this is quite easy.

Tensorflow has this *.predict(...) function on the model you created with tf and it returns the predictions variable you define on your model which contains "classes" and "probabilities"

On your model for an example:

```<code>some_classifier = tf.estimator.Estimator(model_fn=model_fn,
    model_dir=...)
</code>```

you can do this for prediction (as we know it)

```<code>prediction_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": test_feats}, #given you have this variable containing the test data
    y=test_labels, #and the equivalent label for the test data
    num_epochs=1,
    shuffle=False)
prediction_results = some_classifier.predict(input_fn=prediction_input_fn)
</code>```

and then the variable prediction_results contains the values for predicted class and its probabilities which you can then save (e.g using Panda)

```<code>save = panda.DataFrame(list(prediction_results))
save.to_csv("file.csv")
</code>```

The above code snip works well given you already written a code within your model a container for predictions such as below:

```<code>predictions = {
  "classes": tf.argmax(input=logits, axis=1),
  "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
</code>```

}

Body:
I have actually found a way on this and it is very simple as I thought. I was thinking some might have similar question so here it is. Tensorflow is kind a new framework to work on machine learning models but I eventually realize that this is quite easy.

Tensorflow has this *.predict(...) function on the model you created with tf and it returns the predictions variable you define on your model which contains "classes" and "probabilities"

On your model for an example:

some_classifier = tf.estimator.Estimator(model_fn=model_fn,
    model_dir=...)

you can do this for prediction (as we know it)

prediction_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": test_feats}, #given you have this variable containing the test data
    y=test_labels, #and the equivalent label for the test data
    num_epochs=1,
    shuffle=False)
prediction_results = some_classifier.predict(input_fn=prediction_input_fn)

and then the variable prediction_results contains the values for predicted class and its probabilities which you can then save (e.g using Panda)

save = panda.DataFrame(list(prediction_results))
save.to_csv("file.csv")

The above code snip works well given you already written a code within your model a container for predictions such as below:

predictions = {
  "classes": tf.argmax(input=logits, axis=1),
  "probabilities": tf.nn.softmax(logits, name="softmax_tensor")

}


问:
how to set column name in DataTable
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

```<code>connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();
</code>```

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

答:
Hey you can do the following, it will disable taking the header from the excel workbook:

```<code>    conn = New System.Data.OleDb.OleDbConnection(
          "provider=Microsoft.ACE.OLEDB.12.0; " &
          "data source=" & path & "; " &
          "Extended Properties=""Excel 12.0;HDR=No;IMEX=1""")
</code>```

Alter the HDR to No in the connection string

Title: how to set column name in DataTable

Body:
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

Body:
Hey you can do the following, it will disable taking the header from the excel workbook:

    conn = New System.Data.OleDb.OleDbConnection(
          "provider=Microsoft.ACE.OLEDB.12.0; " &
          "data source=" & path & "; " &
          "Extended Properties=""Excel 12.0;HDR=No;IMEX=1""")

Alter the HDR to No in the connection string


问:
Removing a NSData stored in CoreData
I saved a NSData (of UIImage) in an attribute of CoreData.
There are still some other attributes under the same entity.
How can I remove just the NSData stored, but not removing the whole NSManagedObject?
I tried overwriting it to nil, but the size of DB did not change at all, which means the NSData is not removed?</p>

答:
It means the amount of space used to store some value for that attribute is still there, but it does not mean that you did not successfully obliterate the value. Did you use [managedObjectContext save:&error] after writing to the value? If so and it reported no error then the value is gone.

(Does the size of the store really increase when you set an attribute? I expect it would when you add an entity but not just for setting an attribute.)

Title: Removing a NSData stored in CoreData


问:
Using a REST web service how do you make a method that returns text passed to it?
I am currently using Eclipse and Tomcat for my servers and I am trying to make a method that passes an input string as output onto the HTML website.

I got some help from the question below, but how would I go about implementing the code from that link into a servlet file?

How to create a Restful web service with input parameters?

If anyone has any other solutions to taking text, passing it to the method and outputting it I'd appreciate it.

The code I'm using is a demo for Hello World (scroll to the very bottom):

https://www.ibm.com/developerworks/library/os-eclipse-tomcat/index.html

答:
suppose this is your html form

```<code><form action="login" method="get">
        <table>
            <tr>
                <td>User</td>
                <td><input name="user" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input name="password" /></td>
            </tr>
        </table>
        <input type="submit" />
    </form>
</code>```

Then to get the parameters of this form in your method you should use the getParameter method of HttpServletRequest object.

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response,String inputString)
          throws ServletException, IOException {
          String userName = request.getParameter("user");
          String password = request.getParameter("password");
          response.getWriter().write("Name = " +userName+ " And Password = " +password);
            }
</code>```

Body:
suppose this is your html form

<form action="login" method="get">
        <table>
            <tr>
                <td>User</td>
                <td><input name="user" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input name="password" /></td>
            </tr>
        </table>
        <input type="submit" />
    </form>

Then to get the parameters of this form in your method you should use the getParameter method of HttpServletRequest object.

protected void doGet(HttpServletRequest request, HttpServletResponse response,String inputString)
          throws ServletException, IOException {
          String userName = request.getParameter("user");
          String password = request.getParameter("password");
          response.getWriter().write("Name = " +userName+ " And Password = " +password);
            }


问:
child_process quitting when it shouldn't
I have a node app, using child_process to wget a very large file. Despite setting the relevant options (or so I thought, it just seems to terminate with reason 'null' immediately. If I run the command manually it's fine. (The .js / event thread continues to run, so it's not that. '...' is redacted URL)</p>

```<code>const spawn = require('child_process').spawn;
var options = {stdio: 'ignore', detatched: true};

var ls = spawn('wget', ['http://...', '-O', './file.sav'], options);
console.log("PID is ", ls.pid);
ls.unref();
</code>```

答:
Figured it out in the end. I was running pm2 (process manager) in watch mode. This was restarting the Node app each time wget started writing to the disk!

It's interesting that this was happening at the start of the write to the disk, rather than waiting for wget to finish writing the file. Also that it was so quick that even though the code unrefs the process, this wasn't happening in time to save the process from ending with the Node app.

Got round the problem by excluding the directories that are being written to in the config of pm2.

Body:
I have a node app, using child_process to wget a very large file. Despite setting the relevant options (or so I thought, it just seems to terminate with reason 'null' immediately. If I run the command manually it's fine. (The .js / event thread continues to run, so it's not that. '...' is redacted URL)

const spawn = require('child_process').spawn;
var options = {stdio: 'ignore', detatched: true};

var ls = spawn('wget', ['http://...', '-O', './file.sav'], options);
console.log("PID is ", ls.pid);
ls.unref();


问:
UINavigationBar.apperance().titleTextAttributes not working in swift
UINavigationBar.apperance().titleTextAttributes not working. Swift Code is below.

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().barTintColor = UIColor.greenColor()
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]

    return true
}
</code>```

Any idea?

答:
Add below code in Appdelegate didFinishLaunchingWithOptions method</p>

```<code> let navFont = UIFont(name: "HelveticaNeue-Bold", size: 30.0)
 UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.blackColor(), NSAttributedStringKey.font: navFont!]
</code>```

Body:
UINavigationBar.apperance().titleTextAttributes not working. Swift Code is below.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().barTintColor = UIColor.greenColor()
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]

    return true
}

Any idea?

Body:
Add below code in Appdelegate didFinishLaunchingWithOptions method

 let navFont = UIFont(name: "HelveticaNeue-Bold", size: 30.0)
 UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.blackColor(), NSAttributedStringKey.font: navFont!]


问:
axios does not send POST to golang api
I have a golang api backend with a negroni middleware.

I already implemented the CORS handler for negroni, so my api should allow cross origin resource sharing.

```<code>// allow OPTIONS method of CORS requests
c := cors.New(cors.Options{
    AllowedOrigins: []string{"http://127.0.0.1"},
})

//common.StartUp() - Replaced with init method
// Get the mux router object
router := routers.InitRoutes()
// Create a negroni instance
n := negroni.Classic()
n.Use(c)
n.UseHandler(router)

server := &http.Server{
    Addr:    common.AppConfig.Server,
    Handler: n,
}
log.Println("Listening...")
server.ListenAndServe()
</code>```

This is from the https://github.com/rs/cors/blob/master/examples/negroni/server.go example of implementing CORS with negroni.

Nevertheless my api now responses a 200 status back to my frontend, but the frontend does not send the POST request to the server. This my axios code:

```<code>import axios from 'axios';
const data = {
email: 'user@mail.com',
password: 'secret',
};

export default {
name: 'Login',
methods: {
login() {
  axios.post('https://127.0.0.1:8090/users/login', data);
},
</code>```

Postman does not have any problems with sending the POST request. What am I doing wrong?

答:
Okay I found a solution for the problem:

As described in this article, I added some more options to the cors negroni plugin. One important option that was missing in my application was the line

```<code>AllowedHeaders: []string{"X-Auth-Key", "X-Auth-Secret", "Content-Type"},
</code>```

Because my app sent the Content-Type Header and the api refused it.

I hope this will help others with similar problems.

Title: axios does not send POST to golang api

Body:
I have a golang api backend with a negroni middleware.

I already implemented the CORS handler for negroni, so my api should allow cross origin resource sharing.

// allow OPTIONS method of CORS requests
c := cors.New(cors.Options{
    AllowedOrigins: []string{"http://127.0.0.1"},
})

//common.StartUp() - Replaced with init method
// Get the mux router object
router := routers.InitRoutes()
// Create a negroni instance
n := negroni.Classic()
n.Use(c)
n.UseHandler(router)

server := &http.Server{
    Addr:    common.AppConfig.Server,
    Handler: n,
}
log.Println("Listening...")
server.ListenAndServe()

This is from the https://github.com/rs/cors/blob/master/examples/negroni/server.go example of implementing CORS with negroni.

Nevertheless my api now responses a 200 status back to my frontend, but the frontend does not send the POST request to the server. This my axios code:

import axios from 'axios';
const data = {
email: 'user@mail.com',
password: 'secret',
};

export default {
name: 'Login',
methods: {
login() {
  axios.post('https://127.0.0.1:8090/users/login', data);
},

Postman does not have any problems with sending the POST request. What am I doing wrong?

Body:
Okay I found a solution for the problem:

As described in this article, I added some more options to the cors negroni plugin. One important option that was missing in my application was the line

AllowedHeaders: []string{"X-Auth-Key", "X-Auth-Secret", "Content-Type"},

Because my app sent the Content-Type Header and the api refused it.

I hope this will help others with similar problems.


问:
CSS table layout: why does table-row not accept a margin?

.container {
  width: 850px;
  padding: 0;
  display: table;
  margin-left: auto;
  margin-right: auto;
}
.row {
  display: table-row;
  margin-bottom: 30px;
  /* HERE */
}
.home_1 {
  width: 64px;
  height: 64px;
  padding-right: 20px;
  margin-right: 10px;
  display: table-cell;
}
.home_2 {
  width: 350px;
  height: 64px;
  padding: 0px;
  vertical-align: middle;
  font-size: 150%;
  display: table-cell;
}
.home_3 {
  width: 64px;
  height: 64px;
  padding-right: 20px;
  margin-right: 10px;
  display: table-cell;
}
.home_4 {
  width: 350px;
  height: 64px;
  padding: 0px;
  vertical-align: middle;
  font-size: 150%;
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="home_1"></div>
    <div class="home_2"></div>
    <div class="home_3"></div>
    <div class="home_4"></div>
  </div>

  <div class="row">
    <div class="home_1"></div>
    <div class="home_2"></div>
  </div>
</div></code>```

My question is relative to the line marked HERE in the CSS. I found out that the rows are too near to each other, so I tried to add a bottom margin to separate them. Unfortunately it does not work. I have to add the margins to the table cells to separate the rows.

What is the reason behind this behavior?

Also, is it ok to use this strategy to perform layouting as I am doing:

```<code>[icon] - text      [icon] - text
[icon] - text      [icon] - text
</code>```

or is there a better strategy?

答: adding a br tag between the divs worked. add br tag between two divs that are display:table-row in a parent with display:table</p>

Body:
.container {
  width: 850px;
  padding: 0;
  display: table;
  margin-left: auto;
  margin-right: auto;
}
.row {
  display: table-row;
  margin-bottom: 30px;
  /* HERE */
}
.home_1 {
  width: 64px;
  height: 64px;
  padding-right: 20px;
  margin-right: 10px;
  display: table-cell;
}
.home_2 {
  width: 350px;
  height: 64px;
  padding: 0px;
  vertical-align: middle;
  font-size: 150%;
  display: table-cell;
}
.home_3 {
  width: 64px;
  height: 64px;
  padding-right: 20px;
  margin-right: 10px;
  display: table-cell;
}
.home_4 {
  width: 350px;
  height: 64px;
  padding: 0px;
  vertical-align: middle;
  font-size: 150%;
  display: table-cell;
}

My question is relative to the line marked HERE in the CSS. I found out that the rows are too near to each other, so I tried to add a bottom margin to separate them. Unfortunately it does not work. I have to add the margins to the table cells to separate the rows.

What is the reason behind this behavior?

Also, is it ok to use this strategy to perform layouting as I am doing:

[icon] - text      [icon] - text
[icon] - text      [icon] - text

or is there a better strategy?


问:
what does this bash script line of code mean
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

```<code>Path=`echo $line | awk -F '|' '{print $1}'`
</code>```

答:
echo $line will print the value of the variable $line, the | symbol means that the output of this will be passed (or piped) to another program/command/script. I will not attempt to explain awk here, but what is done above is that the output from the echo $line is taken and processed with it.

the option -FS as per awk man page means

-F fs Use fs for the input field separator

so the string after it will be used to split the input string given to awk into different fields. Example, you variable $line has a value of a|b it will be split into two fields a and b. What is to be done with this is specified within the '{}' expression.
Again, what can be done in there is next to infinite, here the only thing that is done is to print the first field which can be accessed with $1, or a in the above example ($2 would be b as can be guessed).

Finally, the output of this whole operation is then stored in the variable Path.

to summarize:

```<code>line="a|b"
echo $line | awk -F '|' '{print $1}'
> a
Path=`echo $line | awk -F '|' '{print $1}'`
echo $Path
> a
</code>```

Body:
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

Path=`echo $line | awk -F '|' '{print $1}'`

Body:
echo $line will print the value of the variable $line, the | symbol means that the output of this will be passed (or piped) to another program/command/script. I will not attempt to explain awk here, but what is done above is that the output from the echo $line is taken and processed with it.

the option -FS as per awk man page means

-F fs Use fs for the input field separator

so the string after it will be used to split the input string given to awk into different fields. Example, you variable $line has a value of a|b it will be split into two fields a and b. What is to be done with this is specified within the '{}' expression.
Again, what can be done in there is next to infinite, here the only thing that is done is to print the first field which can be accessed with $1, or a in the above example ($2 would be b as can be guessed).

Finally, the output of this whole operation is then stored in the variable Path.

to summarize:

line="a|b"
echo $line | awk -F '|' '{print $1}'
> a
Path=`echo $line | awk -F '|' '{print $1}'`
echo $Path
> a


问:
Unable to find the element error in selenium with java
As per the requirement,

A dynamic web table needs to be filled from Excel sheet using selenium.

The web table is dynamic. And for each row in the excel sheet a new row has to be added in the web table

ID of a web element looks like this: asr_100_ct100_ikview_ct155_view

The next element's I'd looks like

asr_100_ct100_ikview_ct156_view

So, here I have done string concatenation like

```<code>Int j=155;

Driver.find element (by.id("asr_100_ct100_ikview_ct" +j+ "_view";

J++.
</code>```

The above code is in for loop.

For each row in the excel sheet, a new webelement has to be found and data should be sent.

Error: unable to find the element with Id
  ==asr_100_ct100_ikview_ct155_view

答:
try xpath instead of id!

```<code>WebDriver driver= new ChromeDriver();
driver.findElement(By.xpath("\\*[starts-with(@id,'asr_100')]
FileInputStream fis= new FileInputStream("path");
XSSFWorkbook b= new XSSFWorkbook(fis); //make sure that it is .xlsx file
XSSFSheet sheet= b.getSheet("sheet name");
WebElement elem= driver.findElement(By.id("id of the whole table"));
List<WebElement> list= elem.findElements(By.xpath(//*[starts-with(@id,'tr id'));

int rows= sheet.getLastRowNum();
for(int i=0; i<rows;i++) {
    Row row= sheet.getRow(i);
    for(int j=0;j<row.getLastCellNum();j++) {
        for(WebElement e: list)
                List<WebElement> tr= e.findElements(By.xpath(//*[starts-
                                   with(@id,'td id'))
                    for(WebElement d: tr)
                     d.sendKeys("data");
    }
}
</code>```

if the element is a table, you have many rows and columns, you need to get data from every cell!
first of all, you need to get that file from which you are reading!

//i'm sorry if I'm wrong
//please correct me if i'm wrong, i'm beginner in coding!

Body:
As per the requirement,

A dynamic web table needs to be filled from Excel sheet using selenium.

The web table is dynamic. And for each row in the excel sheet a new row has to be added in the web table

ID of a web element looks like this: asr_100_ct100_ikview_ct155_view

The next element's I'd looks like

asr_100_ct100_ikview_ct156_view

So, here I have done string concatenation like

Int j=155;

Driver.find element (by.id("asr_100_ct100_ikview_ct" +j+ "_view";

J++.

The above code is in for loop.

For each row in the excel sheet, a new webelement has to be found and data should be sent.

Error: unable to find the element with Id
  ==asr_100_ct100_ikview_ct155_view

Body:
try xpath instead of id!

WebDriver driver= new ChromeDriver();
driver.findElement(By.xpath("\\*[starts-with(@id,'asr_100')]
FileInputStream fis= new FileInputStream("path");
XSSFWorkbook b= new XSSFWorkbook(fis); //make sure that it is .xlsx file
XSSFSheet sheet= b.getSheet("sheet name");
WebElement elem= driver.findElement(By.id("id of the whole table"));
List<WebElement> list= elem.findElements(By.xpath(//*[starts-with(@id,'tr id'));

int rows= sheet.getLastRowNum();
for(int i=0; i<rows;i++) {
    Row row= sheet.getRow(i);
    for(int j=0;j<row.getLastCellNum();j++) {
        for(WebElement e: list)
                List<WebElement> tr= e.findElements(By.xpath(//*[starts-
                                   with(@id,'td id'))
                    for(WebElement d: tr)
                     d.sendKeys("data");
    }
}

if the element is a table, you have many rows and columns, you need to get data from every cell!
first of all, you need to get that file from which you are reading!

//i'm sorry if I'm wrong
//please correct me if i'm wrong, i'm beginner in coding!


问:
What's in gradle a group, module and artifact?
The gradle docs don't take the time to explain the entities they are dealing with. That's why I want to ask such a basic question.

I've got a to understand in detail, what the terms group, module and artifact really mean to alter this code:

```<code>compile('com.thoughtworks.xstream:xstream:1.4.7') {
    exclude group: 'xmlpull', module: 'xmlpull'
}
</code>```

About a year ago I used that exclude statement I took from Android dalvik conversion for xmlpullparser to fix a Multiple dex files failure.

However, after upgrading to Android Studio 3.0 that error occurrs again! Now it says: Multiple dex files define Lorg/xmlpull/mxp1/MXParser and sometimes ...XmlPullParserException.java So, id like to understand how the parameters I give exclude must be shaped.

Reading the documentation one could think a group is the package name and the artifact is the class:

```<code>//excluding a particular transitive dependency:
exclude module: 'cglib' //by artifact name
exclude group: 'org.jmock' //by group
exclude group: 'org.unwanted', module: 'iAmBuggy' //by both name and group
</code>```

Another chinese page (translated) used those excludes

```<code> compile ( 'com.thoughtworks.xstream: xstream: 1.4.7' ) {
       exclude group : 'xmlpull'
       exclude group : 'XmlPullParser'
 }
</code>```

Built on that findings wonder

how xmlpull worked when the package name begins with org.xmlpull?

what projects those terms refer to in my scenario. Where was the group name defined?

What kinda group is XmlPullParser?

Must I clean, rebuild or just build the project after altering those parameters? Because sometimes it complains about different files.

答:
The group, artifact and version are chosen semi randomly and do NOT need to match packages or classes in the jar file.

For example commons-lang has groupId = 'commons-lang' but the classes are in org.apache.commons.lang.* package

The group, artifact and version are defined within the build file of the project. In maven this will be in pom.xml in gradle this will be in build.gradle (and settings.gradle)

If you want to know the group, artifact, version for a project (aka GAV, aka maven co-ordinates) you will usually go to the project's home page.

You can also use the maven central advanced search to "fuzzy" search eg by artifactId or by a classname within a jar. If you are using an in-house repository you can likely "fuzzy" search via the web interface there also

Body:
The gradle docs don't take the time to explain the entities they are dealing with. That's why I want to ask such a basic question.

I've got a to understand in detail, what the terms group, module and artifact really mean to alter this code:

compile('com.thoughtworks.xstream:xstream:1.4.7') {
    exclude group: 'xmlpull', module: 'xmlpull'
}

About a year ago I used that exclude statement I took from Android dalvik conversion for xmlpullparser to fix a Multiple dex files failure.

However, after upgrading to Android Studio 3.0 that error occurrs again! Now it says: Multiple dex files define Lorg/xmlpull/mxp1/MXParser and sometimes ...XmlPullParserException.java So, id like to understand how the parameters I give exclude must be shaped.

Reading the documentation one could think a group is the package name and the artifact is the class:

//excluding a particular transitive dependency:
exclude module: 'cglib' //by artifact name
exclude group: 'org.jmock' //by group
exclude group: 'org.unwanted', module: 'iAmBuggy' //by both name and group

Another chinese page (translated) used those excludes

 compile ( 'com.thoughtworks.xstream: xstream: 1.4.7' ) {
       exclude group : 'xmlpull'
       exclude group : 'XmlPullParser'
 }

Built on that findings wonder

how xmlpull worked when the package name begins with org.xmlpull?

what projects those terms refer to in my scenario. Where was the group name defined?

What kinda group is XmlPullParser?

Must I clean, rebuild or just build the project after altering those parameters? Because sometimes it complains about different files.


问:
Javascript local variable technique
I have a simple question related to one-line programming. First an example:

```<code>function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}
</code>```

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

```<code>function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
</code>```

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

```<code>function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}
</code>```

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

答:
~~shudder~~

This reminds me of awk where there is no way to have local variables in a function unless you declare extra variables in the arguments list.

If you need to have a local variable, just do it.

Title: Javascript local variable technique

Body:
I have a simple question related to one-line programming. First an example:

function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

OwnerDisplayName: Jason S


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答:
Because Java will create a StringBuilder to append s1, or "abc", to s2, or null.

According to the spec for StringBuilder.append(String)--

```<code>If str is null, then the four characters "null" are appended
</code>```

So it turns into the same as "abc" + "null"

Let's take your code example (I placed it inside a method):

```<code> public static void main(String[] args)
 {
  String s1 = "abc";
  String s2 = null;
  String s3 = s1+ s2;
  System.out.println(s3);
 }
</code>```

If we take a gander at the bytecode (gotten by invoking javap -c):

```<code>public static void main(java.lang.String[]);
  Code:
   0:   ldc #2; //String abc
   2:   astore_1
   3:   aconst_null
   4:   astore_2
   5:   new #3; //class java/lang/StringBuilder
   8:   dup
   9:   invokespecial   #4; //Method java/lang/StringBuilder."<init>":()V
   12:  aload_1
   13:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   16:  aload_2
   17:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   20:  invokevirtual   #6; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   23:  astore_3
   24:  getstatic   #7; //Field java/lang/System.out:Ljava/io/PrintStream;
   27:  aload_3
   28:  invokevirtual   #8; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   31:  return
</code>```

Java creates a StringBuilder and appends the values, as Strings, of s1 and s2.

So you have to be careful then, if you were expecting a NullPointerException, because concatenation in Java will skirt the issue.

Side Note: As pointed out by Jon Skeet, this is ultimately just implementation details -- it's the Java spec that guarantees that null, when converted to a String, turns into "null". However, this bytecode at least shows what is actually happening behind the scenes.

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull

Body:
Because Java will create a StringBuilder to append s1, or "abc", to s2, or null.

According to the spec for StringBuilder.append(String)--

If str is null, then the four characters "null" are appended

So it turns into the same as "abc" + "null"

Let's take your code example (I placed it inside a method):

 public static void main(String[] args)
 {
  String s1 = "abc";
  String s2 = null;
  String s3 = s1+ s2;
  System.out.println(s3);
 }

If we take a gander at the bytecode (gotten by invoking javap -c):

public static void main(java.lang.String[]);
  Code:
   0:   ldc #2; //String abc
   2:   astore_1
   3:   aconst_null
   4:   astore_2
   5:   new #3; //class java/lang/StringBuilder
   8:   dup
   9:   invokespecial   #4; //Method java/lang/StringBuilder."<init>":()V
   12:  aload_1
   13:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   16:  aload_2
   17:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   20:  invokevirtual   #6; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   23:  astore_3
   24:  getstatic   #7; //Field java/lang/System.out:Ljava/io/PrintStream;
   27:  aload_3
   28:  invokevirtual   #8; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   31:  return

Java creates a StringBuilder and appends the values, as Strings, of s1 and s2.

So you have to be careful then, if you were expecting a NullPointerException, because concatenation in Java will skirt the issue.

Side Note: As pointed out by Jon Skeet, this is ultimately just implementation details -- it's the Java spec that guarantees that null, when converted to a String, turns into "null". However, this bytecode at least shows what is actually happening behind the scenes.


问:
Selecting the top three columns for each row and saving the results along with index in a dictionary in python
I am using the below code to iterate through rows of a dataframe

Here is the sample dataset :

```<code>device_id   s2  s41 s47 s14 s24 s36 s4  s23 s10
3           0   0   0   0.002507676 0   0   0   0   0
5           0   0   0   0   0   0   0   0   0
23          0   0   0   0   0   0   0   0   0
42          0   0   0   0   0   0   0   0   0
61          0   0   0   0   0   0   0   0   0
49          0   0   0   0   0   0   0   0   7.564063476
54          0   0   0   0   0   0   0   0.001098988 0
</code>```

and sort the top 3 values from each row.

```<code>for index, row in df.iterrows():

    row_sorted = row.sort_values(ascending=False)
    print (index,row_sorted)
</code>```

here is a sample output

```<code>123 s16    1.054018
    s17    0.000000
    s26    0.000000
</code>```

I have also tried with the below code:

```<code>top_n = 3
    pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist()
                  for n, col in enumerate(df.T)}).T
</code>```

to do it all at once but here is the output :

49  s16   s1  s37 -- 49 is the row number here.

As you can see the outputs do not match and the first output is the correct one.

What I am looking for is a final dictionary which contains the index as key and the top 3 columns as values:

```<code>{123 : 's16','s17','s26'}
</code>```

These will be used further down the line to iterate through another dictionary to_map which has the following structure:
ID": ["s26", "International", "E", "B_TV"] from where I will select "E" and "B_TV"

答:
Try this vectorized approach:

Sample DF:

```<code>In [80]: df = pd.DataFrame(np.random.randint(10, size=(5,7)), columns=['id']+list('abcdef'))
    ...: df = df.set_index('id')
    ...:

In [81]: df
Out[81]:
    a  b  c  d  e  f
id
4   4  0  8  8  4  8
0   2  4  7  3  1  4
9   3  6  5  7  3  4
5   7  6  3  8  9  1
6   3  7  6  1  7  9
</code>```

Solution:

```<code>In [82]: idx = np.argsort(df.values, axis=1)[:, ::-1][:, :3]

In [83]: pd.DataFrame(np.take(df.columns, idx), index=df.index).T.to_dict('l')
Out[83]:
{0: ['c', 'f', 'b'],
 4: ['f', 'd', 'c'],
 5: ['e', 'd', 'a'],
 6: ['f', 'e', 'b'],
 9: ['d', 'b', 'c']}
</code>```

PS replace [:, :3] with [:, :top_n]

Body:
I am using the below code to iterate through rows of a dataframe

Here is the sample dataset :

device_id   s2  s41 s47 s14 s24 s36 s4  s23 s10
3           0   0   0   0.002507676 0   0   0   0   0
5           0   0   0   0   0   0   0   0   0
23          0   0   0   0   0   0   0   0   0
42          0   0   0   0   0   0   0   0   0
61          0   0   0   0   0   0   0   0   0
49          0   0   0   0   0   0   0   0   7.564063476
54          0   0   0   0   0   0   0   0.001098988 0

and sort the top 3 values from each row.

for index, row in df.iterrows():

    row_sorted = row.sort_values(ascending=False)
    print (index,row_sorted)

here is a sample output

123 s16    1.054018
    s17    0.000000
    s26    0.000000

I have also tried with the below code:

top_n = 3
    pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist()
                  for n, col in enumerate(df.T)}).T

to do it all at once but here is the output :

49  s16   s1  s37 -- 49 is the row number here.

As you can see the outputs do not match and the first output is the correct one.

What I am looking for is a final dictionary which contains the index as key and the top 3 columns as values:

{123 : 's16','s17','s26'}

These will be used further down the line to iterate through another dictionary to_map which has the following structure:
ID": ["s26", "International", "E", "B_TV"] from where I will select "E" and "B_TV"

Body:
Try this vectorized approach:

Sample DF:

In [80]: df = pd.DataFrame(np.random.randint(10, size=(5,7)), columns=['id']+list('abcdef'))
    ...: df = df.set_index('id')
    ...:

In [81]: df
Out[81]:
    a  b  c  d  e  f
id
4   4  0  8  8  4  8
0   2  4  7  3  1  4
9   3  6  5  7  3  4
5   7  6  3  8  9  1
6   3  7  6  1  7  9

Solution:

In [82]: idx = np.argsort(df.values, axis=1)[:, ::-1][:, :3]

In [83]: pd.DataFrame(np.take(df.columns, idx), index=df.index).T.to_dict('l')
Out[83]:
{0: ['c', 'f', 'b'],
 4: ['f', 'd', 'c'],
 5: ['e', 'd', 'a'],
 6: ['f', 'e', 'b'],
 9: ['d', 'b', 'c']}

PS replace [:, :3] with [:, :top_n]


问:
Rails 5 ActionView::Helpers capture method
I'm new in ruby on rails, and I want to practice it.
I'm stuck when I want to include a view into antoher view.
I want by doing that to have my posts into another view than of posts/index

posts/index

method:

```<code>def index
    @Posts = Post.all
end
</code>```

view:

```<code><% @posts = capture do %>

   <% @posts.each do |post| %>
     <h3>
      <%= post.title %>
     </h3>
    <p>
     <%= post.content %>
    </p>
  <% end %>

<% end %>
</code>```

pages/index

```<code><h1> Index Of another pages </h1>
<%= @posts %>
</code>```

答:
It sounds to me like you need to save the reusable view code as a partial, and render it all places it's required.

To use a partial, save it down with an underscore prefix, i.e. _posts.html.erb.

This can then be rendered using:

```<code><%= render 'path/to/posts' %>
</code>```

You'll likely need to pass in the posts variable to the partial, as in the following:

```<code><%= render 'path/to/posts', posts: @posts %>
</code>```

And the change your view to use posts rather than @posts.

Update:

The result of capture is assigned to @posts, although this variable still wouldn't be available in another template - rather to be used again on the same page

Based on what you're saying about the project's structure, it sounds like you'd need the following:

in app/views/posts/_posts.html.web

```<code><% @posts.each do |post| %>
  <h3>
    <%= post.title %>
  </h3>
  <p>
    <%= post.content %>
  </p>
<% end %>
</code>```

In both controllers' index action:

@posts = Post.all

In the posts/index view:

<%= render 'posts' %>

In the pages/index view:

<%= render 'posts/posts' %>

I don't want to confuse things, but Rails has a little magic in there where -
 alternatively - you can define a partial _post.html.erb as follows:

```<code><h3>
  <%= post.title %>
</h3>
<p>
  <%= post.content %>
</p>
</code>```

And simply call <%= render @posts %> in each view. This would be the best 'Railsy' way of doing things.

Let me know how you get on!

Body:
I'm new in ruby on rails, and I want to practice it.
I'm stuck when I want to include a view into antoher view.
I want by doing that to have my posts into another view than of posts/index

posts/index

method:

def index
    @Posts = Post.all
end

view:

<% @posts = capture do %>

   <% @posts.each do |post| %>

      <%= post.title %>

     <%= post.content %>

  <% end %>

<% end %>

pages/index

 Index Of another pages

<%= @posts %>

Body:
It sounds to me like you need to save the reusable view code as a partial, and render it all places it's required.

To use a partial, save it down with an underscore prefix, i.e. _posts.html.erb.

This can then be rendered using:

<%= render 'path/to/posts' %>

You'll likely need to pass in the posts variable to the partial, as in the following:

<%= render 'path/to/posts', posts: @posts %>

And the change your view to use posts rather than @posts.

Update:

The result of capture is assigned to @posts, although this variable still wouldn't be available in another template - rather to be used again on the same page

Based on what you're saying about the project's structure, it sounds like you'd need the following:

in app/views/posts/_posts.html.web

<% @posts.each do |post| %>
  <h3>
    <%= post.title %>
  </h3>
  <p>
    <%= post.content %>
  </p>
<% end %>

In both controllers' index action:

@posts = Post.all

In the posts/index view:

<%= render 'posts' %>

In the pages/index view:

<%= render 'posts/posts' %>

I don't want to confuse things, but Rails has a little magic in there where -
 alternatively - you can define a partial _post.html.erb as follows:

<h3>
  <%= post.title %>
</h3>
<p>
  <%= post.content %>
</p>

And simply call <%= render @posts %> in each view. This would be the best 'Railsy' way of doing things.

Let me know how you get on!