问:
create custom list view in android
i want to set custom layout for list view in android studio

i add a list view in activity_main.xml file

```<code><ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</code>```

and create a layout file with name row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/icon"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium"
            android:id="@+id/text1"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="small"
            android:id="@+id/text2"/>
    </LinearLayout>

</LinearLayout>
</code>```

and MainActivity.java file include :

public class MainActivity extends AppCompatActivity {

```<code>ListView list;
String [] titles;
String [] description;
int[]imgs = {R.drawable.fb,R.drawable.chat,R.drawable.gplus,R.drawable.instagram};

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

    Resources res = getResources();

    titles = res.getStringArray(R.array.titles);
    description = res.getStringArray(R.array.description);

    list = (ListView) findViewById(R.id.list);
    MyAdapter adapter = new MyAdapter(this,titles,imgs,description);
    list.setAdapter(adapter);

}
class MyAdapter extends ArrayAdapter{
    Context context;
    int[] imgs;
    String[] myTitles;
    String[] myDescription;

    MyAdapter (Context c , String[] titles , int[] imgs , String[]Description){
        super(c,R.layout.row,R.id.text1,titles);
        this.context = c;
        this.imgs = imgs;
        this.myDescription = description;
        this.myTitles = titles;
    }
    @Override
    public View getView(int position , View convertView , ViewGroup parent){
        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = layoutInflater.inflate(R.layout.row,null,true);
        ImageView images = (ImageView) findViewById(R.id.icon);
        TextView myTitle = (TextView) findViewById(R.id.text1);
        TextView myDescription = (TextView) findViewById(R.id.text2);
        images.setImageResource(imgs[position]);
        myTitle.setText(titles[position]);
        myDescription.setText(description[position]);
        return row;
    }
}
</code>```

}

when i run the application , display : Unfortunately , application has stopped.

how  to resolve this problem ?

error log :

```<code>AndroidRuntime: FATAL EXCEPTION: main
                                                                               java.lang.NullPointerException
                                                                                at com.example.nik.myapplication.MainActivity$MyAdapter.getView(MainActivity.java:57)
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2207)
                                                                                at android.widget.ListView.makeAndAddView(ListView.java:1845)
                                                                                at android.widget.ListView.fillDown(ListView.java:678)
                                                                                at android.widget.ListView.fillFromTop(ListView.java:739)
                                                                                at android.widget.ListView.layoutChildren(ListView.java:1661)
                                                                                at android.widget.AbsListView.onLayout(AbsListView.java:2037)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:985)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:435)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
                                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
                                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2183)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1947)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4879)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:579)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:548)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
                                                                                at android.os.Handler.handleCallback(Handler.java:725)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:153)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5341)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Here's your answer:

```<code>@Override
public View getView(int position , View convertView , ViewGroup parent){
    LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = layoutInflater.inflate(R.layout.row,null,true);
    ImageView images = (ImageView) row.findViewById(R.id.icon);
    TextView myTitle = (TextView) row.findViewById(R.id.text1);
    TextView myDescription = (TextView) row.findViewById(R.id.text2);
    images.setImageResource(imgs[position]);
    myTitle.setText(titles[position]);
    myDescription.setText(description[position]);
    return row;
}
</code>```

And here is why that's your answer:

You were having a null pointer exception because you were calling findViewById on your activity rather than on the view you had just inflated. Because the activity does not have fields with the IDs icon, text1 or text2 you're not getting any results back. When you try to set them it throws the exception.

Hope that helps!

Title: create custom list view in android

Body:
i want to set custom layout for list view in android studio

i add a list view in activity_main.xml file

<ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

and create a layout file with name row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/icon"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium"
            android:id="@+id/text1"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="small"
            android:id="@+id/text2"/>
    </LinearLayout>

</LinearLayout>

and MainActivity.java file include :

public class MainActivity extends AppCompatActivity {

ListView list;
String [] titles;
String [] description;
int[]imgs = {R.drawable.fb,R.drawable.chat,R.drawable.gplus,R.drawable.instagram};

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

    Resources res = getResources();

    titles = res.getStringArray(R.array.titles);
    description = res.getStringArray(R.array.description);

    list = (ListView) findViewById(R.id.list);
    MyAdapter adapter = new MyAdapter(this,titles,imgs,description);
    list.setAdapter(adapter);

}
class MyAdapter extends ArrayAdapter{
    Context context;
    int[] imgs;
    String[] myTitles;
    String[] myDescription;

    MyAdapter (Context c , String[] titles , int[] imgs , String[]Description){
        super(c,R.layout.row,R.id.text1,titles);
        this.context = c;
        this.imgs = imgs;
        this.myDescription = description;
        this.myTitles = titles;
    }
    @Override
    public View getView(int position , View convertView , ViewGroup parent){
        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = layoutInflater.inflate(R.layout.row,null,true);
        ImageView images = (ImageView) findViewById(R.id.icon);
        TextView myTitle = (TextView) findViewById(R.id.text1);
        TextView myDescription = (TextView) findViewById(R.id.text2);
        images.setImageResource(imgs[position]);
        myTitle.setText(titles[position]);
        myDescription.setText(description[position]);
        return row;
    }
}

}

when i run the application , display : Unfortunately , application has stopped.

how  to resolve this problem ?

error log :

AndroidRuntime: FATAL EXCEPTION: main
                                                                               java.lang.NullPointerException
                                                                                at com.example.nik.myapplication.MainActivity$MyAdapter.getView(MainActivity.java:57)
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2207)
                                                                                at android.widget.ListView.makeAndAddView(ListView.java:1845)
                                                                                at android.widget.ListView.fillDown(ListView.java:678)
                                                                                at android.widget.ListView.fillFromTop(ListView.java:739)
                                                                                at android.widget.ListView.layoutChildren(ListView.java:1661)
                                                                                at android.widget.AbsListView.onLayout(AbsListView.java:2037)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:985)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:435)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
                                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
                                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                                at android.view.View.layout(View.java:14118)
                                                                                at android.view.ViewGroup.layout(ViewGroup.java:4474)
                                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2183)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1947)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4879)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:579)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:548)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
                                                                                at android.os.Handler.handleCallback(Handler.java:725)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:153)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5341)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Body:
Here's your answer:

@Override
public View getView(int position , View convertView , ViewGroup parent){
    LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = layoutInflater.inflate(R.layout.row,null,true);
    ImageView images = (ImageView) row.findViewById(R.id.icon);
    TextView myTitle = (TextView) row.findViewById(R.id.text1);
    TextView myDescription = (TextView) row.findViewById(R.id.text2);
    images.setImageResource(imgs[position]);
    myTitle.setText(titles[position]);
    myDescription.setText(description[position]);
    return row;
}

And here is why that's your answer:

You were having a null pointer exception because you were calling findViewById on your activity rather than on the view you had just inflated. Because the activity does not have fields with the IDs icon, text1 or text2 you're not getting any results back. When you try to set them it throws the exception.

Hope that helps!


来源: stackexchange

问:
Swift function unclear in TMDB wrapper API
I'm making a application in Swift that makes use of a API from the TMDB. I found a wrapper for this. Installed it with Cocoapods and now I'm wrestling with the functions. I think the readme file is outdated. So with this function I want to retrieve a list of genres.

For example a function in the framework:

```<code>    ///Get the list of tv or movie genres.
  open class func genres(_ api_key: String!, listType: GenresListType, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [GenresMDB]?) -> ()) -> (){
    Client.Genres(api_key, listType: listType.rawValue, language: language, genreId: 0, page: nil, include_all_movies: nil, include_adult: nil, movieList: false){
      apiReturn in
      if(apiReturn.error == nil){
        completion(apiReturn, GenresMDB.initialize(json: apiReturn.json!["genres"]))
      }else{
        completion(apiReturn, nil)
      }
    }
  }
</code>```

In the Readme the function is called like this(get the list of movie OR tv genre):

```<code>GenresMDB.genres(apikey, listType: .tv, language: "en"){
  apiReturn, genres in
  if let genres = genres{
    genres.forEach{
      print($0.name)
    }
  }
}
</code>```

But I think its outdated.

So now I call the function in a viewController.swift like this:

```<code>    GenresMDB.genres(apiKey, listType: .movie, language: "en", completion: (ClientReturn, [GenresMDB]?) -> ()) {
}
</code>```

I want a list of genres for movies with language english. But I I stil don't understand what the completion handler will do. Or how I save the data returned by the function(I think in JSON format). Is there someone who understands this function and an explain it to me?

答:
nothing much has changed since the wiki was last updated. Below is an example of how to achieve what you want.

```<code>GenresMDB.genres(key, listType: .movie, language: "en", completion: {
    error, genresData in
    //Do something with genres returned
    print(genresData[0].name)
})
</code>```

Also you can check out the documentation on using closures / completion handlers in swift

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

ContentLicense: CC BY-SA 3.0

Body:
I'm making a application in Swift that makes use of a API from the TMDB. I found a wrapper for this. Installed it with Cocoapods and now I'm wrestling with the functions. I think the readme file is outdated. So with this function I want to retrieve a list of genres.

For example a function in the framework:

    ///Get the list of tv or movie genres.
  open class func genres(_ api_key: String!, listType: GenresListType, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: [GenresMDB]?) -> ()) -> (){
    Client.Genres(api_key, listType: listType.rawValue, language: language, genreId: 0, page: nil, include_all_movies: nil, include_adult: nil, movieList: false){
      apiReturn in
      if(apiReturn.error == nil){
        completion(apiReturn, GenresMDB.initialize(json: apiReturn.json!["genres"]))
      }else{
        completion(apiReturn, nil)
      }
    }
  }

In the Readme the function is called like this(get the list of movie OR tv genre):

GenresMDB.genres(apikey, listType: .tv, language: "en"){
  apiReturn, genres in
  if let genres = genres{
    genres.forEach{
      print($0.name)
    }
  }
}

But I think its outdated.

So now I call the function in a viewController.swift like this:

    GenresMDB.genres(apiKey, listType: .movie, language: "en", completion: (ClientReturn, [GenresMDB]?) -> ()) {
}

I want a list of genres for movies with language english. But I I stil don't understand what the completion handler will do. Or how I save the data returned by the function(I think in JSON format). Is there someone who understands this function and an explain it to me?

Body:
nothing much has changed since the wiki was last updated. Below is an example of how to achieve what you want.

GenresMDB.genres(key, listType: .movie, language: "en", completion: {
    error, genresData in
    //Do something with genres returned
    print(genresData[0].name)
})

Also you can check out the documentation on using closures / completion handlers in swift

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html


问:
Using Jquery to find two input values for 1 checkbox selection?
I need to retrieve two values, "price and weight" , from 1 checkbox. I am using Jquery Mobile CSS for this.

I simplified the code down and wrote out as much as I could. I don't know how to approach this.

I need the outputs in two separate divs after the box is clicked. I am going to use the results to pass to to simplecartJS.

MY CODE

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="simpleCart.js"></script>
</head>
<body>
<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
        <div style="flex:2;">2.0 grams</div>
        <div style="flex:1;text-align: center;">$22.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
    <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
        <div style="flex:2;">3.5 grams</div>
        <div style="flex:1;text-align: center;">$45.00</div>
    </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
        <div style="flex:2;">7.0 grams</div>
        <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

    <script>
     var price_results;
     var weight_results;

        $("????").click(function(){
        ????
});

        $(".price_results").html( price_results );
        $(".weight_results").html( weight_results );
    </script>

<div class="simpleCart_shelfItem">

    <div class="item_price"> <!-- simplecart div -->
        <div class="price_results"></div> <!-- price function result? -->
    </div>

     <div class="item_weight"> <!-- simplecart div -->
        <div class="weight_results"></div>   <!-- weight function result? -->
    </div>

</div>

</body>
</html>
</code>```

copy and paste.

Here is my page
www.aarontomlinson.com

Thanks!!!

答:
try this,, that should work for you,,

$('input[type=radio]').on( 'change', function(el){
  $( '.price_results' ).text( $(this).parent().prev().val() );
  $( '.weight_results' ).text( $(this).val() );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
        <div style="flex:2;">2.0 grams</div>
        <div style="flex:1;text-align: center;">$22.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
    <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
        <div style="flex:2;">3.5 grams</div>
        <div style="flex:1;text-align: center;">$45.00</div>
    </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
        <div style="flex:2;">7.0 grams</div>
        <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

<div class="simpleCart_shelfItem">

    <div class="item_price"> <!-- simplecart div -->
        <div class="price_results"></div> <!-- price function result? -->
    </div>

     <div class="item_weight"> <!-- simplecart div -->
        <div class="weight_results"></div>   <!-- weight function result? -->
    </div>

</div></code>```

Body:
I need to retrieve two values, "price and weight" , from 1 checkbox. I am using Jquery Mobile CSS for this.

I simplified the code down and wrote out as much as I could. I don't know how to approach this.

I need the outputs in two separate divs after the box is clicked. I am going to use the results to pass to to simplecartJS.

MY CODE

<!doctype html>

<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">

2.0 grams

$22.00

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">

3.5 grams

$45.00

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">

7.0 grams

$90.00

</fieldset>

copy and paste.

Here is my page
www.aarontomlinson.com

Thanks!!!

Body:
try this,, that should work for you,,

$('input[type=radio]').on( 'change', function(el){
  $( '.price_results' ).text( $(this).parent().prev().val() );
  $( '.weight_results' ).text( $(this).val() );
});

<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
        <div style="flex:2;">2.0 grams</div>
        <div style="flex:1;text-align: center;">$22.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
    <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
        <div style="flex:2;">3.5 grams</div>
        <div style="flex:1;text-align: center;">$45.00</div>
    </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
        <div style="flex:2;">7.0 grams</div>
        <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

<div class="simpleCart_shelfItem">

    <div class="item_price"> <!-- simplecart div -->
        <div class="price_results"></div> <!-- price function result? -->
    </div>

     <div class="item_weight"> <!-- simplecart div -->
        <div class="weight_results"></div>   <!-- weight function result? -->
    </div>

</div>


问:
Imagick delegates installation on WAMP
I would like to know how to download the correct Imagemagick decode delegates from http://www.imagemagick.org/download/delegates/, as well what to do with them afterwards.

I'm using:

Imagick 3.4.3RC1, 6.9.3-7 Q16 x64 2016-03-27

PHP 5.6.25

WAMP 3.0.0.25 on Windows 7

I've been looking on Imagick and Stackoverflow threads, but the ones I found were mostly concerning errors with the delegates after they had them, and none of them used WAMP. Any help would be appreciated

答:
In the past this has worked by installing ImageMagick and then downloading a compatible imagick PHP extension.

But currently there seems to be a temporary "Catch 22" situation with ImageMagick and imagick.

imagick versions need to be compiled against a specific version of ImageMagick and currently that has not been done for imagick against the new ImageMagick 7 although I am informed by @danack that imagick is ready to be compiled but nobody has done so yet, or at least they have not shared the binary.

Unfortunately ImageMagick do not retain older versions of their install i.e. ImageMagick 6.? so if you dont already have a version of the installer the only availaible one is ImageMagick 7

The Catch 22

Therefore the only versions of imagick available will only work with ImageMagick 6 and you cannot download ImageMagick 6 as the ImageMagick people do not retain old version of their installer.

The work around

However, if you only want ImageMagick to work within a PHP/Apache environment this proceedure works.

The versions of the following must match your WAMPServer, so if you installed WAMPServer 32bit use the 32bit versions of ImageMagick and Imagick, if you use WAMPServer 64bit, use the 64bit versions of ImageMagick and Imagick.
The VC14 versions should work with WAMPServers Apache 2.4.x versions

Download ImageMagick-6.9.3-7-vc14-x86.zip (32bit)
or       ImageMagick-6.9.3-7-vc14-x64.zip (64bit)
from http://windows.php.net/downloads/pecl/deps/ depending upon which WAMPServer version you are using i.e. 32bit or 64bit

Download php_imagick-3.4.3-5.6-ts-vc11-x86.zip (32bit)
or       php_imagick-3.4.3-5.6-ts-vc11-x64.zip (64bit)
from http://windows.php.net/downloads/pecl/releases/imagick/3.4.3/ depending upon which WAMPServer version you are using i.e. 32bit or 64bit

Create a folder to hold ImageMagick, I used wamp\imagemagick

Unzip whichever of the ImageMagick's you downloaded i.e.
ImageMagick-6.9.3-7-vc14-x86.zip or ImageMagick-6.9.3-7-vc14-x64.zip into the wamp\imagemagick folder

Unzip whichever of the imagick version you downloaded php_imagick-3.4.3-5.6-ts-vc11-x86.zip (32bit) or php_imagick-3.4.3-5.6-ts-vc11-x64.zip (64bit) into a temp folder and copy the php_imagick.dll from the temp folder to your wamp\bin\php\php5.6.25\ext folder

Edit your 'php.inifile to add the extension. Use the wampmanager menus so you edit the correct file
(left click) wampmanager->PHP->php.ini
Add the lineextension=php_imagick.dllinto the section ofphp.inithat contains the otherextension` parameters.

Add the folder to your windows PATH using
Control Panel -> System -> Advanced System Setting
    Select the Advanced Tab
    Click the Environment Variables Button
    Add C:\wamp\imagick; to the PATH variable in the System Variables section
[I dont like adding anything to the PATH for WAMPServer, but I cannot think of a better solution for now and as this way will work for multiple versions of PHP it is not actually so bad]

Start WAMPServer, or restart Apache. It may be necessary to reboot windows, it was for me, but maybe that was because I tried a number of things before I got to this solution.

Check with phpinfo() you should see

Title: Imagick delegates installation on WAMP


问:
Expose database auto-incrementing ids via APIs or web pages
I was of the opinion that NOT exposing auto-incrementing DB ids (accounts, products etc.) was the better way. We could maybe use UUIDs & expose those via the APIs or web pages.

But I checked that many major companies don't seem to care:

Google, Amazon, Facebook, Twitter (all seem to have numeric
auto-incrementing account ids)

Macys & Ebay show product ids(or web ids) which are auto-incrementing
ids

One case where Amazon does seem to care:

Amazon does use ASIN numbers for its product catalog (which
supposedly internally link to their numeric auto-incrementing DB
product ids.)

So, in using UUIDs are we trying to solve a problem that does not exist ? Just not worth the time & effort ?

答:
Concerning the use of auto-incrementing ids for account table, here are some reasons why its a bad idea:

Sequence numbers expose to the public the number of records in a table and growth rate of the table if sampled over a period of time.

If the api has poor security, one could scrape all the records in the database by simply incrementing the id and making api calls until all the data is retrieved.

when using auto-incrementing ids and inserting multiple related entities, you need to make multiple calls to the database in order to insert the entities in the database. If using UUIDs, you can construct the whole set of objects without need to interact with the database. For instance with an order header and order line items, you need to insert the order header, get the primary id, and then insert the order line items with the order header id.

When migrating data from dev to staging or staging to live, inserting new data can be challenging if using auto-increment id's and foreign keys, etc.


问:
Search tables from SQL and show their data on page
I've been trying to find an easy way for this. A search (dropdown menu) of all tables in mysql, and show their content when I click the table I want to show on the page. Instead of showing just every table on the page I thought it can be easier? Any help would be appreciated!
 My code so far:

```<code><?php
$host    = "localhost";
$user    = "heijsdb_user";
$pass    = "maus";
$db_name = "heijsdb";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
echo "borsten HFP controle";
$result = mysqli_query($connection,"SELECT * FROM borstenHFPcontrole");
$all_property = array();  //declare an array for saving property

//showing property
echo '<table class="data-table w3-table-all" border="2px">
        <tr class="data-heading">';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '<td>' . $property->name . '</td>';  //get field name for header
    array_push($all_property, $property->name);  //save those to array
}
echo '</tr>'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    foreach ($all_property as $item) {
        echo '<td>' . $row[$item] . '</td>'; //get items using property value
    }
    echo '</tr>';
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////
</code>```

答:
This is pretty much the idea, you can play from here and adapt it to your solution. Sorry I used my way, I prefer PHP template style when embedding in HTML. ;)

```<code>$host    = "localhost";
$user    = "heijsdb_user";
$pass    = "maus";
$db_name = "heijsdb";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}

//check if the form was submitted
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);

?>
<html>
<head>
    <title>showing table content on user action</title>
</head>
<body>
    <div>

        <form id="form-menu" method="post">
            <label for="select-menu">Choose a table</label>
            <select id="select-menu" name="table">
                <option></option>
                <?php
                $result = mysqli_query($connection,"SELECT table_name FROM information_schema.tables where table_schema='test'"); // <-- the table_schema field here is your database name, change 'test' for yours
                while ($row = mysqli_fetch_array($result)) : $selected = $row['table_name'] == $table ? 'selected' : ''; ?>
                    <option value="<?php echo $row['table_name'] ; ?>" <?php echo $selected; ?>><?php echo $row['table_name'] ; ?></option>
                <?php endwhile; ?>
            </select>
        </form>

        <hr>

        <div>
            <?php if (empty($table)) : ?>
                <h3>Please select a table to show its content</h3>
            <?php else : ?>
                <h3>Content for the table `<?php echo $table; ?>`</h3>
                <?php
                $result = mysqli_query($connection,"SELECT * FROM `{$table}`");
                $all_property = [];  //declare an array for saving property
                ?>
                <!-- showing property -->
                <table class="data-table w3-table-all" border="2px">
                    <tr class="data-heading"> <!-- initialize table tag -->
                        <?php while ($property = mysqli_fetch_field($result)) : ?>
                        <td><?php echo $property->name; ?></td> <!-- get field name for header -->
                        <?php $all_property[] = $property->name; //save those to array ?>
                        <?php endwhile; ?>
                    </tr> <!-- end tr tag -->

                    <!-- showing all data -->
                    <?php while ($row = mysqli_fetch_array($result)) : ?>
                    <tr>
                        <?php foreach ($all_property as $item) : ?>
                            <td><?php echo $row[$item]; ?></td> <!-- get items using property value -->
                        <?php endforeach; ?>
                    </tr>
                    <?php endwhile; ?>
                </table>
            <?php endif; ?>
        </div>

    </div>

    <script>
        document.getElementById('select-menu').addEventListener('change', function() {
            document.getElementById('form-menu').submit();
        });
    </script>
</body>
</html>
</code>```

Handy links:

- Get table names using SELECT statement in MySQL

- Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

Hope this helps :)

Body:
I've been trying to find an easy way for this. A search (dropdown menu) of all tables in mysql, and show their content when I click the table I want to show on the page. Instead of showing just every table on the page I thought it can be easier? Any help would be appreciated!
 My code so far:

<?php
$host    = "localhost";
$user    = "heijsdb_user";
$pass    = "maus";
$db_name = "heijsdb";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
echo "borsten HFP controle";
$result = mysqli_query($connection,"SELECT * FROM borstenHFPcontrole");
$all_property = array();  //declare an array for saving property

//showing property
echo '

';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '' . $property->name . '	';  //get field name for header
    array_push($all_property, $property->name);  //save those to array
}
echo '
'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "
";
    foreach ($all_property as $item) {
        echo '' . $row[$item] . '	'; //get items using property value
    }
    echo '
';
}
echo "
";
////////////////////////////////////////////////////////////////////////////////////////////////////////////

Body:
This is pretty much the idea, you can play from here and adapt it to your solution. Sorry I used my way, I prefer PHP template style when embedding in HTML. ;)

$host    = "localhost";
$user    = "heijsdb_user";
$pass    = "maus";
$db_name = "heijsdb";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}

//check if the form was submitted
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);

?>
<html>
<head>
    <title>showing table content on user action</title>
</head>
<body>
    <div>

        <form id="form-menu" method="post">
            <label for="select-menu">Choose a table</label>
            <select id="select-menu" name="table">
                <option></option>
                <?php
                $result = mysqli_query($connection,"SELECT table_name FROM information_schema.tables where table_schema='test'"); // <-- the table_schema field here is your database name, change 'test' for yours
                while ($row = mysqli_fetch_array($result)) : $selected = $row['table_name'] == $table ? 'selected' : ''; ?>
                    <option value="<?php echo $row['table_name'] ; ?>" <?php echo $selected; ?>><?php echo $row['table_name'] ; ?></option>
                <?php endwhile; ?>
            </select>
        </form>

        <hr>

        <div>
            <?php if (empty($table)) : ?>
                <h3>Please select a table to show its content</h3>
            <?php else : ?>
                <h3>Content for the table `<?php echo $table; ?>`</h3>
                <?php
                $result = mysqli_query($connection,"SELECT * FROM `{$table}`");
                $all_property = [];  //declare an array for saving property
                ?>
                <!-- showing property -->
                <table class="data-table w3-table-all" border="2px">
                    <tr class="data-heading"> <!-- initialize table tag -->
                        <?php while ($property = mysqli_fetch_field($result)) : ?>
                        <td><?php echo $property->name; ?></td> <!-- get field name for header -->
                        <?php $all_property[] = $property->name; //save those to array ?>
                        <?php endwhile; ?>
                    </tr> <!-- end tr tag -->

                    <!-- showing all data -->
                    <?php while ($row = mysqli_fetch_array($result)) : ?>
                    <tr>
                        <?php foreach ($all_property as $item) : ?>
                            <td><?php echo $row[$item]; ?></td> <!-- get items using property value -->
                        <?php endforeach; ?>
                    </tr>
                    <?php endwhile; ?>
                </table>
            <?php endif; ?>
        </div>

    </div>

    <script>
        document.getElementById('select-menu').addEventListener('change', function() {
            document.getElementById('form-menu').submit();
        });
    </script>
</body>
</html>

Handy links:

- Get table names using SELECT statement in MySQL

- Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

Hope this helps :)


问:
Syntax for using multi-argument init for a swift class in Objective-C
I am a new iOS developer and am having a small problem initializing a Swift class in a separate objective C file within my project.  I have already configured the project properly and imported the class as per answers to this question:

Can't use Swift classes inside Objective-C

My question is this: what would be the syntax to call the init method of this swift class in objective-C?

```<code>@objc class Book: NSObject{
    private var title: String
    private var author: String
    private var detail: String
    private var buyLink: String
    private var rank: integer_t
    private var lastRank: integer_t?

    public init(newTitle: String,newAuthor: String, newDetail: String, newBuyLink: String, newRank: integer_t, newLastRank: integer_t?){
        self.title = newTitle
        self.author = newAuthor
        self.detail = newDetail
        self.buyLink = newBuyLink
        self.rank = newRank
        self.lastRank = newLastRank
    }

    func getBasicInfo() -> (title: String, author: String) {
        return (title, author)
    }

    func getDetailInfo() -> (detail: String, buyLink: String, rank: integer_t, lastRank: integer_t?) {
        return (detail, buyLink, rank, lastRank)
    }
}
</code>```

I have tried writing it like so:

```<code>NSString *title = [NSString stringWithFormat:@"%@", book[@"title"]];
NSString *author = [NSString stringWithFormat:@"%@", book[@"author"]];
NSString *detail = [NSString stringWithFormat:@"%@", book[@"description"]];
NSString *buyLink = [NSString stringWithFormat:@"%@", book[@"amazon_product_url"]];
int rank = [book[@"rank"] intValue];
int lastRank = [book[@"rank_last_week"] intValue];

Book *bookFromList = [[Book alloc] initWithNewTitle: title newAuthor: author
    newDetail: detail newBuyLink: buyLink newRank: rank newLastRank: lastRank];
</code>```

where book is a NSDictionary

but there is an error "No visible @interface for 'Book' declares the selector 'initWithNewTitle:newAuthor:NewDetail:.....'

答:
All the parameters need to be compatible with Objective-C. You have to use all @objc classes, and only data types that are supported by Objective-C. Tuples and Swift Structs, for example, are not valid types in Objective-C.

I don't think Optionals are supported. You're init method takes an optional. I'm pretty sure that's your problem.

Body:
I am a new iOS developer and am having a small problem initializing a Swift class in a separate objective C file within my project.  I have already configured the project properly and imported the class as per answers to this question:

Can't use Swift classes inside Objective-C

My question is this: what would be the syntax to call the init method of this swift class in objective-C?

@objc class Book: NSObject{
    private var title: String
    private var author: String
    private var detail: String
    private var buyLink: String
    private var rank: integer_t
    private var lastRank: integer_t?

    public init(newTitle: String,newAuthor: String, newDetail: String, newBuyLink: String, newRank: integer_t, newLastRank: integer_t?){
        self.title = newTitle
        self.author = newAuthor
        self.detail = newDetail
        self.buyLink = newBuyLink
        self.rank = newRank
        self.lastRank = newLastRank
    }

    func getBasicInfo() -> (title: String, author: String) {
        return (title, author)
    }

    func getDetailInfo() -> (detail: String, buyLink: String, rank: integer_t, lastRank: integer_t?) {
        return (detail, buyLink, rank, lastRank)
    }
}

I have tried writing it like so:

NSString *title = [NSString stringWithFormat:@"%@", book[@"title"]];
NSString *author = [NSString stringWithFormat:@"%@", book[@"author"]];
NSString *detail = [NSString stringWithFormat:@"%@", book[@"description"]];
NSString *buyLink = [NSString stringWithFormat:@"%@", book[@"amazon_product_url"]];
int rank = [book[@"rank"] intValue];
int lastRank = [book[@"rank_last_week"] intValue];

Book *bookFromList = [[Book alloc] initWithNewTitle: title newAuthor: author
    newDetail: detail newBuyLink: buyLink newRank: rank newLastRank: lastRank];

where book is a NSDictionary

but there is an error "No visible @interface for 'Book' declares the selector 'initWithNewTitle:newAuthor:NewDetail:.....'


问:
Changing src value using jQuery not working
I'm trying to use jQuery to change out images within a small application.  I'm using anchor tags with click event.  Every time a anchor tag if clicked it updates a section for the html mark up to update a h1, a p tag, and an image.  Everything works, except for the image isn't being swapped out.

Here is my html for this small project:

```<code><ul class="nav navbar-nav">
    <li><a id="chilledMandy">Chilled Mandy</a></li>
    <li><a id="cuteMandy">Cute Mandy</a></li>
</ul>
</code>```

This is the area where everything gets updated.

```<code><div class="row">
        <div class="col-md-10 col-md-offset-1">

            <div class="panel panel-danger">
                <div class="panel-heading">
                    <h1 id="title">The Many Different Profiles of Mandy Mangum</h1>
                </div>
                    <div id="profile">
                        <h1 id="profile-title">This is the title area.</h1>
                        <img id="profile-image" src="images/chilledmandy.png">
                        <p id="profile-paragraph">This is the bio area<p>
                    </div><!-- end #profile -->
                </div><!-- end .panel-heading -->
            </div><!-- end .panel -->
    </div><!-- end .col-md-10 -->
  </div> <!-- end row -->
</code>```

And this is my JQuery script

```<code>    $(document).ready(function() {
        $('#chilledMandy').click(function() {
            var title = 'Chilled Mandy';
            var paragraph = "This is a photo of chilled Mandy.  She seems to be enjoying herself outside on her patio while smiling at the camera.";
            var image = '\images/chilledmandy.png';

            var profileTitle = document.getElementById('profile-title');
            var profileParagraph = document.getElementById('profile-paragraph');
            var profileImage = document.getElementById('profile-image');

            profileTitle.innerHTML = title;
            profileParagraph.innerHTML = paragraph;
            profileImage.attr('alt', "We are adding this because we can.");
        });

        $('#cuteMandy').click(function() {
            var title = 'Cute Mandy';
            var paragraph = "This is a photo of cute Mandy.  She seems to be out and about with a few of her friends at a local place here in Austin, Texas.  As usual, when she is with her friends, Mandy seems to be at her happiest.";
            var image = '\images/cutemandy.png';

            var profileTitle = document.getElementById('profile-title');
            var profileParagraph = document.getElementById('profile-paragraph');
            var profileImage = document.getElementById('profile-image');

            profileTitle.innerHTML = title;
            profileParagraph.innerHTML = paragraph;
            profileImage.attr('alt', 'We are going to change this in the next major upgrade.');
        });
    });
</code>```

Any help would be great.

答:
You're never putting image into the src. Also, you have an extra \ in the image string.

You're using a jQuery method to update the DOM element profileImage.

```<code>$(document).ready(function() {
    $('#chilledMandy').click(function() {
        var title = 'Chilled Mandy';
        var paragraph = "This is a photo of chilled Mandy.  She seems to be enjoying herself outside on her patio while smiling at the camera.";
        var image = 'images/chilledmandy.png';

        var profileTitle = document.getElementById('profile-title');
        var profileParagraph = document.getElementById('profile-paragraph');
        var profileImage = document.getElementById('profile-image');

        profileTitle.innerHTML = title;
        profileParagraph.innerHTML = paragraph;
        $(profileImage).attr({
            'alt': "We are adding this because we can.",
            'src': image
        });
    });

    $('#cuteMandy').click(function() {
        var title = 'Cute Mandy';
        var paragraph = "This is a photo of cute Mandy.  She seems to be out and about with a few of her friends at a local place here in Austin, Texas.  As usual, when she is with her friends, Mandy seems to be at her happiest.";
        var image = 'images/cutemandy.png';

        var profileTitle = document.getElementById('profile-title');
        var profileParagraph = document.getElementById('profile-paragraph');
        var profileImage = document.getElementById('profile-image');

        profileTitle.innerHTML = title;
        profileParagraph.innerHTML = paragraph;
        $(profileImage).attr({
            'alt': 'We are going to change this in the next major upgrade.',
            'src': image
        });
    });
});
</code>```

Body:
I'm trying to use jQuery to change out images within a small application.  I'm using anchor tags with click event.  Every time a anchor tag if clicked it updates a section for the html mark up to update a h1, a p tag, and an image.  Everything works, except for the image isn't being swapped out.

Here is my html for this small project:

Chilled Mandy

Cute Mandy

This is the area where everything gets updated.

The Many Different Profiles of Mandy Mangum

This is the title area.

This is the bio area

And this is my JQuery script

    $(document).ready(function() {
        $('#chilledMandy').click(function() {
            var title = 'Chilled Mandy';
            var paragraph = "This is a photo of chilled Mandy.  She seems to be enjoying herself outside on her patio while smiling at the camera.";
            var image = '\images/chilledmandy.png';

            var profileTitle = document.getElementById('profile-title');
            var profileParagraph = document.getElementById('profile-paragraph');
            var profileImage = document.getElementById('profile-image');

            profileTitle.innerHTML = title;
            profileParagraph.innerHTML = paragraph;
            profileImage.attr('alt', "We are adding this because we can.");
        });

        $('#cuteMandy').click(function() {
            var title = 'Cute Mandy';
            var paragraph = "This is a photo of cute Mandy.  She seems to be out and about with a few of her friends at a local place here in Austin, Texas.  As usual, when she is with her friends, Mandy seems to be at her happiest.";
            var image = '\images/cutemandy.png';

            var profileTitle = document.getElementById('profile-title');
            var profileParagraph = document.getElementById('profile-paragraph');
            var profileImage = document.getElementById('profile-image');

            profileTitle.innerHTML = title;
            profileParagraph.innerHTML = paragraph;
            profileImage.attr('alt', 'We are going to change this in the next major upgrade.');
        });
    });

Any help would be great.

Body:
You're never putting image into the src. Also, you have an extra \ in the image string.

You're using a jQuery method to update the DOM element profileImage.

$(document).ready(function() {
    $('#chilledMandy').click(function() {
        var title = 'Chilled Mandy';
        var paragraph = "This is a photo of chilled Mandy.  She seems to be enjoying herself outside on her patio while smiling at the camera.";
        var image = 'images/chilledmandy.png';

        var profileTitle = document.getElementById('profile-title');
        var profileParagraph = document.getElementById('profile-paragraph');
        var profileImage = document.getElementById('profile-image');

        profileTitle.innerHTML = title;
        profileParagraph.innerHTML = paragraph;
        $(profileImage).attr({
            'alt': "We are adding this because we can.",
            'src': image
        });
    });

    $('#cuteMandy').click(function() {
        var title = 'Cute Mandy';
        var paragraph = "This is a photo of cute Mandy.  She seems to be out and about with a few of her friends at a local place here in Austin, Texas.  As usual, when she is with her friends, Mandy seems to be at her happiest.";
        var image = 'images/cutemandy.png';

        var profileTitle = document.getElementById('profile-title');
        var profileParagraph = document.getElementById('profile-paragraph');
        var profileImage = document.getElementById('profile-image');

        profileTitle.innerHTML = title;
        profileParagraph.innerHTML = paragraph;
        $(profileImage).attr({
            'alt': 'We are going to change this in the next major upgrade.',
            'src': image
        });
    });
});


问:
Getting a DrawingContext for a wpf WriteableBitmap
Is there a way to get a DrawingContext (or something similar) for a WriteableBitmap?  I.e. something to allow you to call simple DrawLine/DrawRectangle/etc kinds of methods, rather than manipulate the raw pixels directly.

答:
A different way to solve this problem is to use a RenderTargetBitmap as a backing store, just like in the WriteableBitmap example. Then you can create and issue WPF drawing commands to it whenever you want. For example:

```<code>// create the backing store in a constructor
var backingStore =
      new RenderTargetBitmap(200,200,97,97,PixelFormats.Pbgra32);
myImage.Source = backingStore;

// whenever you want to update the bitmap, do:
var drawingVisual = new DrawingVisual();
var drawingContext = drawingVisual.RenderOpen();
{
    // your drawing commands go here
    drawingContext.DrawRectangle(
            Brushes.Red, new Pen(),
            new Rect(this.RenderSize));
}
Render(drawingContext);
drawingContext.Close();
backingStore.Render(drawingVisual);
</code>```

If you want to redraw this RenderTargetBitmap every frame, you can catch the CompositionTarget.Rendering event, like this:

```<code>CompositionTarget.Rendering += MyRenderingHandler;
</code>```

OwnerDisplayName: Emperor XLII

Body:
A different way to solve this problem is to use a RenderTargetBitmap as a backing store, just like in the WriteableBitmap example. Then you can create and issue WPF drawing commands to it whenever you want. For example:

// create the backing store in a constructor
var backingStore =
      new RenderTargetBitmap(200,200,97,97,PixelFormats.Pbgra32);
myImage.Source = backingStore;

// whenever you want to update the bitmap, do:
var drawingVisual = new DrawingVisual();
var drawingContext = drawingVisual.RenderOpen();
{
    // your drawing commands go here
    drawingContext.DrawRectangle(
            Brushes.Red, new Pen(),
            new Rect(this.RenderSize));
}
Render(drawingContext);
drawingContext.Close();
backingStore.Render(drawingVisual);

If you want to redraw this RenderTargetBitmap every frame, you can catch the CompositionTarget.Rendering event, like this:

CompositionTarget.Rendering += MyRenderingHandler;


问:
Move user uploaded video from local to amazon S3 in rails app
I have a rails app that lets users upload videos. Right now, it works well locally, I want to move it to AWS so that when a user uploads a video, it gets added to my S3 bucket.

Right now, my video uploader.rb looks like this:

```<code>class VideoUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end
</code>```

What do I have to change here so it'll be uploaded to S3?

I have also read a little bit about the FOG gem. From what I understand, it helps you upload videos locally and also on the cloud. Will I have to use it here? Sorry if I'm asking this question the wrong way, I'm new here and also to rails.

Thanks a lot and please let me know if you need any more information.

答:
You will want to use the fog-aws gem.

In your Gemfile add

```<code>gem 'fog-aws'
</code>```

Create an initializer and name it something like carrierwave.rb. You will then put your credentials in here:

```<code>CarrierWave.configure do |config|
  config.fog_provider = 'fog/aws'                          # required
  config.fog_credentials = {
      provider:              'AWS',                        # required
      aws_access_key_id:     ENV['aws_access_key_id'],     # required
      aws_secret_access_key: ENV['aws_secret_access_key'], # required
  }
  config.fog_directory  = ENV['bucket']                    # required
end
</code>```

Use ENV variables to hide your AWS information.

You will also want to change storage :file to storage :fog.

For complete information on file uploads with S3 and Carrierwave check out the documentation.

Due to large video sizes (assuming), I would probably move the upload process into a background job so your web server doesn't time out.

Body:
I have a rails app that lets users upload videos. Right now, it works well locally, I want to move it to AWS so that when a user uploads a video, it gets added to my S3 bucket.

Right now, my video uploader.rb looks like this:

class VideoUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

What do I have to change here so it'll be uploaded to S3?

I have also read a little bit about the FOG gem. From what I understand, it helps you upload videos locally and also on the cloud. Will I have to use it here? Sorry if I'm asking this question the wrong way, I'm new here and also to rails.

Thanks a lot and please let me know if you need any more information.

Body:
You will want to use the fog-aws gem.

In your Gemfile add

gem 'fog-aws'

Create an initializer and name it something like carrierwave.rb. You will then put your credentials in here:

CarrierWave.configure do |config|
  config.fog_provider = 'fog/aws'                          # required
  config.fog_credentials = {
      provider:              'AWS',                        # required
      aws_access_key_id:     ENV['aws_access_key_id'],     # required
      aws_secret_access_key: ENV['aws_secret_access_key'], # required
  }
  config.fog_directory  = ENV['bucket']                    # required
end

Use ENV variables to hide your AWS information.

You will also want to change storage :file to storage :fog.

For complete information on file uploads with S3 and Carrierwave check out the documentation.

Due to large video sizes (assuming), I would probably move the upload process into a background job so your web server doesn't time out.


问:
Facebook api and java
Im playing around with the facebook api and java. Now i created a small application from a tutorial I saw, but when I cant compile it properly because netbeans underlines the lines:

```<code>import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;
</code>```

How do i import these into netbeans to use?

答:
You have to add the facebook-java-api jar to your classpath.

Btw, I'm not sure whether the facebook-java-api project supports the new facebook API, a.k.a "the Graph API". You can take a look at restfb for that.

ContentLicense: CC BY-SA 2.5

Title: Facebook api and java

Body:
Im playing around with the facebook api and java. Now i created a small application from a tutorial I saw, but when I cant compile it properly because netbeans underlines the lines:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;

How do i import these into netbeans to use?


问:
App installation failed due to application-identifier entitlement
I am unable to install a watchOS 2 WatchKit app due to an application-identifier entitlement. This happened after turning on App Groups in the Capabilities tab.

Full error:

App installation failed

This application's application-identifier entitlement does not match that of the installed application. These values must match for an upgrade to be allowed.

This is running the app in debug mode on a physical device. Running just the iOS app works fine.

I have turned App Groups off again and removed the entitlements files that were added, but same error.

答: My problem was the App ID in combination with the certificate used to create the provisioning profiles.  None of my provisioning profiles were working because none of them were "Elgible" (created with a certificate that matched the App ID). I had moved development to a new machine, so perhaps this was the deeper reason.  At any rate I had to create a new certificate, then new provisioning profiles with that certificate being careful to choose the right App ID when creating them.  Good luck.</p>


问:
Add space between
 elements
I have a nav-menu on which it seems that I can't add a space (margin: 3px;) between the
 elements.

You can see the HTML and CSS code on this jsfiddle or below.

You will see that I've added a border-bottom: 2px solid #fff; to the #access li to simulate the space between elements, but that is not going to work because under the nav-menu I will have a bunch of different colors. If I add margin-button: 2px it doesn't work.

This is the HTML:

```<code><nav id="access" role="navigation">
    <div class="menu-header-menu-container">
        <ul id="menu-header-menu" class="menu">
            <li id="menu-item-41" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-41">
                <a href="http://localhost:8888/fullstream/?page_id=5">About Us</a>
            </li>
            <li id="menu-item-35" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-35">
                <a href="http://localhost:8888/fullstream/?page_id=7">Services</a>
            </li>
            <li id="menu-item-34" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-34">
                <a href="http://localhost:8888/fullstream/?page_id=9">Environmental Surface Cleaning</a>
            </li>
            <li id="menu-item-33" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-33">
                <a href="http://localhost:8888/fullstream/?page_id=11">Regulations</a>
            </li>
            <li id="menu-item-32" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-32">
                <a href="http://localhost:8888/fullstream/?page_id=13">Contact Us</a>
            </li>
       </ul>
</div>
</code>```

This is the CSS:

```<code>#access {
    background: #0f84e8; /* Show a solid color for older browsers */
    display: block;
    margin: 0 auto 6px 55px;
    position: absolute;
    top: 100px;
    z-index: 9999;
}
#access ul {
    font-size: 13px;
    list-style: none;
    margin: 0 0 0 -0.8125em;
    padding-left: 0;
}
#access li {
    position: relative;
    padding-left: 11px;
}
#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

#access li:hover > a,
#access ul ul :hover > a,
#access a:focus {
    background: #efefef;
}
#access li:hover > a,
#access a:focus {
    background: #f9f9f9; /* Show a solid color for older browsers */
    background: -moz-linear-gradient(#f9f9f9, #e5e5e5);
    background: -o-linear-gradient(#f9f9f9, #e5e5e5);
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f9f9f9), to(#e5e5e5)); /* Older webkit syntax */
    background: -webkit-linear-gradient(#f9f9f9, #e5e5e5);
    color: #373737;
}
#access ul li:hover > ul {
    display: block;
}
</code>```

答:
I just want to say guys:

Only Play With Margin

It is a lot easier to add space between
 if you play with margin.

ContentLicense: CC BY-SA 4.0

Title: Add space between <li> elements

Body:
I have a nav-menu on which it seems that I can't add a space (margin: 3px;) between the
 elements.

You can see the HTML and CSS code on this jsfiddle or below.

You will see that I've added a border-bottom: 2px solid #fff; to the #access li to simulate the space between elements, but that is not going to work because under the nav-menu I will have a bunch of different colors. If I add margin-button: 2px it doesn't work.

This is the HTML:

                About Us

                Services

                Environmental Surface Cleaning

                Regulations

                Contact Us

This is the CSS:

#access {
    background: #0f84e8; /* Show a solid color for older browsers */
    display: block;
    margin: 0 auto 6px 55px;
    position: absolute;
    top: 100px;
    z-index: 9999;
}
#access ul {
    font-size: 13px;
    list-style: none;
    margin: 0 0 0 -0.8125em;
    padding-left: 0;
}
#access li {
    position: relative;
    padding-left: 11px;
}
#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

#access li:hover > a,
#access ul ul :hover > a,
#access a:focus {
    background: #efefef;
}
#access li:hover > a,
#access a:focus {
    background: #f9f9f9; /* Show a solid color for older browsers */
    background: -moz-linear-gradient(#f9f9f9, #e5e5e5);
    background: -o-linear-gradient(#f9f9f9, #e5e5e5);
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f9f9f9), to(#e5e5e5)); /* Older webkit syntax */
    background: -webkit-linear-gradient(#f9f9f9, #e5e5e5);
    color: #373737;
}
#access ul li:hover > ul {
    display: block;
}

Body:
I just want to say guys:

Only Play With Margin

It is a lot easier to add space between <li> if you play with margin.


问:
Open Xcode project and set active file from terminal
Opening an Xcode project from the terminal is easy:

open Foo.xcodeproj/

But that just opens the project and resumes its previous state using UserInterfaceState.xcuserstate - so it just opens to the last active file you were editing.

Is there a way to open an Xcode project and specify which file it should open to?

What I've tried:

Editing .xcuserstate - nightmare, don't do it.

Running open Foo/Foo.xcodeproj/ then open Foo/Sources/main.swift which works some of the time, but not always. (If you just generated the project and do this, it'll open the project, then in a separate window it'll open the file.)

Any other ideas?

答:
An Xcode engineer named Mike pointed me at the loaded property of Xcode's workspace document scripting class. By polling this, we can wait until Xcode has finished loading the project (including loading the editor pane) before asking it to open the file. This lets up reliably open the file in its project's window.

Here's the xopen script I wrote:

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

shopt -s nullglob

sourceFile="$1"
case "$sourceFile" in
    /*) ;;
    *) sourceFile="$PWD"/"$sourceFile" ;;
esac

projectDir="$sourceFile"
while [[ $projectDir = */* ]]; do
    projectDir="${projectDir%/*}"
    candidates=("$projectDir"/*.xcodeproj)
    candidate="${candidates[0]}"
    if [[ "$candidate" != "" ]]; then
    jPath="$candidate"
    fi
done

if [[ "$jPath" = "" ]]; then
    echo 1>&2 "error: couldn't find .xcodeproj in any parent directory"
    exit 1
fi

exec osascript - "$jPath" "$sourceFile" <<EOF
on run argv
    set jPath to item 1 of argv
    set sourceFile to item 2 of argv
    tell app "Xcode"
    set wsDoc to (open jPath)
    set waitCount to 0
    repeat until wsDoc's loaded or waitCount ≥ 20
        set waitCount to waitCount + 1
        delay 1
    end repeat
    if wsDoc's loaded then
        open sourceFile
    end if
    end tell
end run
EOF
</code>```

This script uses the shell to walk up the directory tree from the source file (given as a command line argument) until it finds a directory containing an Xcode project package. Then it passes the path to the project and the path to the source file to an AppleScript. The AppleScript asks Xcode to open the project. If Xcode already has the project open, it'll just bring the existing project window to the front.

Next, the script polls Xcode until it reports that the workspace document is loaded, or until 20 seconds have elapsed.

Finally, if the workspace document is loaded, it asks Xcode to open the source file. Xcode will open the source file in the existing project window's editor.

Body:
An Xcode engineer named Mike pointed me at the loaded property of Xcode's workspace document scripting class. By polling this, we can wait until Xcode has finished loading the project (including loading the editor pane) before asking it to open the file. This lets up reliably open the file in its project's window.

Here's the xopen script I wrote:

#!/bin/bash

shopt -s nullglob

sourceFile="$1"
case "$sourceFile" in
    /*) ;;
    *) sourceFile="$PWD"/"$sourceFile" ;;
esac

projectDir="$sourceFile"
while [[ $projectDir = */* ]]; do
    projectDir="${projectDir%/*}"
    candidates=("$projectDir"/*.xcodeproj)
    candidate="${candidates[0]}"
    if [[ "$candidate" != "" ]]; then
    jPath="$candidate"
    fi
done

if [[ "$jPath" = "" ]]; then
    echo 1>&2 "error: couldn't find .xcodeproj in any parent directory"
    exit 1
fi

exec osascript - "$jPath" "$sourceFile" <<EOF
on run argv
    set jPath to item 1 of argv
    set sourceFile to item 2 of argv
    tell app "Xcode"
    set wsDoc to (open jPath)
    set waitCount to 0
    repeat until wsDoc's loaded or waitCount ≥ 20
        set waitCount to waitCount + 1
        delay 1
    end repeat
    if wsDoc's loaded then
        open sourceFile
    end if
    end tell
end run
EOF

This script uses the shell to walk up the directory tree from the source file (given as a command line argument) until it finds a directory containing an Xcode project package. Then it passes the path to the project and the path to the source file to an AppleScript. The AppleScript asks Xcode to open the project. If Xcode already has the project open, it'll just bring the existing project window to the front.

Next, the script polls Xcode until it reports that the workspace document is loaded, or until 20 seconds have elapsed.

Finally, if the workspace document is loaded, it asks Xcode to open the source file. Xcode will open the source file in the existing project window's editor.


问:
How can I not escape a character sequence in a string in C#?
I am reading in a value from a resource file (.resx) in C# and in that value, I have added \r\n\r\n so that it gets displayed in the correct format. e.g. blah\r\n\r\nblah
For some reason, the string automatically adds a '\' so effectively text becomes blah\\r\\n\\r\\nblah and thus it escapes the character sequences.

答: Try to use Shift+Enter to add a new line in .resx file instead of \r\n. Or replase like str = str.Replace("\\r\\n", "\r\n");


问:
mysql dynamic column based on weekday
I have a table:

```<code>id 0_open 0_close 1_open 1_close 2_open 2_close 3_open 3_close 4_open 4_close 5_open 5_close 6_open 6_close

1 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00
</code>```

Where 0-6 - weekday (From Mon to Sun);

How can I select rows:

```<code>SELECT * FROM table WHERE TIME(NOW()) BETWEEN 2_open AND 2_close
</code>```

If today is Wednesday (Index: 2)?

答:
Your SQL structure is extremly off.

Usually one would create a table like this:

```<code>id, open, close, weekday
</code>```

and you would be able to query it like this

```<code>SELECT open, close WHERE weekday = DAYOFWEEK()
</code>```

I guess you cannot change it, so you are stuck with your current table. You can query your information like this:

```<code>SELECT 0_open, 0_close FROM table WHEN DAYOFWEEK() = 0
UNION
SELECT 1_open, 1_close FROM table WHEN DAYOFWEEK() = 1
UNION
SELECT 2_open, 2_close FROM table WHEN DAYOFWEEK() = 2
UNION
SELECT 3_open, 3_close FROM table WHEN DAYOFWEEK() = 3
UNION
SELECT 4_open, 4_close FROM table WHEN DAYOFWEEK() = 4
UNION
SELECT 5_open, 5_close FROM table WHEN DAYOFWEEK() = 5
UNION
SELECT 6_open, 6_close FROM table WHEN DAYOFWEEK() = 6
</code>```

Title: mysql dynamic column based on weekday

Body:
I have a table:

id 0_open 0_close 1_open 1_close 2_open 2_close 3_open 3_close 4_open 4_close 5_open 5_close 6_open 6_close

1 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00 07:00 18:00

Where 0-6 - weekday (From Mon to Sun);

How can I select rows:

SELECT * FROM table WHERE TIME(NOW()) BETWEEN 2_open AND 2_close

If today is Wednesday (Index: 2)?

Body:
Your SQL structure is extremly off.

Usually one would create a table like this:

id, open, close, weekday

and you would be able to query it like this

SELECT open, close WHERE weekday = DAYOFWEEK()

I guess you cannot change it, so you are stuck with your current table. You can query your information like this:

SELECT 0_open, 0_close FROM table WHEN DAYOFWEEK() = 0
UNION
SELECT 1_open, 1_close FROM table WHEN DAYOFWEEK() = 1
UNION
SELECT 2_open, 2_close FROM table WHEN DAYOFWEEK() = 2
UNION
SELECT 3_open, 3_close FROM table WHEN DAYOFWEEK() = 3
UNION
SELECT 4_open, 4_close FROM table WHEN DAYOFWEEK() = 4
UNION
SELECT 5_open, 5_close FROM table WHEN DAYOFWEEK() = 5
UNION
SELECT 6_open, 6_close FROM table WHEN DAYOFWEEK() = 6


问:
Excel Add in VSTO don't work when other XLA add in are installed
I have developed an Excel Add in with C#, and was working fine.
But since i had installed another Add in written in VBS in XLA file, my C# Add in doesn't work anymore...
Does anyone faced this situation before? how can i proceed to resolve that?
Can i create an XLA file fore my add in to force it loads?
Best regards
Sabri,</p>

答:
Try disabling and re-enabling your Addin. This could also be a very specific conflict between actions performed by your addin and the XLA file. Finally, it's possible that your Add-in does actions on the Application.Worksheets() elements and is not properly distinguishing between what the active workbook is (i.e. actions are being performed on the hidden XLA workbook that opens with each instance.)

A world of possibilities, so try some of these resolutions, and if nothing works, clarify your problem with a description of what each add-in does.


问:
pyunit mock sys.argv in other file
I have one python file wrote like this:

```<code>import sys
cfgfile = sys.argv[1]
cfg = ConfigObj(cfgfile)
db_dbname=cfg.get("DB_NAME")
class UserMappingsLoader:
    def __init__(self):
        self.debug = 0
        self.cuStartTime = 0
        self.fiId = 0
</code>```

and I want to write a pyunit to do the testing for one method in this code. But when I run my testing code, it shows:

```<code>cfgfile = sys.argv[1]
list index out of range
</code>```

Anyone know how to mock the sys.argv from testing file to this file?

答:
You can do this using patch from the mock module. Here is an example:

```<code>from mock import patch

def test_your_function():
    fake_args = [None, "myfakearg"]
    with patch('sys.argv', fake_args):
        import yourmodule
        # rest of your test
</code>```

Title: pyunit mock sys.argv in other file

Body:
I have one python file wrote like this:

import sys
cfgfile = sys.argv[1]
cfg = ConfigObj(cfgfile)
db_dbname=cfg.get("DB_NAME")
class UserMappingsLoader:
    def __init__(self):
        self.debug = 0
        self.cuStartTime = 0
        self.fiId = 0

and I want to write a pyunit to do the testing for one method in this code. But when I run my testing code, it shows:

cfgfile = sys.argv[1]
list index out of range

Anyone know how to mock the sys.argv from testing file to this file?

Body:
You can do this using patch from the mock module. Here is an example:

from mock import patch

def test_your_function():
    fake_args = [None, "myfakearg"]
    with patch('sys.argv', fake_args):
        import yourmodule
        # rest of your test


问:
Open various files using a java netbeans program
I would like to make a program that in java using netbeans.  I want this program to search through a specified folder and display all files into a text area.

here's what I saw on stackoverflow:

```<code>File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));
</code>```

how do I make it better?

答:
```<code>File file=new File("path to your file");
 Process p = Runtime.getRuntime().exec("RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL " + file.getAbsolutePath());
    p.waitFor();
</code>```

this code simply opens Files

Body:
I would like to make a program that in java using netbeans.  I want this program to search through a specified folder and display all files into a text area.

here's what I saw on stackoverflow:

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

how do I make it better?

Body:
File file=new File("path to your file");
 Process p = Runtime.getRuntime().exec("RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL " + file.getAbsolutePath());
    p.waitFor();

this code simply opens Files


问:
PHP PDO prepare() prepared statements not working, but query() works
Having trouble getting these PDO prepared statements to work. Working with PHP 7.0.9 on Windows / MAMP and SQLite here.

PHP PDO driver pdo_sqlite installed version 3.8.10.2

Anyone see what am I doing wrong here?

This works as expected:

```<code>$st = $pdo->query("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= 4010");
$results = $st->fetchAll();
</code>```

This does not work, and gives zero results:

```<code>$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= :x AND `parallel` <= :y");
$st->execute(array(':x' => 4000, ':y' => 4010));
$results = $st->fetchAll();
</code>```

This also does not work:

```<code>$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= :y");
$st->execute(array(':y' => 4010));
$results = $st->fetchAll();
</code>```

And ends up giving me the same results as:

```<code>SELECT * FROM `e48` WHERE `parallel` >= 4000
</code>```

P.S Also tested in Linux virtual machine web server with same results.

答:
I've worked it out.

I was using the TEXT SQLite datatype for the parallel column, and it works when I switched it to REAL (they are all floating point numbers). So the value in the database was previously stored as (preferred) text strings.

After changing it to REAL, the prepared statements now work.

Ref: Type Conversions Prior To Comparison

Why did $pdo->query("SELECT * FROM e48 WHERE parallel >= 4000 AND parallel <= 4010") work?

If one operand has INTEGER, REAL or NUMERIC affinity and the other operand has TEXT or BLOB or no affinity then NUMERIC affinity is applied to other operand.

The right hand operand is treated as having NUMERIC affinity, so comparison works as expected.

Why didn't $pdo->prepare("SELECT * FROM e48 WHERE parallel >= :x AND parallel <= :y") work?

If one operand has TEXT affinity and the other has no affinity, then TEXT affinity is applied to the other operand.

With PHP PDO combined with SQLite, the right hand side operand is queried as having no affinity at all, so the comparison is treated as having TEXT affinity, which in turn becomes a no-op comparison.

Body:
Having trouble getting these PDO prepared statements to work. Working with PHP 7.0.9 on Windows / MAMP and SQLite here.

PHP PDO driver pdo_sqlite installed version 3.8.10.2

Anyone see what am I doing wrong here?

This works as expected:

$st = $pdo->query("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= 4010");
$results = $st->fetchAll();

This does not work, and gives zero results:

$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= :x AND `parallel` <= :y");
$st->execute(array(':x' => 4000, ':y' => 4010));
$results = $st->fetchAll();

This also does not work:

$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= :y");
$st->execute(array(':y' => 4010));
$results = $st->fetchAll();

And ends up giving me the same results as:

SELECT * FROM `e48` WHERE `parallel` >= 4000

P.S Also tested in Linux virtual machine web server with same results.


问:
Copy all files and folders from a source folder to multiple folders with a specic name
I have a source folder(c:\test*) and I want that folder copied to all folders in the same location (c:\resultaat) but only to the folders in that location that contains the name demo_profit.

I think I'm almost there, but I'm missing a small part I think.

```<code>$destination = get-item -include demo_profit* -path C:\resultaat\*
copy-item C:\test\* $destination -recurse -force
</code>```

thanks for your help

答:
So it is not clear if you want to copy the files to a folder containing an item named demo_profit, or to folder with demo_profit in the name. The second is simple, so I'll start there:

```<code>Get-ChildItem C:\resultaat\* -Directory |
    Where{$_.Name -match 'demo_profit'} |
    ForEach{ Copy-Item C:\test\* -dest $_.FullName -recurse -force }
</code>```

That finds any folder within c:\resultaat that has 'demo_profit' as part of its name, and copies the desired files/folders into that folder. Example: C:\resultaat\Folder1_demo_profit would have all the files from C:\temp copied into it.

If you are looking for things named demo_profit, and want to copy the files into the same folder as that item you need to use the PSParentPath property, and some wildcards.

```<code>Get-ChildItem c:\resultaat\*\*demo_profit*
</code>```

This command would find a file or folder with a path such as 'C:\resultaat\Amazon\az_demo_profit'. Then to copy files into the folder containing that you would use the PSParentPath property as such:

```<code>Get-ChildItem c:\resultaat\*\*demo_profit* |
    Select -Expand PSParentPath -Unique
    ForEach{ Copy-Item C:\test\* -dest $_ -recurse -force }
</code>```

Body:
I have a source folder(c:\test*) and I want that folder copied to all folders in the same location (c:\resultaat) but only to the folders in that location that contains the name demo_profit.

I think I'm almost there, but I'm missing a small part I think.

$destination = get-item -include demo_profit* -path C:\resultaat\*
copy-item C:\test\* $destination -recurse -force

thanks for your help

Body:
So it is not clear if you want to copy the files to a folder containing an item named demo_profit, or to folder with demo_profit in the name. The second is simple, so I'll start there:

Get-ChildItem C:\resultaat\* -Directory |
    Where{$_.Name -match 'demo_profit'} |
    ForEach{ Copy-Item C:\test\* -dest $_.FullName -recurse -force }

That finds any folder within c:\resultaat that has 'demo_profit' as part of its name, and copies the desired files/folders into that folder. Example: C:\resultaat\Folder1_demo_profit would have all the files from C:\temp copied into it.

If you are looking for things named demo_profit, and want to copy the files into the same folder as that item you need to use the PSParentPath property, and some wildcards.

Get-ChildItem c:\resultaat\*\*demo_profit*

This command would find a file or folder with a path such as 'C:\resultaat\Amazon\az_demo_profit'. Then to copy files into the folder containing that you would use the PSParentPath property as such:

Get-ChildItem c:\resultaat\*\*demo_profit* |
    Select -Expand PSParentPath -Unique
    ForEach{ Copy-Item C:\test\* -dest $_ -recurse -force }


问:
Is is possible to enable "Hard reload" and "Empty cache and hard reload" options without having devtool open?
Just a quick question. I would like to know if there is an option or a switch to enable the "Hard reload" and "Empty cache and hard reload" options under the reload button without having to open devtools, so that they always pop up, even if the devtools are not open.

I know about the shorcut keys, but if only it was possible to still have all the options available regardless of the devtools, that would be nice.

答:
I was just googling this and couldn't find anything that would enable the hard reload feature but here's what I do:

ctrl + F5 (if it doesn't work then do number 2)

ctrl + shift + delete ( only check cached images and filed) and hit F5 again


问:
Limiting characters on UITextField breaks Emojis, can only add one and not delete
I'm using the following code to limit the amount of characters that can be in a UITextField

```<code>public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let currentCharacterCount = textField.text?.characters.count ?? 0
        if (range.length + range.location > currentCharacterCount){
            return false
        }
        let newLength = currentCharacterCount + string.characters.count - range.length
        return newLength <= 44
    }
</code>```

This is done by setting the UITextField's delegate to self.

--

The issue here is that if you add an Emoji to the textfield, you cannot remove it. Even if you highlight - select all, or use "cut" the text will not change. The emoji can be before or after text, or even alone in the text field. You also cannot add two emojis to the field.

I don't see what the issue is here, can anyone help me out?

答:
In Swift 3.1

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentCharacterCount = textField.text?.characters.count ?? 0
    let limit = 10
    return currentCharacterCount < limit || string.characters.count < range.length
}
</code>```

This won't prevent copy and paste long text string, I disabled the paste function for UITextField, with codes from

https://stackoverflow.com/a/39015132/6311644

Body:
I'm using the following code to limit the amount of characters that can be in a UITextField

public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let currentCharacterCount = textField.text?.characters.count ?? 0
        if (range.length + range.location > currentCharacterCount){
            return false
        }
        let newLength = currentCharacterCount + string.characters.count - range.length
        return newLength <= 44
    }

This is done by setting the UITextField's delegate to self.

--

The issue here is that if you add an Emoji to the textfield, you cannot remove it. Even if you highlight - select all, or use "cut" the text will not change. The emoji can be before or after text, or even alone in the text field. You also cannot add two emojis to the field.

I don't see what the issue is here, can anyone help me out?

Body:
In Swift 3.1

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentCharacterCount = textField.text?.characters.count ?? 0
    let limit = 10
    return currentCharacterCount < limit || string.characters.count < range.length
}

This won't prevent copy and paste long text string, I disabled the paste function for UITextField, with codes from

https://stackoverflow.com/a/39015132/6311644


问:
PHPSESSID security issues?
I've been curious for a while now about the security issues surrounding the PHP session name: PHPSESSID.

I've noticed that some websites rename their session ID cookie, while others just leave it as the default.

Is there any security advantage in using a different name? or is it merely useful for being able to track multiple sessions per user?

答:
No, the session ID’s name is just a name to identify the session ID; you can change it to whatever you want as long as your system knows that name.

But as already mentioned, you might want to change the name to obscure your system. But there are also other aspects that can be used to identify you system besides the session ID’s name.

Title: PHPSESSID security issues?