问:
Drop-down list in Ember;
Is there a way where I can access the selected item in drop down list in ember via controller? Give me a short example.

Thanks in advance!

答:
You can create a drop down list by using HTML <select>:

Controller:

```<code>import Ember from 'ember';

export default Ember.Controller.extend({
  options: ['red', 'green', 'blue'],

  selectedColor: null
});
</code>```

Template:

```<code>Pick your favourite color:

<br/>

<select onchange={{action (mut selectedColor) value='target.value'}}>
{{#each options as |option|}}
    <option value={{option}}>{{option}}</option>
{{/each}}
</select>

<br/><br/>

Your favourite color is: <b>{{selectedColor}}</b>
</code>```

Live demo.

Title: Drop-down list in Ember;

Body:
You can create a drop down list by using HTML <select>:

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  options: ['red', 'green', 'blue'],

  selectedColor: null
});

Template:

Pick your favourite color:

<br/>

<select onchange={{action (mut selectedColor) value='target.value'}}>
{{#each options as |option|}}
    <option value={{option}}>{{option}}</option>
{{/each}}
</select>

<br/><br/>

Your favourite color is: <b>{{selectedColor}}</b>

Live demo.


来源: stackexchange

问:
Nested List comprehension
I have 2 lists, A and B.

A is list of dictionaries which contain list of values.

B is a simple list.

Requirement is to add the elements of list B into dictionary values of A.

Below is the code,

```<code>a = [{'a':[1,5]}, {'b' : [6,10]}, {'c' : [11,15]}]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in a:
  for k,j in i.items():
      for m,n in enumerate(b):
          if j[0]<= n<=j[1]:
              j.append(n)

print(a)

[{'a':[1,5,1,2,3,4,5]}, {'b' : [6,10,6,7,8,9,10]}, {'c' :
[11,15,11,12,13,14,15]}]

# tried list comprehension
a= [{k:n} for i in a for k,j in i.items() for m,n in enumerate(b)
if j[0]<= n<=j[1]]

print(a)

[{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}, {'b': 6}, {'b': 7},
{'b': 8}, {'b': 9}, {'b': 10}, {'c': 11}, {'c': 12}, {'c': 13}, {'c':
14}, {'c': 15}]
</code>```

Question is whether this can be done using list comprehension? I have tried but unable to generate the required output.

答:
```<code>a = [{k: [ x for x in b if v[0] <= x <= v[1] ]} for d in a for k,v in d.items()]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Nested List comprehension

Body:
I have 2 lists, A and B.

A is list of dictionaries which contain list of values.

B is a simple list.

Requirement is to add the elements of list B into dictionary values of A.

Below is the code,

a = [{'a':[1,5]}, {'b' : [6,10]}, {'c' : [11,15]}]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in a:
  for k,j in i.items():
      for m,n in enumerate(b):
          if j[0]<= n<=j[1]:
              j.append(n)

print(a)

[{'a':[1,5,1,2,3,4,5]}, {'b' : [6,10,6,7,8,9,10]}, {'c' :
[11,15,11,12,13,14,15]}]

# tried list comprehension
a= [{k:n} for i in a for k,j in i.items() for m,n in enumerate(b)
if j[0]<= n<=j[1]]

print(a)

[{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}, {'b': 6}, {'b': 7},
{'b': 8}, {'b': 9}, {'b': 10}, {'c': 11}, {'c': 12}, {'c': 13}, {'c':
14}, {'c': 15}]

Question is whether this can be done using list comprehension? I have tried but unable to generate the required output.


问:
Create parameterized VIEW in SQL Server 2008
Can we create parameterized VIEW in SQL Server 2008.

Or Any other alternative for this ?

答:
As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.

(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)

Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.

ContentLicense: CC BY-SA 2.5


问:
ANDROID Best way to load dynamic preference
I am creating an application who show a scool time table . The user need to choose his establishement,formation, group. But there no the same groups for each formations and each establishments.
E.g:
Establishement 1
 -formation 1
  -group 1
  -group 2
 - formation 2
  -group A
  -group B
  -..
Establishement 2
[..]

So to load preference I have trying to use AsyncTask to get 3 JSON from server : establishment and when the user choose the Establishement it get JSON of formation ...
But the Asynctask is too slow and crash the app if the user click on preference list before the end of the load.
So My question : How can I optimize this ? (not with the code but with a new method)
Thanks for reading me.
Have a nice day.

答: You don't let them click on anything until your data is loaded.  Put up a loading screen, do the AsyncTask, then remove the loading screen and go to your real app when its done.</p>


问:
Odoo v10 display amount in company currency in purchase tree and form view
I am using Odoo v10 .

As we know in purchase.order, there is a base (Monetary) field amount_total which contains value of total amount of a Purchase Order based on (self) currency_id .

Now, I create a new float field home_currency_amount_total in purchase.order .

```<code>home_currency_amount_total = fields.Float(string='Total Amount in company currency', store=True)
</code>```

How can i have a value in this field based on company currency? i.e. I want to have a corresponding value in company base currency and can be used in my tree & form views.

I am new to Odoo and I wonder if there is a "shortcut"  (e.g. a built-in compute method) instead of I have to write up related codes.

答:
You can do it using following method.

```<code>class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    @api.multi
    @api.depends('amount_total')
    def get_amount_in_company_currency(self):
        for purchase_order in self:
            if purchase_order.currency_id.id!=purchase_order.company_id.currency_id.id:
                currency_id = purchase_order.currency_id.with_context(date=purchase_order.date_order)
                purchase_order.home_currency_amount_total = currency_id.compute(purchase_order.amount_total, purchase_order.company_id.currency_id)
            else:
                purchase_order.home_currency_amount_total=purchase_order.amount_total
    home_currency_amount_total = fields.Float(string='Total Amount in company currency',compute="get_amount_in_company_currency",store=True)
</code>```

In above code we have create one compute field store True, it means value will  be store in the database.

When amount_total will change at that time system will calculate home currency amount.

In method we have checked if company currency & purchase order currency is different then system will compute currency amount.

In odoo base module on method is available for compute currency, in which you can pass date in the context.

purchase_order.currency_id.with_context(date=purchase_order.date_order)

Based on context date system will take currency rate, if you not pass
  any date then system will take current date rate.

This will help you.

Body:
I am using Odoo v10 .

As we know in purchase.order, there is a base (Monetary) field amount_total which contains value of total amount of a Purchase Order based on (self) currency_id .

Now, I create a new float field home_currency_amount_total in purchase.order .

home_currency_amount_total = fields.Float(string='Total Amount in company currency', store=True)

How can i have a value in this field based on company currency? i.e. I want to have a corresponding value in company base currency and can be used in my tree & form views.

I am new to Odoo and I wonder if there is a "shortcut"  (e.g. a built-in compute method) instead of I have to write up related codes.

Body:
You can do it using following method.

class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    @api.multi
    @api.depends('amount_total')
    def get_amount_in_company_currency(self):
        for purchase_order in self:
            if purchase_order.currency_id.id!=purchase_order.company_id.currency_id.id:
                currency_id = purchase_order.currency_id.with_context(date=purchase_order.date_order)
                purchase_order.home_currency_amount_total = currency_id.compute(purchase_order.amount_total, purchase_order.company_id.currency_id)
            else:
                purchase_order.home_currency_amount_total=purchase_order.amount_total
    home_currency_amount_total = fields.Float(string='Total Amount in company currency',compute="get_amount_in_company_currency",store=True)

In above code we have create one compute field store True, it means value will  be store in the database.

When amount_total will change at that time system will calculate home currency amount.

In method we have checked if company currency & purchase order currency is different then system will compute currency amount.

In odoo base module on method is available for compute currency, in which you can pass date in the context.

purchase_order.currency_id.with_context(date=purchase_order.date_order)

Based on context date system will take currency rate, if you not pass
  any date then system will take current date rate.

This will help you.


问:
Curl request fails error "Failed to connect to 103.xx.xxx.xx port 8085: Connection refused"
$url = 'http://103.xx.xxx.xx:8085/MessagingGateway/SendTransSMS?Username='.$smsUserName.'&Password='.$smsUserPass.'&MessageType=txt&Mobile='.$mobile.'&SenderID='.$senderID.'&Message='.$message;

```<code>    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $result = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    return response()->json(['status'=>'success', 'msg'=>$result, 'url' =>$url]);
</code>```

Same code is working on localhost xampp server but it is not working godaddy shared hosting.

Error showing: "Failed to connect to 103.xx.xxx.xx port 8085: Connection refused". Please suggest me what i am doing wrong?

答: It might help troubleshoot the issue if you could try to execute the same request from an https enabled domain/hosting. Additionally this might be related to your server's firewall blocking the request.</p>

Body:
$url = 'http://103.xx.xxx.xx:8085/MessagingGateway/SendTransSMS?Username='.$smsUserName.'&Password='.$smsUserPass.'&MessageType=txt&Mobile='.$mobile.'&SenderID='.$senderID.'&Message='.$message;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $result = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    return response()->json(['status'=>'success', 'msg'=>$result, 'url' =>$url]);

Same code is working on localhost xampp server but it is not working godaddy shared hosting.

Error showing: "Failed to connect to 103.xx.xxx.xx port 8085: Connection refused". Please suggest me what i am doing wrong?


问:
Username validation with regular expression in php
I am trying to validate a USERNAME in PHP using Regular Expression. But I am failed. My pattern is: /[^a-z0-9_]/

Rules:

username must start number or small letters

username support number, small letters and _

the end of username character is not be _

答:
Assuming the minimum number of characters is two (if less than three, the underscore never would be permitted), here is the correct pattern:

```<code>^[a-z0-9][a-z0-9_]*[a-z0-9]$
</code>```

First character is small letters or digit (there can be more of them, that's why the + sign. Then any amount (including zero) of characters including underscore. At the end again, at least one letter or digit.

You can test it here:

https://regex101.com/r/C1zPfu/1

Body:
Assuming the minimum number of characters is two (if less than three, the underscore never would be permitted), here is the correct pattern:

^[a-z0-9][a-z0-9_]*[a-z0-9]$

First character is small letters or digit (there can be more of them, that's why the + sign. Then any amount (including zero) of characters including underscore. At the end again, at least one letter or digit.

You can test it here:

https://regex101.com/r/C1zPfu/1


问:
How to animate the textview (very very long text )scroll automatically horizontally
I am not interested in Marquee because, in Marquee you can not control the speed of marquee.
I have tried to animate the textview but Parent view clips the text at the end even though all parent layout and view groups encompassing textviews are set with two flags clipchildren= false, clipToPadding=false.

Am I missing something or is there a better work around ?

The xml looks like

```<code><TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="66dp"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#585858"
        android:textSize="32sp" >
    </TextView>
</code>```

and code snippet look like

```<code>TextView textView2 = (TextView)findViewById( R.id.textview1 );
textView2.startAnimation((Animation)AnimationUtils.loadAnimation(this, R.anim.translate));
</code>```

答:
I am sure this will definitely solve the problem of the large audience out there.

Q: Auto-scroll a single line long text message(either using hard_coding or from string.xml) horizontally & infinitely at a reasonable speed but using marquee(try it once at least). No clipping

Step 1:
In activity_main.xml file:

```<code><TextView
    android:text="either hard coding or from string.xml"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"
    android:background="@color/colorPrimary"
    android:textSize="18sp"
    android:marqueeRepeatLimit="marquee_forever"
    android:textColor="@android:color/background_light" />
</code>```

Step 2: In main_activity java file
public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textView = (TextView) findViewById(R.id.textView2);
    textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    textView.setSelected(true);
    textView.setSingleLine(true);
    textView.setText("Oxfam says 8 men as rich as half the world. | Govt may set threshold for probe into deposits. | At least 32 dead after Turkish plane hits village.");}}
</code>```

//one can remove the last line  line if he has already feed the long input

Body:
I am not interested in Marquee because, in Marquee you can not control the speed of marquee.
I have tried to animate the textview but Parent view clips the text at the end even though all parent layout and view groups encompassing textviews are set with two flags clipchildren= false, clipToPadding=false.

Am I missing something or is there a better work around ?

The xml looks like

<TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="66dp"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#585858"
        android:textSize="32sp" >
    </TextView>

and code snippet look like

TextView textView2 = (TextView)findViewById( R.id.textview1 );
textView2.startAnimation((Animation)AnimationUtils.loadAnimation(this, R.anim.translate));

Body:
I am sure this will definitely solve the problem of the large audience out there.

Q: Auto-scroll a single line long text message(either using hard_coding or from string.xml) horizontally & infinitely at a reasonable speed but using marquee(try it once at least). No clipping

Step 1:
In activity_main.xml file:

<TextView
    android:text="either hard coding or from string.xml"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"
    android:background="@color/colorPrimary"
    android:textSize="18sp"
    android:marqueeRepeatLimit="marquee_forever"
    android:textColor="@android:color/background_light" />

Step 2: In main_activity java file
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textView = (TextView) findViewById(R.id.textView2);
    textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    textView.setSelected(true);
    textView.setSingleLine(true);
    textView.setText("Oxfam says 8 men as rich as half the world. | Govt may set threshold for probe into deposits. | At least 32 dead after Turkish plane hits village.");}}

//one can remove the last line  line if he has already feed the long input

ContentLicense: CC BY-SA 4.0


问:
In Lean, is it possible to use decidable_linear_order with a user defined equality relation?
Lean comes with a decidable_linear_order typeclass containing useful lemmas about an ordering and its relation to equality, such as:

lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a

The equalities in these orderings are all expressed in terms of =:

```<code>inductive eq {α : Sort u} (a : α) : α → Prop
| refl : eq a
</code>```

I was wondering whether it would be possible to somehow extend this class (and its superclasses) to work with an arbitrary used defined equality relation R: α → α → Prop that was reflexive, symmetric and transitive, or would this only be possible by rewriting all the relevant lemmas and their proofs to use R instead of eq?

答: Since these classes are not parameterized by the equality relation, you would indeed have to reimplement them (perhaps metaprogramming may be of help for that). Alternatively, because you have an equivalence relation, you could define your order on the quotient type and so keep using eq.

Body:
Lean comes with a decidable_linear_order typeclass containing useful lemmas about an ordering and its relation to equality, such as:

lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a

The equalities in these orderings are all expressed in terms of =:

inductive eq {α : Sort u} (a : α) : α → Prop
| refl : eq a

I was wondering whether it would be possible to somehow extend this class (and its superclasses) to work with an arbitrary used defined equality relation R: α → α → Prop that was reflexive, symmetric and transitive, or would this only be possible by rewriting all the relevant lemmas and their proofs to use R instead of eq?


问:
iOS Parallax Scrolling effect (like in Yahoo News Digest app)
I would like to know how to implement parallax scrolling similar to Yahoo News Digest app. In which when user scroll horizontally background image scrolls in a different speed with the paging is enabled.

May be they do it with a ScrollView with a background view. Not exactly sure. Hint to implement such scrolling would be great. I have checked similar questions but couldn't find the answer I was looking for.

答:
100% working and dam easy

Take a view on imageview exactly size of image view.
by default alpha for view set 0.

```<code>//MARK: Scroll View Delegate methods
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

  NSLog(@"X: %f Y: %f",scrollView.contentOffset.x,scrollView.contentOffset.y);

CGFloat scrollY = _mainScrollView.contentOffset.y;
CGFloat height = _alphaView.frame.size.height;

CGFloat alphaMonitor = scrollY/height;

_alphaView.alpha = alphaMonitor;
}
</code>```

Body:
100% working and dam easy

Take a view on imageview exactly size of image view.
by default alpha for view set 0.

//MARK: Scroll View Delegate methods
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

  NSLog(@"X: %f Y: %f",scrollView.contentOffset.x,scrollView.contentOffset.y);

CGFloat scrollY = _mainScrollView.contentOffset.y;
CGFloat height = _alphaView.frame.size.height;

CGFloat alphaMonitor = scrollY/height;

_alphaView.alpha = alphaMonitor;
}


答:
The following pattern will work: ^[a-z0-9][a-z0-9_]*[a-z0-9]$

^[a-z0-9]: first character may not be an underscore

[a-z0-9_]*: all the others may be anything...

[a-z0-9]$: ...except the last one which can't be an underscore.

Title: Username validation with regular expression in php

Body:
I am trying to validate a USERNAME in PHP using Regular Expression. But I am failed. My pattern is: /[^a-z0-9_]/

Rules:

username must start number or small letters

username support number, small letters and _

the end of username character is not be _


问:
How do I program-select multiple items in a ListView in JavaFx?
Oracle docs say about “selectIndices”: This method allows for one or more selections to be set at the same time.
selectIndices(int index, int... indices)
https://docs.oracle.com/javafx/2/api/javafx/scene/control/MultipleSelectionModel.html

It does not accept an int[] array. It accepts ints separated with commas:

```<code>list.getSelectionModel().selectIndices(0,2);
</code>```

But how to do this in program?
I can manually select multiple items in the ListView OK.

答:
It does accept an int[] array, but only as second parameter. The only inconvenience is that there is a first parameter to ensure you pass at least one index.

Fortunately selectIndices's contract also contains a part that allows you to pass a value as first parameter that will be ignored:

It will ignore any value that is not within the valid range (i.e. greater than or equal to zero, and less than the total number of items in the underlying data model).

So you can safely pass -1 as first parameter and all the indices to select as second parameter.

Example

```<code>private static void select(ListView<?> listView, int divisor, int remainder) {
    MultipleSelectionModel<?> selectionModel = listView.getSelectionModel();

    // create array of indices to select
    final int size = listView.getItems().size();
    int selectionSize = size / divisor;
    if (size % divisor > remainder) {
        selectionSize++;
    }
    int[] selectedIndices = new int[selectionSize];
    for (int i = 0, value = remainder; i < selectionSize; i++, value += divisor) {
        selectedIndices[i] = value;
    }

    // unselect currently selected items
    selectionModel.clearSelection();

    // select indices in the array
    selectionModel.selectIndices(-1, selectedIndices);
}

@Override
public void start(Stage primaryStage) {
    ListView<Integer> listView = new ListView<>();
    listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    for (int i = 0; i < 99; i++) {
        listView.getItems().add(i);
    }

    Button btn = new Button("Select Even");
    btn.setOnAction(evt -> select(listView, 2, 0));

    Button btn2 = new Button("Select Odd");
    btn2.setOnAction(evt -> select(listView, 2, 1));

    Scene scene = new Scene(new VBox(10, listView, btn, btn2));

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

Body:
Oracle docs say about “selectIndices”: This method allows for one or more selections to be set at the same time.
selectIndices(int index, int... indices)
https://docs.oracle.com/javafx/2/api/javafx/scene/control/MultipleSelectionModel.html

It does not accept an int[] array. It accepts ints separated with commas:

list.getSelectionModel().selectIndices(0,2);

But how to do this in program?
I can manually select multiple items in the ListView OK.

Body:
It does accept an int[] array, but only as second parameter. The only inconvenience is that there is a first parameter to ensure you pass at least one index.

Fortunately selectIndices's contract also contains a part that allows you to pass a value as first parameter that will be ignored:

It will ignore any value that is not within the valid range (i.e. greater than or equal to zero, and less than the total number of items in the underlying data model).

So you can safely pass -1 as first parameter and all the indices to select as second parameter.

Example

private static void select(ListView<?> listView, int divisor, int remainder) {
    MultipleSelectionModel<?> selectionModel = listView.getSelectionModel();

    // create array of indices to select
    final int size = listView.getItems().size();
    int selectionSize = size / divisor;
    if (size % divisor > remainder) {
        selectionSize++;
    }
    int[] selectedIndices = new int[selectionSize];
    for (int i = 0, value = remainder; i < selectionSize; i++, value += divisor) {
        selectedIndices[i] = value;
    }

    // unselect currently selected items
    selectionModel.clearSelection();

    // select indices in the array
    selectionModel.selectIndices(-1, selectedIndices);
}

@Override
public void start(Stage primaryStage) {
    ListView<Integer> listView = new ListView<>();
    listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    for (int i = 0; i < 99; i++) {
        listView.getItems().add(i);
    }

    Button btn = new Button("Select Even");
    btn.setOnAction(evt -> select(listView, 2, 0));

    Button btn2 = new Button("Select Odd");
    btn2.setOnAction(evt -> select(listView, 2, 1));

    Scene scene = new Scene(new VBox(10, listView, btn, btn2));

    primaryStage.setScene(scene);
    primaryStage.show();
}


问:
Thrown exception of java.lang.NullPointerException after importing image to my Main Activity XML file
So i tried to copy an image downloaded from the internet to my android studio mainactivity xml file via copying the image and pasting it onto the drawable resource folder, But for some reason, I got an error of "Failed to instantiate one or more classes" This is the first time I'm getting this error as my previous images copied the exact same way had no errors except for other images such as this one. Does it have something to do with PNG or JPG format?I tried to resync the project with Gradle files but its still the same. What should I do to solve this exception? Thank You.

1) the process of copying and pasting image to drawable

2) The error itself after pasting the image

```<code>java.lang.NullPointerException
at android.content.res.Resources_Delegate.getValue(Resources_Delegate.java:788)
at android.content.res.Resources.getValue(Resources.java:1286)
at android.support.v7.widget.AppCompatDrawableManager.createDrawableIfNeeded(AppCompatDrawableManager.java:236)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:199)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)
at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:54)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
at sun.reflect.GeneratedConstructorAccessor1111.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:250)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

Edit: Also, When i try to compile the code, my project would'nt start unless i delete the image file in my drawable folder due to this error : `Error:Execution failed for task ':app:mergeDebugResources'.

C:\Users\TP_baseline\AndroidStudioProjects\COMTProject(MeloWide)\app\src\main\res\drawable\icons8-Medal-80.png: Error: '-' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore`

答:
The problem is arise in two condition
1)in android resource names must contain only lowercase a-z, 0-9, or underscore.
2)if your image is corrupted then provide this type of error.so check in your resource any image file is corrupted </p>

Body:
So i tried to copy an image downloaded from the internet to my android studio mainactivity xml file via copying the image and pasting it onto the drawable resource folder, But for some reason, I got an error of "Failed to instantiate one or more classes" This is the first time I'm getting this error as my previous images copied the exact same way had no errors except for other images such as this one. Does it have something to do with PNG or JPG format?I tried to resync the project with Gradle files but its still the same. What should I do to solve this exception? Thank You.

1) the process of copying and pasting image to drawable

2) The error itself after pasting the image

java.lang.NullPointerException
at android.content.res.Resources_Delegate.getValue(Resources_Delegate.java:788)
at android.content.res.Resources.getValue(Resources.java:1286)
at android.support.v7.widget.AppCompatDrawableManager.createDrawableIfNeeded(AppCompatDrawableManager.java:236)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:199)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)
at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:54)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
at sun.reflect.GeneratedConstructorAccessor1111.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:250)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Edit: Also, When i try to compile the code, my project would'nt start unless i delete the image file in my drawable folder due to this error : `Error:Execution failed for task ':app:mergeDebugResources'.

C:\Users\TP_baseline\AndroidStudioProjects\COMTProject(MeloWide)\app\src\main\res\drawable\icons8-Medal-80.png: Error: '-' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore`


问:
expected `;' before "pennies"? C++ Debugging (Code Completed)
Can anyone tell me why I get an error on my last cout?

```<code>#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}
</code>```

答:
You are missing the << between the variables.

Try:

cout << saying << pennies << penn <<
  "\n" << saying << nickles << five <<
  "\n" << saying << dimes << ten << "\n"
  << saying << quarters << twentyfive <<
  "\n" << saying << half_dollars <<
  fifty << "\n";

Update:

The scope of some of your variables, such as penn, means they cannot be seen in the cout statement.

You need to declare the variables outside the if/else statements.

Also, as mentioned by @Color Bend, you are missing a semicolon after the keep_window_open() function.

Body:
Can anyone tell me why I get an error on my last cout?

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}


问:
JSONObject parsing in android?
The JSONObject looks like

```<code>{"result":
     {
        "id":"1",
        "name":"ankur",
        "email":"ankur@gmail.com",
        "address":"bblock",
        "designation":"devloper",
        "department":"development",
        "balanceleave":"5"
     }
}
</code>```

and my parse code looks like

```<code>Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("id", response.getString("id"));
intent.putExtra("name", response.getString("name"));
intent.putExtra("email", response.getString("email"));
intent.putExtra("address", response.getString("address"));
intent.putExtra("designation", response.getString("designation"));
intent.putExtra("department", response.getString("department"));
intent.putExtra("balanceleave", response.getString("balanceleave"));

startActivity(intent);
</code>```

Can you help me out, actually I am parsing the JSON and sending it to the profile activity to display and if you can comeup with something that I can send the JSONObject to profile that would be great!!

答:
Try like this : </p>

```<code>JSONObject response=new JSONObject("your response string");
JSONObject result=response.getJSONObject("result");
String id=result.getString("id");
String name=result.getString("name"));
String email=result.getString("email"));
String address=result..getString("address"));
String designation=result.getString("designation"));
String department=result.getString("department"));
String balanceleave=result.getString("balanceleave"));
</code>```

Title: JSONObject parsing in android?

Body:
The JSONObject looks like

{"result":
     {
        "id":"1",
        "name":"ankur",
        "email":"ankur@gmail.com",
        "address":"bblock",
        "designation":"devloper",
        "department":"development",
        "balanceleave":"5"
     }
}

and my parse code looks like

Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("id", response.getString("id"));
intent.putExtra("name", response.getString("name"));
intent.putExtra("email", response.getString("email"));
intent.putExtra("address", response.getString("address"));
intent.putExtra("designation", response.getString("designation"));
intent.putExtra("department", response.getString("department"));
intent.putExtra("balanceleave", response.getString("balanceleave"));

startActivity(intent);

Can you help me out, actually I am parsing the JSON and sending it to the profile activity to display and if you can comeup with something that I can send the JSONObject to profile that would be great!!

Body:
Try like this :

JSONObject response=new JSONObject("your response string");
JSONObject result=response.getJSONObject("result");
String id=result.getString("id");
String name=result.getString("name"));
String email=result.getString("email"));
String address=result..getString("address"));
String designation=result.getString("designation"));
String department=result.getString("department"));
String balanceleave=result.getString("balanceleave"));


问:
best practice to manage GoogleApiClient
I have a background service which runs in the background tracking device location using a PendingIntent.

The service calls mFusedLocationClient.requestLocationUpdates(mLocationRequest, locationRequest, pendingIntent) to start location tracking but also sometimes to update the location tracking (change the frequency of updates).

Should I store the GoogleApiClient instance in the service class or should I connect to it each time I need it?

I'm worried if I store it, disconnection can appear. This shouldn't be a problem in theory because the documentation says GoogleApiClient automatically tries to reconnect itself.

If I connect each time to GoogleApiClient, it adds a bit of complexity in the code, because the connection made with connect() is asynchronous.

Based on your experience, what do you think is best?

答: You should call googleApiClient.connect() in onStart() of your activity and googleApiClient.disconnect() in onStop(). You can implement GoogleApiClient.ConnectionCallbacks, which will let you know if the client connects successfully via invoking public void onConnected(Bundle bundle) and then you can access your api.

Title: best practice to manage GoogleApiClient


问:
Handle space between repeated background image?
I have div element with size 200 x 200.

I added a background image to the element to the right side.

```<code>div {
    background-image: url('./images/dot.png');
    background-position: right;
    background-repeat: repeat-y;
}
</code>```

It is repeating nicely. But I want to control the space between repeated images. I want to add space of 20px between repeated images. How can I do that?

Edit

I need to add the space as much as I would like to add. If I use background-repeat: space I only get some space but it may not 10px or 20px or 30px. I want to add particular size(specific number).

答:
Answer base on this.

Suppose we have an apple image:

Step 1. Convert this image to Base64

For example you'll get

```<code>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=
</code>```

Step 2: Insert this Base64 to SVG

'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50" height="40"><image width="40" height="40" xlink:href="[paste it here]" /></svg>');

Step 3: copy this to CSS background-image

To get 10px space we have 50px width for CSS background-image, 40px for image tag of svg, 50 – 40 = 10 px.

body {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50" height="40"><image width="40" height="30" xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=" /></svg>');
}```
</div>
</div>
</p>

<h3>Step 4. If need IE/Edge support</h3>

<p>IE/Edge has following bug:</p>

<blockquote>
  <p>This is a longstanding difference between IE/Edge and Webkit based browsers where they do not require almost any values to be escaped in SVG data uris, and we require the entire value after the “utf8,” to be fully escaped. In the mean time, you can easily accomplish this yourself by using javascript’s built in escape function. That value will work in all browsers today.</p>
</blockquote>

<p>So to make it work use this SVG as external file or escape <code><svg>…</svg></code> part in <code>background-image</code>. For example using this CodePen.</p>

<hr>

<h3>Update</h3>

<p>If you want picture align to the right with <code>40px</code> space between images and <code>background-repeat: repeat-y</code> you need to set SVG height to <code>70px</code> (while image height is <code>30px</code>). Here is demo:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="70"><image width="40" height="30" xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=" /></svg>');
    background-repeat: repeat-y;
    background-position: right top;
}</code>```

Body:
I have div element with size 200 x 200.

I added a background image to the element to the right side.

div {
    background-image: url('./images/dot.png');
    background-position: right;
    background-repeat: repeat-y;
}

It is repeating nicely. But I want to control the space between repeated images. I want to add space of 20px between repeated images. How can I do that?

Edit

I need to add the space as much as I would like to add. If I use background-repeat: space I only get some space but it may not 10px or 20px or 30px. I want to add particular size(specific number).

Body:
Answer base on this.

Suppose we have an apple image:

Step 1. Convert this image to Base64

For example you'll get

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=

Step 2: Insert this Base64 to SVG

'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50" height="40"><image width="40" height="40" xlink:href="[paste it here]" /></svg>');

Step 3: copy this to CSS background-image

To get 10px space we have 50px width for CSS background-image, 40px for image tag of svg, 50 – 40 = 10 px.

body {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50" height="40"><image width="40" height="30" xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=" /></svg>');
}

Step 4. If need IE/Edge support

IE/Edge has following bug:

This is a longstanding difference between IE/Edge and Webkit based browsers where they do not require almost any values to be escaped in SVG data uris, and we require the entire value after the “utf8,” to be fully escaped. In the mean time, you can easily accomplish this yourself by using javascript’s built in escape function. That value will work in all browsers today.

So to make it work use this SVG as external file or escape <svg>…</svg> part in background-image. For example using this CodePen.

Update

If you want picture align to the right with 40px space between images and background-repeat: repeat-y you need to set SVG height to 70px (while image height is 30px). Here is demo:

body {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="70"><image width="40" height="30" xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlQBAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAB4AKAMBIgACEQEDEQH/xAAaAAACAwEBAAAAAAAAAAAAAAAECAUGBwMJ/9oACAEBAAAAAHF7EAEzEstyjOveEdsam+kw+VE5cxH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAwUG/9oACAECEAAAAMMmE7K3/8QAFwEBAAMAAAAAAAAAAAAAAAAABgMEBf/aAAgBAxAAAAC+sMIJc3//xAAsEAACAQIFBAAEBwAAAAAAAAABAgMEBQAGERIhBxMxQQgyUXEUI0JhYoGR/9oACAEBAAE/AFihQhnZdDhVZjpHFJJzxxtH+nAo6twSe1GPZPOmCkM9wegWWSaSOESylNuyPcdFVuddzaEgfQYeiWJP1Ff74xRWqBF02DuIdHJ5P3xHSgsVPJQDUfTd4Jx1Vzla6LMFfarhUSxx0dLEYo18F5Ru3EYqeplytzSw0s0csZPl4l3Bh4dW03A46EZwuOesiGruJMtTQ1r0jTnzKqqHUn+QDaHE2eZE7kixUsTGIoGJYjX0T9jix5/6mSdVaCkatmpWgucb1w3kwyQw8yFm1O8OuPiNgjzFVx5ntU8ImECU9dTAkb1T5JF3eSPBGLLQXK/3OGgp4vzJXA3yHtov7sx9DHTentmQMqUllpUirNjNNPO+4d2aT5mC68D0Mfi3UEKijjFJZTBf4KsFdy1IcnU6nnHUCaW4TR0xSMRRjdt9E4ioxBMrqiBkYEEeiMZau0lZa43mjVnHBP10x//EAB0RAAEEAwEBAAAAAAAAAAAAAAIAAQMSBBFBE1H/2gAIAQIBAT8AdRQeveIwICcfigySC9htsVjZlIdU2/HRzyOT7d1//8QAHxEAAgIDAAIDAAAAAAAAAAAAAQIDEQAEEhMhBhQi/9oACAEDAQE/AMg+NI+kmxNteMuoZV5v0cnjMEzx2DyavNVDFDMsZUB669Xg+2IUTyjkD8jH1kZyWom8/9k=" /></svg>');
    background-repeat: repeat-y;
    background-position: right top;
}


问:
What is the point of nulling private variables in destructor?
I have spot the following pattern in code I'm working with: in some classes in destructor I have found private variable being nulled, in example:

```<code>public function __destruct()
{
    foreach($this->observers as $observer)
    {
        $observer = null;
    }
    $this->db_build = null;
}
</code>```

Is there any point in doing this when PHP has GC? Does it somehow improve performance of script?

答:
It could be because PHP's garbage collection is based on reference countring, and older versions could not handle cyclical dependencies. Then, in some cases it would have been necessary to manually set references to null to enable the GC to do its work, and there may still be some special cases that the cycle detection algorithm does not catch.

More likely though, it's just an example of cargo cult programming (the Wikipedia entry even explicitly lists this as an example).

Body:
I have spot the following pattern in code I'm working with: in some classes in destructor I have found private variable being nulled, in example:

public function __destruct()
{
    foreach($this->observers as $observer)
    {
        $observer = null;
    }
    $this->db_build = null;
}

Is there any point in doing this when PHP has GC? Does it somehow improve performance of script?


问:
iOS 7 parallax effect in my view controller
I'm developing an app for iOS 7 in Objective-C. I've got a screen in my app with a few buttons and a pretty background image. (It's a simple xib with UIButtons on top of a UIImageView.)

I was thinking that it'd be cool if those buttons had the parallax effect that the iOS 7 home screen has, so if you tilt the phone you could see the background.

How can I implement that effect in my own app?

答:
Really dam easy to do so why refers complex code. just try it. Working

Take a view on imageview exactly size of image view.
by default alpha for view set 0.

```<code>//MARK: Scroll View Delegate methods
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

NSLog(@"X: %f Y: %f",scrollView.contentOffset.x,scrollView.contentOffset.y);

CGFloat scrollY = _mainScrollView.contentOffset.y;
CGFloat height = _alphaView.frame.size.height;

CGFloat alphaMonitor = scrollY/height;

_alphaView.alpha = alphaMonitor;
}
</code>```

Body:
Really dam easy to do so why refers complex code. just try it. Working

Take a view on imageview exactly size of image view.
by default alpha for view set 0.

//MARK: Scroll View Delegate methods
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

NSLog(@"X: %f Y: %f",scrollView.contentOffset.x,scrollView.contentOffset.y);

CGFloat scrollY = _mainScrollView.contentOffset.y;
CGFloat height = _alphaView.frame.size.height;

CGFloat alphaMonitor = scrollY/height;

_alphaView.alpha = alphaMonitor;
}


问:
Connection failed: SQLState: '01000' SQL Server Error: 10061
I'm trying to connect my access front-end to the SQL Server backend.

It was working when SQL Server was on my computer but now i'm trying to connect to a server

So when I create the DSN file with access

I chose SQL-Server driver ( I have also tried with SQL-Server native 10.0 )

I enter the server name that I copied from SQL Management Studio so there's no typo there

I chose the NT authentication

Then I have this error

In the properties, I tried with TCP/IP with the default port 1433 and I also tried with the name pipes

I made sure that the checkbox to allow remote connection is checked

If I try to connect with management studio I got this error

I can see the server when I browse on the network

I'm trying this troubleshotting but i'm stuck with the telnet command. It says Could not open connection to host on 1433

I also tried with no port and i got the same error on port 23

Any ideas?

Thank you

答:
Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it
  there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\


问:
Angular JS / Data Binding / Controller
I have two controllers and one service. Could someone explain me why
firstname will be not updatet / the reference is "old" when changing it?

I thought this is the way to communicate between controllers...?

```<code><!-- language: lang-js -->
// Controller 1
function controllerOne (..., myService) {
    $scope.firstname = myService.customer.firstname;
}

// Controller 2
function controllerTwo (..., myService) {
    $scope.firstnameNew = myService.customer.firstname;
}

// Service
application.factory('myService', ...)
    function(...) {
    return {
         customer: {
             "firstname": "",
             "lastname": "",
             "pers": "",
             "street": "",
             "zip": "",
             "city": "",
             "selectedCountry": "",
             "comment": ""
        },
                    ...
    }
</code>```

答:
```<code><body data-ng-app="myApp">
<div data-ng-controller="ctrl1">
        {{firstName}}
        {{lastName}}
    </div>
      <div data-ng-controller="ctrl2">
        {{firstName}}
        {{lastName}}
    </div>
</body>
Script :
         var myApp= angular.module('myApp', []);
myApp.controller('ctrl1', function ($scope, myService) {
    $scope.firstName = myService.firstName;
    $scope.lastName = myService.lastName;
    myService.firstName = "ABC";
    myService.lastName = "DEF";
});
myApp.controller('ctrl2', function ($scope, myService) {
    $scope.firstName = myService.firstName;
    $scope.lastName = myService.lastName;
});
myApp.factory('myService', function ($rootScope) {
    return {
        firstName: '123',
        lastName: '456'
    };
});
</code>```

Title: Angular JS / Data Binding / Controller

Body:
I have two controllers and one service. Could someone explain me why
firstname will be not updatet / the reference is "old" when changing it?

I thought this is the way to communicate between controllers...?

// Controller 1
function controllerOne (..., myService) {
    $scope.firstname = myService.customer.firstname;
}

// Controller 2
function controllerTwo (..., myService) {
    $scope.firstnameNew = myService.customer.firstname;
}

// Service
application.factory('myService', ...)
    function(...) {
    return {
         customer: {
             "firstname": "",
             "lastname": "",
             "pers": "",
             "street": "",
             "zip": "",
             "city": "",
             "selectedCountry": "",
             "comment": ""
        },
                    ...
    }


问:
Getting error Warning: mysqli::query(): Couldn't fetch mysqli in my code
Getting error Warning: mysqli::query(): Couldn't fetch mysqli in

```<code>  <?php

    include 'includes/config.php';
    include 'includes/database.php';
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    if (isset($_POST['sign'])) {
      $name=$_POST['email'];
      $pass=$_POST['password'];
      $query_two="SELECT * FROM admin WHERE user='$name' AND password='$pass' ";
      $runn=$db->query($query_two);

      $row_login=$runn->fetch_assoc();

    if ($row_login['user']==$name && $row_login['password']==$pass) {
      session_start();

      $_SESSION["username"] = $name;
      header('Location: adminpane.php');
      exit();

    }

    else {
      echo "<script>
    check();

      </script>

      ";
      exit();

    }

    }

     ?>
</code>```

this is in  my database.php file

```<code><?php
$db=new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
?>
</code>```

this is in my config.php file

```<code> <?php

define('DB_HOST', 'xxx.xxx.xxx.xxx');
define('DB_USERNAME', 'XXX');
define('DB_PASSWORD', 'XXX');
define('DB_NAME', 'myDB');

 ?>
</code>```

I am including both at the top,but still it doesnt seems to work!!,
  everything username password is correct and the code was working on
  local host

答:
Use something as :</p>

```<code><?php
session_start();
include 'includes/config.php';
include 'includes/database.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_POST['sign'])) {
  $name = mysqli_real_escape_string($db,$_POST['email']);
  $pass = mysqli_real_escape_string($db,$_POST['password']);
  $query_two = "SELECT * FROM admin WHERE user='$name' AND password='$pass'";
  $runn = mysqli_query($db,$query_two);
  $row_login = mysqli_fetch_assoc($runn);

  if ($row_login['user']==$name && $row_login['password']==$pass) {
   $_SESSION["username"] = $name;
   header('Location: adminpane.php');
   exit();
  } else {
   echo "<script>check();</script>";
   exit();
 }
}
?>
</code>```

Body:
Getting error Warning: mysqli::query(): Couldn't fetch mysqli in

  <?php

    include 'includes/config.php';
    include 'includes/database.php';
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    if (isset($_POST['sign'])) {
      $name=$_POST['email'];
      $pass=$_POST['password'];
      $query_two="SELECT * FROM admin WHERE user='$name' AND password='$pass' ";
      $runn=$db->query($query_two);

      $row_login=$runn->fetch_assoc();

    if ($row_login['user']==$name && $row_login['password']==$pass) {
      session_start();

      $_SESSION["username"] = $name;
      header('Location: adminpane.php');
      exit();

    }

    else {
      echo "

      ";
      exit();

    }

    }

     ?>

this is in  my database.php file

<?php
$db=new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
?>

this is in my config.php file

 <?php

define('DB_HOST', 'xxx.xxx.xxx.xxx');
define('DB_USERNAME', 'XXX');
define('DB_PASSWORD', 'XXX');
define('DB_NAME', 'myDB');

 ?>

I am including both at the top,but still it doesnt seems to work!!,
  everything username password is correct and the code was working on
  local host

Body:
Use something as :

<?php
session_start();
include 'includes/config.php';
include 'includes/database.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_POST['sign'])) {
  $name = mysqli_real_escape_string($db,$_POST['email']);
  $pass = mysqli_real_escape_string($db,$_POST['password']);
  $query_two = "SELECT * FROM admin WHERE user='$name' AND password='$pass'";
  $runn = mysqli_query($db,$query_two);
  $row_login = mysqli_fetch_assoc($runn);

  if ($row_login['user']==$name && $row_login['password']==$pass) {
   $_SESSION["username"] = $name;
   header('Location: adminpane.php');
   exit();
  } else {
   echo "<script>check();</script>";
   exit();
 }
}
?>


问:
PHP if statment for boolean/tinyint(1) type
What is the best way for boolen statement to know it is true or false?

In MYSQL database after select boolean it is showing tinyint(1) but the issue is when in database the value is 1,

I use if($var == 1) result is false and if($var == "1") is true.

But in my localhost (WAMP Server)

if($var == 1) is true

I am very confused the MYSQL version issue?
By the way I am using laravel framework...

答:
MySQL has very little to do with your problem and neither does laravel.

In php, 1 is true, "1" is true, 0 is false, and "0" is false. Therefore, you should be able to write it as if ($var) {} unless you abhor such conventions.


问:
Grid Recyclerview with 3 columns in even number row and 4 columns in odd number row
How to create a Grid Recyclerview with 3 columns in even number row and 4 columns in odd number row?</p>

```<code>    lLayout = new GridLayoutManager(getActivity(), 4, LinearLayoutManager.VERTICAL, false); // MAX NUMBER OF SPACES

    lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return (position % 3 == 0 ? 3 : 4);
        }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(lLayout);

    if (arrayList != null) {
        adapter = new RecyclerViewAdapter(getActivity(), arrayList);
        recyclerView.setAdapter(adapter);
    }
</code>```

答:
Try something like this

```<code> layoutManager = new GridLayoutManager(getActivity(), 4);
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position % 3 == 0)
                return 3;
            else
                return 4;
        }
    });
    recyclerView.setLayoutManager(layoutManager);
</code>```

Hope this helps

Body:
How to create a Grid Recyclerview with 3 columns in even number row and 4 columns in odd number row?

    lLayout = new GridLayoutManager(getActivity(), 4, LinearLayoutManager.VERTICAL, false); // MAX NUMBER OF SPACES

    lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return (position % 3 == 0 ? 3 : 4);
        }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(lLayout);

    if (arrayList != null) {
        adapter = new RecyclerViewAdapter(getActivity(), arrayList);
        recyclerView.setAdapter(adapter);
    }

Body:
Try something like this

 layoutManager = new GridLayoutManager(getActivity(), 4);
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position % 3 == 0)
                return 3;
            else
                return 4;
        }
    });
    recyclerView.setLayoutManager(layoutManager);

Hope this helps


答: The statement keep_window_open() those not have a semicolon.

Title: expected `;' before "pennies"? C++ Debugging (Code Completed)


问:
ANDROID Best way to load dynamic preference
I am creating an application who show a scool time table . The user need to choose his establishement,formation, group. But there no the same groups for each formations and each establishments.
E.g:
Establishement 1
 -formation 1
  -group 1
  -group 2
 - formation 2
  -group A
  -group B
  -..
Establishement 2
[..]

So to load preference I have trying to use AsyncTask to get 3 JSON from server : establishment and when the user choose the Establishement it get JSON of formation ...
But the Asynctask is too slow and crash the app if the user click on preference list before the end of the load.
So My question : How can I optimize this ? (not with the code but with a new method)
Thanks for reading me.
Have a nice day.

答: You can add a ProgressDialog to the Activity so until your data is loaded the user will be unable to click on anything. After the data is loaded you can call progressDialog.dismiss()</p>


问:
how to find the opid of an index build operation
I want to add a index for a collection(data_04), but after execute it in mongo shell

```<code>mongos> db.data_04.createIndex({"column1":1, "column":1,cacheDataTime:1 })
</code>```

but after quite a long time, it still did not finish. So I want to kill it explicitly and create it in background. But I first should know its opid, I tried below manner all nothing output

```<code># The following example returns information on index creation operations:
mongos> db.currentOp(
...     {
...       $or: [
...         { op: "query", "query.createIndexes": { $exists: true } },
...         { op: "insert", ns: /\.system\.indexes\b/ }
...       ]
...     }
... )

"inprog" : [ ],
"ok" : 1

mongos> db.currentOp(
...    {
...      "active" : true,
...      "ns" : /data_04/
...    }
... )

"inprog" : [ ],
"ok" : 1
</code>```

So what's wrong and how to find the opid of an index creation operation?

答:
In my case it should be </p>

```<code>db.currentOp(
    {
      $or: [
        { op: "command", "query.createIndexes": { $exists: true } },
        { op: "insert", ns: /\.system\.indexes\b/ }
      ]
    }
)

   {
    "desc" : "conn292",
    "threadId" : "140288792557312",
    "connectionId" : 292,
    "client_s" : "10.47.50.216:39380",
    "active" : true,
    "opid" : "shard1:2005849",
    "secs_running" : 42,
    "microsecs_running" : NumberLong(42991403),
    "op" : "command",
    "ns" : "mydata.$cmd",
    "query" : {
        "createIndexes" : "data_04",
        "indexes" : [
            {
                "key" : {
                    "column1" : 1,
                    "column" : 1,
                    "cacheDataTime" : 1
                },
                "name" : "column1_1_column_1_cacheDataTime_1",
                "background" : true
            }
        ]
    },
    "msg" : "Index Build (background) Index Build (background): 41209/1447644 2%",
    "progress" : {
        "done" : 41209,
        "total" : 1447644
    },
    "numYields" : 1369,
    "locks" : {
        "Global" : "w",
        "Database" : "w",
        "Collection" : "w"
    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(1370),
                "w" : NumberLong(1370)
            }
        },
        "Database" : {
            "acquireCount" : {
                "w" : NumberLong(1370),
                "W" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "w" : NumberLong(1370)
            }
        }
    }
}
</code>```

Body:
I want to add a index for a collection(data_04), but after execute it in mongo shell

mongos> db.data_04.createIndex({"column1":1, "column":1,cacheDataTime:1 })

but after quite a long time, it still did not finish. So I want to kill it explicitly and create it in background. But I first should know its opid, I tried below manner all nothing output

# The following example returns information on index creation operations:
mongos> db.currentOp(
...     {
...       $or: [
...         { op: "query", "query.createIndexes": { $exists: true } },
...         { op: "insert", ns: /\.system\.indexes\b/ }
...       ]
...     }
... )

"inprog" : [ ],
"ok" : 1

mongos> db.currentOp(
...    {
...      "active" : true,
...      "ns" : /data_04/
...    }
... )

"inprog" : [ ],
"ok" : 1

So what's wrong and how to find the opid of an index creation operation?

Body:
In my case it should be

db.currentOp(
    {
      $or: [
        { op: "command", "query.createIndexes": { $exists: true } },
        { op: "insert", ns: /\.system\.indexes\b/ }
      ]
    }
)

   {
    "desc" : "conn292",
    "threadId" : "140288792557312",
    "connectionId" : 292,
    "client_s" : "10.47.50.216:39380",
    "active" : true,
    "opid" : "shard1:2005849",
    "secs_running" : 42,
    "microsecs_running" : NumberLong(42991403),
    "op" : "command",
    "ns" : "mydata.$cmd",
    "query" : {
        "createIndexes" : "data_04",
        "indexes" : [
            {
                "key" : {
                    "column1" : 1,
                    "column" : 1,
                    "cacheDataTime" : 1
                },
                "name" : "column1_1_column_1_cacheDataTime_1",
                "background" : true
            }
        ]
    },
    "msg" : "Index Build (background) Index Build (background): 41209/1447644 2%",
    "progress" : {
        "done" : 41209,
        "total" : 1447644
    },
    "numYields" : 1369,
    "locks" : {
        "Global" : "w",
        "Database" : "w",
        "Collection" : "w"
    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(1370),
                "w" : NumberLong(1370)
            }
        },
        "Database" : {
            "acquireCount" : {
                "w" : NumberLong(1370),
                "W" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "w" : NumberLong(1370)
            }
        }
    }
}


答:
You can write below line

```<code>JSONString url = objectname.getJsonString("url");
</code>```

then put in intent

Title: JSONObject parsing in android?

Body:
You can write below line

JSONString url = objectname.getJsonString("url");

then put in intent


答:
Try this,

```<code>// Create a grid layout with 12 columns
    // (least common multiple of 3 and 4)
 GridLayoutManager manager = new GridLayoutManager(this, 12, GridLayoutManager.VERTICAL, false);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 7 is the sum of items in one repeated section
                switch (position % 7) {
                    // first three items span 3 columns each
                    case 0:
                    case 1:
                    case 2:
                        return 4;
                    // next four items span 2 columns each

                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        return 3;
                }
                throw new IllegalStateException("internal error");
            }
        });
        recyclerView.setLayoutManager(manager);
</code>```

Title: Grid Recyclerview with 3 columns in even number row and 4 columns in odd number row

Body:
Try this,

// Create a grid layout with 12 columns
    // (least common multiple of 3 and 4)
 GridLayoutManager manager = new GridLayoutManager(this, 12, GridLayoutManager.VERTICAL, false);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 7 is the sum of items in one repeated section
                switch (position % 7) {
                    // first three items span 3 columns each
                    case 0:
                    case 1:
                    case 2:
                        return 4;
                    // next four items span 2 columns each

                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        return 3;
                }
                throw new IllegalStateException("internal error");
            }
        });
        recyclerView.setLayoutManager(manager);


问:
Custom underline effect, other than creating a background image for it
is there a better way to create this style of "underline" through CSS, other than creating a background image for it?

To be clear, I'm only interested in the "duplicated line" effect, a thicker and shorter line sitting directly atop a thinner and longer line of a different color. Thanks!

答:
You can use pseudo elements here, i.e. :before and :after. Here, what am doing is, using an h1 element which am displaying it as inline-block. Later, we need to use CSS positioning to set both the bottom borders in place, as the borders are smaller than your element.

Later, again by using CSS positioning, we position the small border on top of the bigger one. Note that am using left: 50%; and transform: translateX(-50%) to position the border in horizontally center.

Make sure you don't miss out the z-index as it is important to use here, else the other border will render on top of the smaller one.

@import url('https://fonts.googleapis.com/css?family=Varela+Round');

* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}

h1 {
  position: relative;
  display: inline-block;
  font-family: Varela Round;
  font-size: 24px;
  text-transform: uppercase;
  font-weight: bold;
  color: #401f1c;
  margin: 40px; /* not required, only for demo purpose */
}

h1 span {
  color: #efcc4c;
}

h1:before,
h1:after {
  content: '';
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

h1:before {
  bottom: -11px;
  width: 40px;
  border-bottom: 3px solid #efcc4c;
  z-index: 1;
}

h1:after {
  width: 80%;
  border-bottom: 1px solid #ddd;
  bottom: -10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Our <span>Services</span></h1></code>```

Edit: Refactored my code and making the demo more precisee.

Body:
You can use pseudo elements here, i.e. :before and :after. Here, what am doing is, using an h1 element which am displaying it as inline-block. Later, we need to use CSS positioning to set both the bottom borders in place, as the borders are smaller than your element.

Later, again by using CSS positioning, we position the small border on top of the bigger one. Note that am using left: 50%; and transform: translateX(-50%) to position the border in horizontally center.

Make sure you don't miss out the z-index as it is important to use here, else the other border will render on top of the smaller one.

@import url('https://fonts.googleapis.com/css?family=Varela+Round');

* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}

h1 {
  position: relative;
  display: inline-block;
  font-family: Varela Round;
  font-size: 24px;
  text-transform: uppercase;
  font-weight: bold;
  color: #401f1c;
  margin: 40px; /* not required, only for demo purpose */
}

h1 span {
  color: #efcc4c;
}

h1:before,
h1:after {
  content: '';
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

h1:before {
  bottom: -11px;
  width: 40px;
  border-bottom: 3px solid #efcc4c;
  z-index: 1;
}

h1:after {
  width: 80%;
  border-bottom: 1px solid #ddd;
  bottom: -10px;
}

<h1>Our <span>Services</span></h1>

Edit: Refactored my code and making the demo more precisee.


问:
Nested List comprehension
I have 2 lists, A and B.

A is list of dictionaries which contain list of values.

B is a simple list.

Requirement is to add the elements of list B into dictionary values of A.

Below is the code,

```<code>a = [{'a':[1,5]}, {'b' : [6,10]}, {'c' : [11,15]}]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in a:
  for k,j in i.items():
      for m,n in enumerate(b):
          if j[0]<= n<=j[1]:
              j.append(n)

print(a)

[{'a':[1,5,1,2,3,4,5]}, {'b' : [6,10,6,7,8,9,10]}, {'c' :
[11,15,11,12,13,14,15]}]

# tried list comprehension
a= [{k:n} for i in a for k,j in i.items() for m,n in enumerate(b)
if j[0]<= n<=j[1]]

print(a)

[{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}, {'b': 6}, {'b': 7},
{'b': 8}, {'b': 9}, {'b': 10}, {'c': 11}, {'c': 12}, {'c': 13}, {'c':
14}, {'c': 15}]
</code>```

Question is whether this can be done using list comprehension? I have tried but unable to generate the required output.

Title: Nested List comprehension

Body:
I have 2 lists, A and B.

A is list of dictionaries which contain list of values.

B is a simple list.

Requirement is to add the elements of list B into dictionary values of A.

Below is the code,

a = [{'a':[1,5]}, {'b' : [6,10]}, {'c' : [11,15]}]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in a:
  for k,j in i.items():
      for m,n in enumerate(b):
          if j[0]<= n<=j[1]:
              j.append(n)

print(a)

[{'a':[1,5,1,2,3,4,5]}, {'b' : [6,10,6,7,8,9,10]}, {'c' :
[11,15,11,12,13,14,15]}]

# tried list comprehension
a= [{k:n} for i in a for k,j in i.items() for m,n in enumerate(b)
if j[0]<= n<=j[1]]

print(a)

[{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}, {'b': 6}, {'b': 7},
{'b': 8}, {'b': 9}, {'b': 10}, {'c': 11}, {'c': 12}, {'c': 13}, {'c':
14}, {'c': 15}]

Question is whether this can be done using list comprehension? I have tried but unable to generate the required output.

Body:
Just a small modification of the @Błotosmętek answer to get exactly what you need as output.

a = [{'a': [1, 5]}, {'b': [6, 10]}, {'c': [11, 15]}]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

a = [{k: v+[x for x in b if v[0]<=x<=v[1]]} for d in a for k, v in d.items()]
print(a)

Output

[{'a': [1, 5, 1, 2, 3, 4, 5]}, {'b': [6, 10, 6, 7, 8, 9, 10]}, {'c': [11, 15, 11, 12, 13, 14, 15]}]


问:
Component can not access ViewChild after injection in page
In a brand new project with ionic 3 and Angular4, I am having a @Component that renders something in a canvas like so:

analyzer-chart.html:

```<code><div>
  <canvas #chartCanvas></canvas>
</div>
</code>```

analyzer-chart.ts:

```<code>@Component({
  selector: 'analyzer-chart',
  templateUrl: 'analyzer-chart.html'
})
export class AnalyzerChartComponent {

  @ViewChild('chartCanvas') chartCanvas;
</code>```

and later

```<code>new Chart(this.chartCanvas.nativeElement
</code>```

This component is used in an @IonicPage (AnalyzerPage) and works very well.

But now I want to call a method from AnalyzerChartComponent in analyzer.ts and therefore want to inject that component in the constructor of the page like so:

```<code>@IonicPage()
@Component({
  selector: 'page-analyzer',
  templateUrl: 'analyzer.html',
  providers: [AnalyzerChartComponent]
})
export class AnalyzerPage {

  pageTitle:string = "loading...";

  constructor(public navCtrl: NavController, public navParams: NavParams,
     public analyzerChart: AnalyzerChartComponent
    ) {
  }
</code>```

And then, by injecting the component into the page, it stops working because the @ViewChild('chartCanvas') chartCanvas is suddenly undefined. Don't know why.

The analyzer.html is simply like

```<code><ion-content padding>

  <h1>{{ pageTitle }}</h1>
  <analyzer-selection-form></analyzer-selection-form>
  <br />
  <analyzer-chart></analyzer-chart>

</ion-content>
</code>```

What is the correct way to call members in the included component?

答:
I was totally wrong. Instead of trying to inject the subcomponent (like I used to do it in like JSF etc.) I should use standard angular data binding like so:

```<code> <analyzer-chart [analyzerResponse]="analyzerResponse"></analyzer-chart>
</code>```

And then set the data in the parent component like so:

```<code>private analyzerResponse:BacktestResult = xxx;
</code>```

And responde to change events in the subcomponent like so:

```<code> @Input()
  analyzerResponse:BacktestResult;

  ngOnChanges() {
    console.log('Hello AnalyzerChartComponent::ngOnChangeData');
    if (this.analyzerResponse && this.chartCanvas) {
      if (this.chart) {
        this.chart.destroy();
      }
      this.setupChart(600);
    }
  }
</code>```

Next time I finish my manual-readings before asking. Thanks anyway to Maximus!

Body:
In a brand new project with ionic 3 and Angular4, I am having a @Component that renders something in a canvas like so:

analyzer-chart.html:

  <canvas #chartCanvas></canvas>

analyzer-chart.ts:

@Component({
  selector: 'analyzer-chart',
  templateUrl: 'analyzer-chart.html'
})
export class AnalyzerChartComponent {

  @ViewChild('chartCanvas') chartCanvas;

and later

new Chart(this.chartCanvas.nativeElement

This component is used in an @IonicPage (AnalyzerPage) and works very well.

But now I want to call a method from AnalyzerChartComponent in analyzer.ts and therefore want to inject that component in the constructor of the page like so:

@IonicPage()
@Component({
  selector: 'page-analyzer',
  templateUrl: 'analyzer.html',
  providers: [AnalyzerChartComponent]
})
export class AnalyzerPage {

  pageTitle:string = "loading...";

  constructor(public navCtrl: NavController, public navParams: NavParams,
     public analyzerChart: AnalyzerChartComponent
    ) {
  }

And then, by injecting the component into the page, it stops working because the @ViewChild('chartCanvas') chartCanvas is suddenly undefined. Don't know why.

The analyzer.html is simply like

<ion-content padding>

{{ pageTitle }}

  <analyzer-selection-form></analyzer-selection-form>

  <analyzer-chart></analyzer-chart>

</ion-content>

What is the correct way to call members in the included component?

Body:
I was totally wrong. Instead of trying to inject the subcomponent (like I used to do it in like JSF etc.) I should use standard angular data binding like so:

 <analyzer-chart [analyzerResponse]="analyzerResponse"></analyzer-chart>

And then set the data in the parent component like so:

private analyzerResponse:BacktestResult = xxx;

And responde to change events in the subcomponent like so:

 @Input()
  analyzerResponse:BacktestResult;

  ngOnChanges() {
    console.log('Hello AnalyzerChartComponent::ngOnChangeData');
    if (this.analyzerResponse && this.chartCanvas) {
      if (this.chart) {
        this.chart.destroy();
      }
      this.setupChart(600);
    }
  }

Next time I finish my manual-readings before asking. Thanks anyway to Maximus!


问:
Push Plugin for ANDROID IONIC 2 not working in prod mode, but works in dev mode
[The very same code working fine in dev mode..getting pushes. but in prod build iam getting the error push plugin not installed.Check the below image]

https://i.stack.imgur.com/wMqIE.png

答: Found the solution.. The problem is that i have called Push.init before platform.ready. Once i enclosed it inside the success callback of platform.ready it is working now.</p>


问:
best way for substring pandas data frame

Q1

I want to extract the Title of each person from the Name attribute of concat data frame. what is the best way of doing this?

```<code>concat['Title'][concat['Title'] == 'Mlle'] = 'Miss'
concat['Title'][concat['Title'] == 'Ms'] = 'Miss'
concat['Title'][concat['Title'] == 'Mme'] = 'Mrs'
concat['Title'][concat['Title'] == 'Dona' or 'Lady'or 'Countess'or'Capt' or 'Col'or'Don'or 'Dr'or 'Major'or 'Rev'or 'Sir'or 'Jonkheer' ] = 'Rare'
</code>```

Q2

when i run the above code i get this error:

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

why?

Refrences

the full problem with datasets : Titanic

答:
What does "extract" mean is not clear.

Does the following help?

```<code>import pandas as pd

df = pd.DataFrame([{'id': 1 , 'title' : 'mrs'},
                  {'id': 2 , 'title' : 'mr'},
                  {'id': 3 , 'title' : 'mr'},
                  {'id': 4 , 'title' : 'mrs'}])

df[df.title == 'mrs']
#   id title
#0   1   mrs
#3   4   mrs

df[((df.title == 'mrs') | (df.title == 'mr'))]
#   id title
#0   1   mrs
#1   2    mr
#2   3    mr
#3   4   mrs
</code>```

Body:
Q1

I want to extract the Title of each person from the Name attribute of concat data frame. what is the best way of doing this?

concat['Title'][concat['Title'] == 'Mlle'] = 'Miss'
concat['Title'][concat['Title'] == 'Ms'] = 'Miss'
concat['Title'][concat['Title'] == 'Mme'] = 'Mrs'
concat['Title'][concat['Title'] == 'Dona' or 'Lady'or 'Countess'or'Capt' or 'Col'or'Don'or 'Dr'or 'Major'or 'Rev'or 'Sir'or 'Jonkheer' ] = 'Rare'

Q2

when i run the above code i get this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

why?

Refrences

the full problem with datasets : Titanic

Body:
What does "extract" mean is not clear.

Does the following help?

import pandas as pd

df = pd.DataFrame([{'id': 1 , 'title' : 'mrs'},
                  {'id': 2 , 'title' : 'mr'},
                  {'id': 3 , 'title' : 'mr'},
                  {'id': 4 , 'title' : 'mrs'}])

df[df.title == 'mrs']
#   id title
#0   1   mrs
#3   4   mrs

df[((df.title == 'mrs') | (df.title == 'mr'))]
#   id title
#0   1   mrs
#1   2    mr
#2   3    mr
#3   4   mrs


问:
Pyspark ML - How to save pipeline and RandomForestClassificationModel
I unable to save random forest model generated using ml package of python/spark.

```<code>>>> rf = RandomForestClassifier(labelCol="label", featuresCol="features")
>>> pipeline = Pipeline(stages=early_stages + [rf])
>>> model = pipeline.fit(trainingData)
>>> model.save("fittedpipeline")
</code>```

Traceback (most recent call last):   File "", line 1, in
   AttributeError: 'PipelineModel' object has no attribute
  'save'

```<code>>>> rfModel = model.stages[8]
>>> print(rfModel)
</code>```

RandomForestClassificationModel (uid=rfc_46c07f6d7ac8) with 20 trees

```<code>>> rfModel.save("rfmodel")
</code>```

Traceback (most recent call last):   File "", line 1, in
   AttributeError: 'RandomForestClassificationModel' object has
  no attribute 'save'**

Also tried by pass 'sc' as first parameter to save method.

答:
The main issue with your code is that you are using a version of Apache Spark prior to 2.0.0. Thus, save isn't available yet for the Pipeline API.

Here is a full example compounded from the official documentation. Let's create our pipeline first:

from pyspark.ml import Pipeline
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer

# Load and parse the data file, converting it to a DataFrame.
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

# Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
label_indexer = StringIndexer(inputCol="label", outputCol="indexedLabel")
labels = label_indexer.fit(data).labels

# Automatically identify categorical features, and index them.
# Set maxCategories so features with > 4 distinct values are treated as continuous.
feature_indexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4)

early_stages = [label_indexer, feature_indexer]

# Split the data into training and test sets (30% held out for testing)
(train, test) = data.randomSplit([0.7, 0.3])

# Train a RandomForest model.
rf = RandomForestClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures", numTrees=10)

# Convert indexed labels back to original labels.
label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=labels)

# Chain indexers and forest in a Pipeline
pipeline = Pipeline(stages=early_stages + [rf, label_converter])

# Train model. This also runs the indexers.
model = pipeline.fit(train)
```

<p>You can now save your pipeline:</p>

<pre class="lang-py prettyprint-override"><code>>>> model.save("/tmp/rf")
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
</code>```

You can also save the RF model :

>>> rf_model = model.stages[2]
>>> print(rf_model)
RandomForestClassificationModel (uid=rfc_b368678f4122) with 10 trees
>>> rf_model.save("/tmp/rf_2")
```

Body:
I unable to save random forest model generated using ml package of python/spark.

>>> rf = RandomForestClassifier(labelCol="label", featuresCol="features")
>>> pipeline = Pipeline(stages=early_stages + [rf])
>>> model = pipeline.fit(trainingData)
>>> model.save("fittedpipeline")

Traceback (most recent call last):   File "", line 1, in
   AttributeError: 'PipelineModel' object has no attribute
  'save'

>>> rfModel = model.stages[8]
>>> print(rfModel)

RandomForestClassificationModel (uid=rfc_46c07f6d7ac8) with 20 trees

>> rfModel.save("rfmodel")

Traceback (most recent call last):   File "", line 1, in
   AttributeError: 'RandomForestClassificationModel' object has
  no attribute 'save'**

Also tried by pass 'sc' as first parameter to save method.

Body:
The main issue with your code is that you are using a version of Apache Spark prior to 2.0.0. Thus, save isn't available yet for the Pipeline API.

Here is a full example compounded from the official documentation. Let's create our pipeline first:

from pyspark.ml import Pipeline
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer

# Load and parse the data file, converting it to a DataFrame.
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

# Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
label_indexer = StringIndexer(inputCol="label", outputCol="indexedLabel")
labels = label_indexer.fit(data).labels

# Automatically identify categorical features, and index them.
# Set maxCategories so features with > 4 distinct values are treated as continuous.
feature_indexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4)

early_stages = [label_indexer, feature_indexer]

# Split the data into training and test sets (30% held out for testing)
(train, test) = data.randomSplit([0.7, 0.3])

# Train a RandomForest model.
rf = RandomForestClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures", numTrees=10)

# Convert indexed labels back to original labels.
label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=labels)

# Chain indexers and forest in a Pipeline
pipeline = Pipeline(stages=early_stages + [rf, label_converter])

# Train model. This also runs the indexers.
model = pipeline.fit(train)

You can now save your pipeline:

>>> model.save("/tmp/rf")
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

You can also save the RF model :

>>> rf_model = model.stages[2]
>>> print(rf_model)
RandomForestClassificationModel (uid=rfc_b368678f4122) with 10 trees
>>> rf_model.save("/tmp/rf_2")


问:
Debug static file requests from IIS6
How can I debug what is being returned by IIS(6) when the response goes through proxies before getting to the browser?

I have requests for static files which are being sent with the 'Accept-encoding: gzip' header. These are being gzipped correctly.  However, if a 'Via: ' header (to redirect the response via a proxy) is also included the content is not received gzipped by the browser.

I want to know if the issue is with IIS not applying the compression or related to something the proxy is doing.

How can I investigate this problem?

This is related to IIS6 not doing gzip compression when including Via header in request.

答:
If your still interested my answer would be install Fiddler probably on the client first.  For HTML snooping you can't do much better.

That would be my first port of call.

Title: Debug static file requests from IIS6