问:
Jenkins: addOrReplaceAction() throwing strange exception
I was attempting to add parameters to a job with a Trigger plugin I'm writing. Here's the incriminating line of code:

```<code>job.addOrReplaceAction(new ParametersAction(new StringParameterValue("repoAction", "testan", "test")));
</code>```

Maven compiles and builds the plugin perfectly fine. However, once the trigger is activated, an exception is thrown:

java.lang.UnsupportedOperationException   at
  java.util.Collections$UnmodifiableCollection.removeAll(Collections.java:1068)
    at hudson.model.Actionable.addOrReplaceAction(Actionable.java:206)
    at plugin package.GitHubRepoTrigger.run(GitHubRepoTrigger.java:38)

...

I took a dive into the Jenkins Actionable class source code and noted that the addOrReplaceAction() function  uses a List<Action> collection which calls the collection method removeAll(). When I then looked through Java's documentation on this function it notes:

java.lang.UnsupportedOperationException if the removeAll method is not supported by this collection

By this point I was completely lost as to why this issue is occurring. Is something actually wrong with Jenkins? Or is my understanding of adding and modifying build parameters just dead wrong?

答:
Jenkins wrote that function may cause unexpected results:

concurrent calls to any of the mutation methods may produce
  surprising results

See java docs.

Body:
I was attempting to add parameters to a job with a Trigger plugin I'm writing. Here's the incriminating line of code:

job.addOrReplaceAction(new ParametersAction(new StringParameterValue("repoAction", "testan", "test")));

Maven compiles and builds the plugin perfectly fine. However, once the trigger is activated, an exception is thrown:

java.lang.UnsupportedOperationException   at
  java.util.Collections$UnmodifiableCollection.removeAll(Collections.java:1068)
    at hudson.model.Actionable.addOrReplaceAction(Actionable.java:206)
    at plugin package.GitHubRepoTrigger.run(GitHubRepoTrigger.java:38)

...

I took a dive into the Jenkins Actionable class source code and noted that the addOrReplaceAction() function  uses a List<Action> collection which calls the collection method removeAll(). When I then looked through Java's documentation on this function it notes:

java.lang.UnsupportedOperationException if the removeAll method is not supported by this collection

By this point I was completely lost as to why this issue is occurring. Is something actually wrong with Jenkins? Or is my understanding of adding and modifying build parameters just dead wrong?


来源: stackexchange

问:
Gallery Layout through posts
I am developing a  gallery in which I want a layout something like .. http://mightymente.org/projects/aarohievents/design/

I developed most of it .. please review the code and give suggestions how to impprove it.

My code:

```<code>$the_query = new WP_Query("showposts=6&cat=1&orderby=asc");
$count = 1;
while ( $the_query ->have_posts() ) {$the_query ->the_post(); $i++;
    $thumb_id = get_post_thumbnail_id();
    $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size',
   false);
    list($width, $height) = getimagesize($thumb_url[0]);
    if($width == 800){
        $class='grid-1';
    } elseif($width==270) {
        $class='sub_grid gallery_w3l';
    }
    if ($i == 1){
        echo "<div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
    }
?>

    <div class="<?php echo $class; ?>">
    <a class="cm-overlay" href="<?php echo $thumb_url[0];?>">
    <img src="<?php echo $thumb_url[0];?>" alt=" " class="img-responsive" />
    <div class="w3agile-text w3agile-text-small">
    <h5><?php the_title(); ?></h5>
    </div>
     </a> <?php //echo $i ; ?>
     </div>
<?php
    $count++;
    if ($i == 3){
        echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";}
        if ($i == 6){
            echo "</div>";$i=0;
        }
    }
    wp_reset_postdata();
</code>```

答:
This is your actuall code:

```<code>   if ($i == 3){
       //At this position $i has to be 3, if not it will never come to here
       echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
       if ($i == 6){
          //So this line will never be executed cause $i will never be 6 here
          echo "</div>";$i=0;
       }
    }
</code>```

So it should be:

```<code>    if ($i == 3){
       echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
    }
    if ($i == 6){
       echo "</div>";$i=0;
    }
</code>```

Or with elseIf

Based on  @ravisachaniya comment you can also go for

```<code>if ($i % 3 == 0){
     //This way it divides $i with 3 and if the levtover is 0 it goes inside
     //Means 3, 6, 9, 12, 15 and so on
     echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
     if ($i == 6){
          echo "</div>";$i=0;
     }
 }
</code>```

With this solution it would also print in the 6th loop

```<code>echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Gallery Layout through posts

Body:
I am developing a  gallery in which I want a layout something like .. http://mightymente.org/projects/aarohievents/design/

I developed most of it .. please review the code and give suggestions how to impprove it.

My code:

$the_query = new WP_Query("showposts=6&cat=1&orderby=asc");
$count = 1;
while ( $the_query ->have_posts() ) {$the_query ->the_post(); $i++;
    $thumb_id = get_post_thumbnail_id();
    $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size',
   false);
    list($width, $height) = getimagesize($thumb_url[0]);
    if($width == 800){
        $class='grid-1';
    } elseif($width==270) {
        $class='sub_grid gallery_w3l';
    }
    if ($i == 1){
        echo "
";
    }
?>

    <div class="<?php echo $class; ?>">
    <a class="cm-overlay" href="<?php echo $thumb_url[0];?>">
    <img src="<?php echo $thumb_url[0];?>" alt=" " class="img-responsive" />

<?php the_title(); ?>

      <?php //echo $i ; ?>

<?php
    $count++;
    if ($i == 3){
        echo "

";}
        if ($i == 6){
            echo "
";$i=0;
        }
    }
    wp_reset_postdata();

Body:
This is your actuall code:

   if ($i == 3){
       //At this position $i has to be 3, if not it will never come to here
       echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
       if ($i == 6){
          //So this line will never be executed cause $i will never be 6 here
          echo "</div>";$i=0;
       }
    }

So it should be:

    if ($i == 3){
       echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
    }
    if ($i == 6){
       echo "</div>";$i=0;
    }

Or with elseIf

Based on  @ravisachaniya comment you can also go for

if ($i % 3 == 0){
     //This way it divides $i with 3 and if the levtover is 0 it goes inside
     //Means 3, 6, 9, 12, 15 and so on
     echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";
     if ($i == 6){
          echo "</div>";$i=0;
     }
 }

With this solution it would also print in the 6th loop

echo "</div><div class='col-md-6 col-sm-6 col-xs-12 grid_w3'>";


问:
if content size > actual height then fixed height and if content size < actual height then dynamic of tableview swift 3?
In storyBoard i have given top, bottom, leading and trailing constraints to tableview in a view.
i have given tableview height as contentSize.height. As per tableview height, no of cells that can visible in tableview 3 or 4 or etc(depending upon content size it may vary). But the problem is table view height is increasing as per content size.
if no of cells are more, then it should compare actual height of the table view with content size and if contentSize is lesser than tableview Actual height then only it should change the height of tableview.

```<code>if tableViewActualHeight > contentSize {
// then only change tableview height
    tableViewActualHeight = contentSize
}
</code>```

How can we get & where to place that code?

答:
You need to set one more constraint to your tableview - Fixed height.

Now take(or connect) outlet of that constraint and then set constant of that outlet as per your condition. If your content size is greater then your tableview do nothing else set your height constraint's constant as content size like,

```<code>  heightConstraint.constant = 20  // Your contentsize instead of 20
</code>```

You need to do that after your tableview successfully reload, other wise it will not give correct content size.

If your cell or row's height is fixed then you can count content height your self. You can multiply row height with number of row (array count)!

Body:
In storyBoard i have given top, bottom, leading and trailing constraints to tableview in a view.
i have given tableview height as contentSize.height. As per tableview height, no of cells that can visible in tableview 3 or 4 or etc(depending upon content size it may vary). But the problem is table view height is increasing as per content size.
if no of cells are more, then it should compare actual height of the table view with content size and if contentSize is lesser than tableview Actual height then only it should change the height of tableview.

if tableViewActualHeight > contentSize {
// then only change tableview height
    tableViewActualHeight = contentSize
}

How can we get & where to place that code?

Body:
You need to set one more constraint to your tableview - Fixed height.

Now take(or connect) outlet of that constraint and then set constant of that outlet as per your condition. If your content size is greater then your tableview do nothing else set your height constraint's constant as content size like,

  heightConstraint.constant = 20  // Your contentsize instead of 20

You need to do that after your tableview successfully reload, other wise it will not give correct content size.

If your cell or row's height is fixed then you can count content height your self. You can multiply row height with number of row (array count)!


问:
Devanagaric text processing(NLP) where to start
I am new to Devnagaric NLP, Is there any group or resources that would help me get started with NLP in Devnagaric language(Mostly Nepali language or similar like Hindi).  I want to be able to develop fonts for Devanagaric and also do some font processing application. If anyone (working in this field), could give me some advice then it would be highly appreciable.
Thanks in advance </p>

答:
Is there any group or resources that would help me get started with NLP in Devnagaric language?

The Bhasa Sanchar project under Madan Puraskar Pustakalaya has developed a Nepali corpus. You may request a Nepali corpus for non-commerical purposes from the contact provided in the link above.

Python's NLTK has the Hindi Language corpus. You may import it using

```<code>from nltk.corpus import indian
</code>```

For gaining insight to Devnagari based NLP, I suggest you go through research papers.Nepali being an under-resourced language;much work yet to be done, and it might be difficult to get contents for the same.

You should probably look into language detection,text classification,sentiment analysis among others (preferably based on POS tagging library from the corpus) for grasping the basics.

For the second part of the question

I am pretty sure font development doesn't come under the domain of Natural Language Processing. Did you mean something else?

Body:
Is there any group or resources that would help me get started with NLP in Devnagaric language?

The Bhasa Sanchar project under Madan Puraskar Pustakalaya has developed a Nepali corpus. You may request a Nepali corpus for non-commerical purposes from the contact provided in the link above.

Python's NLTK has the Hindi Language corpus. You may import it using

from nltk.corpus import indian

For gaining insight to Devnagari based NLP, I suggest you go through research papers.Nepali being an under-resourced language;much work yet to be done, and it might be difficult to get contents for the same.

You should probably look into language detection,text classification,sentiment analysis among others (preferably based on POS tagging library from the corpus) for grasping the basics.

For the second part of the question

I am pretty sure font development doesn't come under the domain of Natural Language Processing. Did you mean something else?


问:
running openCL in android
Well there are many tutorials and post about this, but I am not getting exactly how to deal with libOpenCL.so file. Many vendors does not include it inside phone, but my app needs to support maximum available phones today, so do I need to get compatible libOpenCL.so file for each of them?  </p>

答:
OpenCL is not officially supported by Android Open Source Project

See: Why did Google choose RenderScript instead of OpenCL

However it appears that Device Manufacturers are including support by adding in the driver.

See: Does Android support OpenCL?

Realize that OpenCL is at a similar layer in the hardware stack as the graphics driver and any particular implementation will depend on the manufacturer and would be specific to that device. You can't just take a libOpenCL.so from one ARM64 device and expect to work for another due to system-on-a-chip specific customizations (number of cores, DSPs, GPUs etc.)

My recommendation from: C++, OpenCV and "what" for cross-platform GPU programing

If you want maximum support - stick to C/C++ code.

If you need OpenCL to make your app performant even with parallelized code, your option is to check if the library is there and warn the user about the lack of support. Ideally then fall back to the parallelized code on those devices without OpenCL.

Until Google makes OpenCL part of the Android Compatibility Definition Document and requires some metadata property, only by the app checking on the device can the app know that OpenCL is even available.

Title: running openCL in android


问:
HTTP WCF Service, JSON date formatting issue returning IEnumerable<class>
I have a Restful WCF Http Service that returns JSON and works great, except the DateTime doesn't format correctly:

e.g. "AdjudDate": "/Date(1349409600000-0400)/"

After looking around I found an old post here but I could not get that code to work. It was last updated in 2011. Is there maybe a more current version or implementation?
JSON.NET Serializer for WCF REST Services

Here's my code that returns an IEnumerable.

//All JSON values are good except for the dates:

```<code>private IEnumerable<Customer> ProcessWcfPost(Customer searchmodel)
{
    return _repository.GetCustomers(searchModel);
}
</code>```

edit
I've also of course tried changing the return type to string instead of IEnumerable as:

```<code>private string ProcessWcfPost(Customer searchmodel)
    {
        var result = _repository.GetCustomers(searchModel);
        return Newtonsoft.Json.JsonConvert.SerializeObject(result);
    }
</code>```

But my JSON is not quite right:
[{\"ClaimProcessId\":1599986,\"ClmHdrId\":1011,\"ClmLineId\":1011,\"ClmAdjId\":1011,\"ReceivedDtSur\":\"2012-12-05T00:00:00\",\"AdjudicationDtSur\":\"2011-10-05T00:00:00\"(on and on)...

答:
You can try use IsoDateTimeConverter</p>

```<code>IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string strJSON = JsonConvert.SerializeObject(jsonObject, Newtonsoft.Json.Formatting.Indented, timeConverter);
</code>```

Body:
I have a Restful WCF Http Service that returns JSON and works great, except the DateTime doesn't format correctly:

e.g. "AdjudDate": "/Date(1349409600000-0400)/"

After looking around I found an old post here but I could not get that code to work. It was last updated in 2011. Is there maybe a more current version or implementation?
JSON.NET Serializer for WCF REST Services

Here's my code that returns an IEnumerable.

//All JSON values are good except for the dates:

private IEnumerable<Customer> ProcessWcfPost(Customer searchmodel)
{
    return _repository.GetCustomers(searchModel);
}

edit
I've also of course tried changing the return type to string instead of IEnumerable as:

private string ProcessWcfPost(Customer searchmodel)
    {
        var result = _repository.GetCustomers(searchModel);
        return Newtonsoft.Json.JsonConvert.SerializeObject(result);
    }

But my JSON is not quite right:
[{\"ClaimProcessId\":1599986,\"ClmHdrId\":1011,\"ClmLineId\":1011,\"ClmAdjId\":1011,\"ReceivedDtSur\":\"2012-12-05T00:00:00\",\"AdjudicationDtSur\":\"2011-10-05T00:00:00\"(on and on)...

Body:
You can try use IsoDateTimeConverter

IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string strJSON = JsonConvert.SerializeObject(jsonObject, Newtonsoft.Json.Formatting.Indented, timeConverter);


问:
Android Volley Error
I get Android volley error suddenly when i run my program.here i paste my AppController class for handling the volley objects.

AppController.java

```<code>public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}
</code>```

and i call this class in some another class of my program like

AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

it will executed without any errors in so many days but now it shows error
like

Error:

```<code>java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request or its super classes (declaration of 'com.android.volley.Request'; appears in /data/app/com.example.rninja4.rookie-1/split_lib_dependencies_apk.apk:classes6.dex)
                                                                          at com.example.packagename.App.AppController.addToRequestQueue(AppController.java:39)
</code>```

答:
You have not declared application class in manifest like below.</p>

```<code><application
    android:name="AppController"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</code>```

Title: Android Volley Error

Body:
I get Android volley error suddenly when i run my program.here i paste my AppController class for handling the volley objects.

AppController.java

public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}

and i call this class in some another class of my program like

AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

it will executed without any errors in so many days but now it shows error
like

Error:

java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request or its super classes (declaration of 'com.android.volley.Request'; appears in /data/app/com.example.rninja4.rookie-1/split_lib_dependencies_apk.apk:classes6.dex)
                                                                          at com.example.packagename.App.AppController.addToRequestQueue(AppController.java:39)

Body:
You have not declared application class in manifest like below.

<application
    android:name="AppController"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >


问:
How to place an object in front of camera always
I am making an application in that i am rendering an 360 image and i want to add an object or cross hair in front of camera i.e(billboard concept).

So i have tired alot of thing from stack overflow itself but i didn't get any idea how i can do that below is my code which i am trying to do.

```<code>Vector3 position;
    float[] newPosition4 = new float[4];
    position = obj.getPosition();
    float[] posVec4 = {0, 0, -8, 0.0f};
    float[] HeadViewMatrix_inv = new float[16];
    Matrix4 HeadViewMatrix4 = new Matrix4();
    HeadViewMatrix4.setAll(getCurrentCamera().getViewMatrix());
    HeadViewMatrix4 = HeadViewMatrix4.inverse();

    //Copy matrix to HeadViewMatrix array,
    HeadViewMatrix4.toFloatArray(HeadViewMatrix_inv);

    //Translation of viewMatrix
    Matrix.multiplyMV(newPosition4, 0, HeadViewMatrix_inv, 0, posVec4, 0);
    obj.setPosition(newPosition4[0], newPosition4[1], newPosition4[2]);
</code>```

So any one can help me out in this.

答:
If you want to use canvas, i can offer a simple solution.

```<code>    <RelativeLayout
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- Camera Preview -->

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
</code>```

Add SurfaceView and Canvas to this FrameLayout and draw anything you wish inside that canvas.

Body:
I am making an application in that i am rendering an 360 image and i want to add an object or cross hair in front of camera i.e(billboard concept).

So i have tired alot of thing from stack overflow itself but i didn't get any idea how i can do that below is my code which i am trying to do.

Vector3 position;
    float[] newPosition4 = new float[4];
    position = obj.getPosition();
    float[] posVec4 = {0, 0, -8, 0.0f};
    float[] HeadViewMatrix_inv = new float[16];
    Matrix4 HeadViewMatrix4 = new Matrix4();
    HeadViewMatrix4.setAll(getCurrentCamera().getViewMatrix());
    HeadViewMatrix4 = HeadViewMatrix4.inverse();

    //Copy matrix to HeadViewMatrix array,
    HeadViewMatrix4.toFloatArray(HeadViewMatrix_inv);

    //Translation of viewMatrix
    Matrix.multiplyMV(newPosition4, 0, HeadViewMatrix_inv, 0, posVec4, 0);
    obj.setPosition(newPosition4[0], newPosition4[1], newPosition4[2]);

So any one can help me out in this.

Body:
If you want to use canvas, i can offer a simple solution.

    <RelativeLayout
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- Camera Preview -->

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

Add SurfaceView and Canvas to this FrameLayout and draw anything you wish inside that canvas.


问:
RadioGroup not working in fragment android
I have faced an issue radio check change listener not working in the android fragment, I tried this within an activity it will work fine, while I convert into fragment it will give no response, please help me, here is my code.

K06_Away.java

```<code> public class K06_Away extends Fragment {

        private View kf06_view;
        protected Typeface tfLatoBold,tfLatoMedium,tfLatoRegular;
        private Button button_kf06_back,button_kf06_next;
        private TextView txtVw_kf06_resident_away;
        private EditText edTxt_kf06_visiting_lastname;
        private RadioGroup radioGp_kf06_resident_away;
        List<RadioButton> radioButtons = new ArrayList<RadioButton>();

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            kf06_view = inflater.inflate(R.layout.k06_away, container, false);

            return kf06_view;
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
                   configViews();
        }

        private void configViews() {
            button_kf06_back = (Button) kf06_view.findViewById(R.id.button_kf06_back);
            button_kf06_next = (Button) kf06_view.findViewById(R.id.button_kf06_next);
            txtVw_kf06_resident_away= (TextView) kf06_view.findViewById(R.id.txtVw_kf06_resident_away);

            radioGp_kf06_resident_away = (RadioGroup) kf06_view.findViewById(R.id.radioGp_kf06_resident_away);
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_1_2_hours) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_halfday) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_allday) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_moreday) );

            configClickListeners();
            radioButtonAction();

        }
        private void configClickListeners() {
            button_kf06_back.setOnClickListener(this);
            button_kf06_next.setOnClickListener(this);
        }
        private void radioButtonAction(){
            for (RadioButton button : radioButtons){
                button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) processRadioButtonClick(buttonView);
                        String radio_Text = buttonView.getText().toString();
                        int radio_Id = buttonView.getId();
                        System.out.println("Selected the Radio:"+radio_Text+", Radio-Id:"+radio_Id);
                    }
                });

            }
        }

        private void processRadioButtonClick(CompoundButton buttonView){
            for (RadioButton button : radioButtons){
                if (button != buttonView ) button.setChecked(false);
            }

        }

}
</code>```

k06_away.xml

```<code><RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/lLayout_kf06_resident_away"
            android:id="@+id/radioGp_kf06_resident_away">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:baselineAligned="false"
                tools:ignore="UselessParent">
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:layout_marginLeft="150dp"
                    tools:ignore="RtlHardcoded">
                    <RadioButton
                        android:id="@+id/radio_kf06_1_2_hours"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_1"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:paddingStart="20dp"
                        android:layout_marginTop="150dp"
                        android:textColor="@color/colorWhite"
                        tools:ignore="NestedWeights,RtlSymmetry" />

                    <RadioButton
                        android:id="@+id/radio_kf06_halfday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_2"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="50dp"
                        tools:ignore="NestedWeights,RtlSymmetry"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:layout_marginLeft="50dp"
                    tools:ignore="RtlHardcoded">
                    <RadioButton
                        android:id="@+id/radio_kf06_allday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_3"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="150dp"
                        tools:ignore="NestedWeights,RtlSymmetry"/>

                    <RadioButton
                        android:id="@+id/radio_kf06_moreday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_4"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="50dp"
                        tools:ignore="NestedWeights,RtlSymmetry,RtlHardcoded"/>

                </LinearLayout>
            </LinearLayout>
        </RadioGroup>
</code>```

答: RadioGroup Directly contain only RadioButtons,No other Layouts,if you add LinearLayout inside RadioGroup,it will not works as you expect.Only use RadioButtons as child of RadioGroup.</p>

Body:
I have faced an issue radio check change listener not working in the android fragment, I tried this within an activity it will work fine, while I convert into fragment it will give no response, please help me, here is my code.

K06_Away.java

 public class K06_Away extends Fragment {

        private View kf06_view;
        protected Typeface tfLatoBold,tfLatoMedium,tfLatoRegular;
        private Button button_kf06_back,button_kf06_next;
        private TextView txtVw_kf06_resident_away;
        private EditText edTxt_kf06_visiting_lastname;
        private RadioGroup radioGp_kf06_resident_away;
        List<RadioButton> radioButtons = new ArrayList<RadioButton>();

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            kf06_view = inflater.inflate(R.layout.k06_away, container, false);

            return kf06_view;
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
                   configViews();
        }

        private void configViews() {
            button_kf06_back = (Button) kf06_view.findViewById(R.id.button_kf06_back);
            button_kf06_next = (Button) kf06_view.findViewById(R.id.button_kf06_next);
            txtVw_kf06_resident_away= (TextView) kf06_view.findViewById(R.id.txtVw_kf06_resident_away);

            radioGp_kf06_resident_away = (RadioGroup) kf06_view.findViewById(R.id.radioGp_kf06_resident_away);
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_1_2_hours) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_halfday) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_allday) );
            radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_moreday) );

            configClickListeners();
            radioButtonAction();

        }
        private void configClickListeners() {
            button_kf06_back.setOnClickListener(this);
            button_kf06_next.setOnClickListener(this);
        }
        private void radioButtonAction(){
            for (RadioButton button : radioButtons){
                button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) processRadioButtonClick(buttonView);
                        String radio_Text = buttonView.getText().toString();
                        int radio_Id = buttonView.getId();
                        System.out.println("Selected the Radio:"+radio_Text+", Radio-Id:"+radio_Id);
                    }
                });

            }
        }

        private void processRadioButtonClick(CompoundButton buttonView){
            for (RadioButton button : radioButtons){
                if (button != buttonView ) button.setChecked(false);
            }

        }

}

k06_away.xml

<RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/lLayout_kf06_resident_away"
            android:id="@+id/radioGp_kf06_resident_away">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:baselineAligned="false"
                tools:ignore="UselessParent">
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:layout_marginLeft="150dp"
                    tools:ignore="RtlHardcoded">
                    <RadioButton
                        android:id="@+id/radio_kf06_1_2_hours"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_1"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:paddingStart="20dp"
                        android:layout_marginTop="150dp"
                        android:textColor="@color/colorWhite"
                        tools:ignore="NestedWeights,RtlSymmetry" />

                    <RadioButton
                        android:id="@+id/radio_kf06_halfday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_2"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="50dp"
                        tools:ignore="NestedWeights,RtlSymmetry"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:layout_marginLeft="50dp"
                    tools:ignore="RtlHardcoded">
                    <RadioButton
                        android:id="@+id/radio_kf06_allday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_3"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="150dp"
                        tools:ignore="NestedWeights,RtlSymmetry"/>

                    <RadioButton
                        android:id="@+id/radio_kf06_moreday"
                        style="@style/radionbutton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_resident_away_hour_4"
                        android:layout_gravity="left"
                        android:checked="false"
                        android:textSize="25sp"
                        android:textColor="@color/colorWhite"
                        android:paddingStart="20dp"
                        android:layout_marginTop="50dp"
                        tools:ignore="NestedWeights,RtlSymmetry,RtlHardcoded"/>

                </LinearLayout>
            </LinearLayout>
        </RadioGroup>

ContentLicense: CC BY-SA 4.0


问:
change view's property from method of other class
I'm trying to remotely adjust an object myImageView's alphato 0 of MyViewControllerclass From Another class Assistant(it's a NSObject subclass).

in Assistant.h

```<code>#import <Foundation/Foundation.h>

@class MyViewController;

@interface Assistant : NSObject {

    MyViewController *myViewController;
    UIImageView *button;

}
- (void)adjustAlpha:(id)sender;

@property (nonatomic, retain) UIImageView *button;
</code>```

in Assistant.m

```<code>#import "MyViewController.h"

@implementation Assistant

@synthesize button;

- (id)init
{
 self = [super init];
 if (self)
 {
      myViewController = [[MyViewController alloc] init];
      NSLog(@"alloced?: %@", myViewController ? @"YES" : @"NO");
 }
 return self;
}

- (void)adjustAlpha:(id)sender
{
     NSLog(@"method called");
     myViewController.myImageView.alpha = 0;
}
</code>```

the method did get called, But myViewController.myImageView.alpha didn't change, why? where i need to fix? thank you for reading ^_^

Edit

This is MyViewController class:

MyViewController.h

```<code>@class Assistant;

@class MyAppAppDelegate;

@interface MyViewController : UIViewController <UITextViewDelegate, UIScrollViewDelegate>
{
   UIImageView *myImageView;
   Assistant *assistant;
}
@property (nonatomic, retain) UIImageView *myImageView;
</code>```

MyViewController.m

```<code>#import "MyViewController.h"
#import "Assistant.h"

@implementation MyViewController

@synthesize myImageView;

- (void)viewDidLoad
{
  [super viewDidLoad];
    assistant = [[Assistant alloc] init];
    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,460);
    [self.view addSubview: myScrollView];

    myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"weather.png"]];
    myImageView.frame = CGRectMake(19, 54, 48, 48);
    myImageView.userInteractionEnabled = YES;
    [myScrollView addSubview:myImageView];

    //this button uses to call adjustAlpha
    assistant.button = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button.png"]];
    assistant.button.frame = CGRectMake(19, 126, 48, 48);
    assistant.button.userInteractionEnabled = YES;
[myScrollView addSubview:assistant.button];

    //here is how i call adjustAlpha:
    assistant.adjustAlphaTap =  [[UITapGestureRecognizer alloc] initWithTarget:assistant action:@selector(adjustAlpha:)];
    [assistant.button addGestureRecognizer:assistant.adjustAlphaTap];

}
</code>```

this question got complex and need some experiments, so just hanging there, will make it clear when i have time. for developer met the same problems: declare the object you need to access in a singleton class, can be easily accessed from any other classes, and Merry Christmas!

答:
This will only work if myImageView is declared as a global scope variable (also called an iVar) in the .h file of your MyViewController class AND that it has a property of (nonatomic, retain) with a matching @synthesize in the .m.

If this sounds like what you're doing then can you please post the contents of your MyViewController h and m files.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to remotely adjust an object myImageView's alphato 0 of MyViewControllerclass From Another class Assistant(it's a NSObject subclass).

in Assistant.h

#import <Foundation/Foundation.h>

@class MyViewController;

@interface Assistant : NSObject {

    MyViewController *myViewController;
    UIImageView *button;

}
- (void)adjustAlpha:(id)sender;

@property (nonatomic, retain) UIImageView *button;

in Assistant.m

#import "MyViewController.h"

@implementation Assistant

@synthesize button;

- (id)init
{
 self = [super init];
 if (self)
 {
      myViewController = [[MyViewController alloc] init];
      NSLog(@"alloced?: %@", myViewController ? @"YES" : @"NO");
 }
 return self;
}

- (void)adjustAlpha:(id)sender
{
     NSLog(@"method called");
     myViewController.myImageView.alpha = 0;
}

the method did get called, But myViewController.myImageView.alpha didn't change, why? where i need to fix? thank you for reading ^_^

Edit

This is MyViewController class:

MyViewController.h

@class Assistant;

@class MyAppAppDelegate;

@interface MyViewController : UIViewController <UITextViewDelegate, UIScrollViewDelegate>
{
   UIImageView *myImageView;
   Assistant *assistant;
}
@property (nonatomic, retain) UIImageView *myImageView;

MyViewController.m

#import "MyViewController.h"
#import "Assistant.h"

@implementation MyViewController

@synthesize myImageView;

- (void)viewDidLoad
{
  [super viewDidLoad];
    assistant = [[Assistant alloc] init];
    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,460);
    [self.view addSubview: myScrollView];

    myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"weather.png"]];
    myImageView.frame = CGRectMake(19, 54, 48, 48);
    myImageView.userInteractionEnabled = YES;
    [myScrollView addSubview:myImageView];

    //this button uses to call adjustAlpha
    assistant.button = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button.png"]];
    assistant.button.frame = CGRectMake(19, 126, 48, 48);
    assistant.button.userInteractionEnabled = YES;
[myScrollView addSubview:assistant.button];

    //here is how i call adjustAlpha:
    assistant.adjustAlphaTap =  [[UITapGestureRecognizer alloc] initWithTarget:assistant action:@selector(adjustAlpha:)];
    [assistant.button addGestureRecognizer:assistant.adjustAlphaTap];

}

this question got complex and need some experiments, so just hanging there, will make it clear when i have time. for developer met the same problems: declare the object you need to access in a singleton class, can be easily accessed from any other classes, and Merry Christmas!


问:
Getting empty result in output when using Select statement in Grid-View
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code

```<code>using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
    con1.Open();
    SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con1.Close();
}
</code>```

Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here

答:
You have used the DataSet not DataTable. So you could either do this:

```<code>da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];
</code>```

Or use a DataTable instead:

```<code>DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
</code>```

Also you should always use parameterized queries to avoid SQL Injection. Something like this:

```<code>SqlCommand cmd = new SqlCommand("select * from Pm where user_id=@userId", con1);
cmd.Parameters.AddWithValue("@userId", (String)Session["uid"]);
</code>```

Also have a look at this: Can we stop using AddWithValue() already?

Body:
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code

using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
    con1.Open();
    SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con1.Close();
}

Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here

Body:
You have used the DataSet not DataTable. So you could either do this:

da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];

Or use a DataTable instead:

DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;

Also you should always use parameterized queries to avoid SQL Injection. Something like this:

SqlCommand cmd = new SqlCommand("select * from Pm where user_id=@userId", con1);
cmd.Parameters.AddWithValue("@userId", (String)Session["uid"]);

Also have a look at this: Can we stop using AddWithValue() already?


问:
if ( Selection < 0) and (Selection > 3) condition behaves differently for input =4. Why?
```<code>def PrintBlue():
    print (" You chose Blue!\r\n")

def PrintRed():
    print (" You chose Red!\r\n")

def PrintOrange():
    print (" You chose Orange!\r\n")

def PrintYellow():
    print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
    0:PrintBlue,
    1:PrintRed,
    2:PrintOrange,
    3:PrintYellow
    }

Selection = 0

while (Selection != 4):
    print ("0.Blue")
    print ("1.Red")
    print ("2.Orange")
    print ("3.Yellow")
    try:
        Selection = int(input("Select a color option: "))
        x=0
        if ( Selection < 0) and (Selection > 3):
            raise KeyError(" Enter a number >=0 and <4)")
        else:
            ColorSelect[Selection]() # Run the function inside dictionary as well
    except KeyError:
        pass
</code>```

Above is my python code. I am using 2.7 version. but after running I got different result for input =4. While I am expecting same result for Selection<0 or >3.Here is result look like:

0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 5
0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 4

Notice after I enter input =4 , python exits from run time.When I enter 0,1,2,3,5,6,7, every time it ask again to enter value again, but when I enter 4 it exits.

答:
```<code>if ( Selection < 0) and (Selection > 3):
</code>```

means "if Selection is both less than zero and greater than three", which can't happen. I suspect you mean

```<code>if ( Selection < 0) or (Selection > 3):
</code>```

which will raise an error for an input outside of the valid range.

The program is exiting when you enter 4 because of

```<code>while (Selection != 4):
</code>```

If that's not the desired behavior, you need to change that line. For example, if you want the loop to run forever, it could be just

```<code>while True:
</code>```

Body:
def PrintBlue():
    print (" You chose Blue!\r\n")

def PrintRed():
    print (" You chose Red!\r\n")

def PrintOrange():
    print (" You chose Orange!\r\n")

def PrintYellow():
    print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
    0:PrintBlue,
    1:PrintRed,
    2:PrintOrange,
    3:PrintYellow
    }

Selection = 0

while (Selection != 4):
    print ("0.Blue")
    print ("1.Red")
    print ("2.Orange")
    print ("3.Yellow")
    try:
        Selection = int(input("Select a color option: "))
        x=0
        if ( Selection < 0) and (Selection > 3):
            raise KeyError(" Enter a number >=0 and <4)")
        else:
            ColorSelect[Selection]() # Run the function inside dictionary as well
    except KeyError:
        pass

Above is my python code. I am using 2.7 version. but after running I got different result for input =4. While I am expecting same result for Selection<0 or >3.Here is result look like:

0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 5
0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 4

Notice after I enter input =4 , python exits from run time.When I enter 0,1,2,3,5,6,7, every time it ask again to enter value again, but when I enter 4 it exits.

Body:
if ( Selection < 0) and (Selection > 3):

means "if Selection is both less than zero and greater than three", which can't happen. I suspect you mean

if ( Selection < 0) or (Selection > 3):

which will raise an error for an input outside of the valid range.

The program is exiting when you enter 4 because of

while (Selection != 4):

If that's not the desired behavior, you need to change that line. For example, if you want the loop to run forever, it could be just

while True:


问:
Using multiple observables to create an observable?
I have a bunch of observables that I'm running/subscribing to in a method (about 9 to be exact), that itself returns an observable. I narrowed it down to 2 observables for the purpose of this question. Here is my method that I created that returns an Observable that contains the other observables.

```<code>public static Observable<MyCustomObject> runAll(Service networkService) {
        return Observable.create(subscriber -> {

            networkService.getOne().subscribe(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                subscriber.onNext(case);
            }, exception -> {
                throw new OnErrorNotImplementedException(exception);
            });

            networkService.getTwo().subscribe(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                subscriber.onNext(case);
            }, exception -> {
                throw new OnErrorNotImplementedException(exception);
            });

            subscriber.onComplete();
        });
    }
</code>```

I then use the Observable that's returned...

```<code>       runAll(networkService)
.subscribeOn(Schedulers.io())
.subscribe(case -> {
           //do stuff

        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                //handle error
            }
        });
</code>```

I'm not sure if I'm creating an observable correctly. I'm essentially replacing a listener/interface that I had here before with an Observable, but I know using Observable.create() is something that is not easy. Should I do it another way? Is there anything wrong with doing what I'm doing?

EDIT: getOne() and getTwo() are network calls so they return Observables.

EDIT 2: Currently have this

```<code>public static Observable<MyCustomObject> quickRun(Service networkService) {
    return Observable.concat(
            networkService.getOne().map(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                return case;
            }),
            networkService.getTwo().map(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                return case;
            })
    );
}
</code>```

答:
Yes, you should do it in a different way.

Whenever you're treating Observable like regular async callback this is a smell that you are not acting 'reactive'-ly.

As you said Observable.create() is non-trivial way with some pitfalls for creating Observable, that being said, you probably use older version of RxJava 1, with newer version (1.3+ I think), and with RxJava2, create is based on emitter and is safer. you can read here about the pitfalls of Create and the emitter approach. (as a side note with RxJava2 has another way of extending Observable).

All of those ways are to bridge between the async callback world to Reactive world, and wrap it any kind of async operation with Observable.

As for your case, as you have already Observables at your hand, what you need is to compose them together to single stream - Observable.
Rx has many operators for this purpose, according to your example Observable.merge seems the appropriate operator, all your Observable will run in asynchronously (note, you will need to apply to each of them the IO scheduler for that), and each Observable will emit its result on the merged stream, when all of the Observable will finish - onCompleted will be called on the merged Observable, which is by the way wrong at your example as it's called at the very start just after you've been fire all tasks.

```<code>Observable.merge(
        networkService.getOne()
                .subscribeOn(Schedulers.io()),
        networkService.getTwo()
                .subscribeOn(Schedulers.io())
)
        .map(response -> {
            Request request = response.raw().request();
            return new MyCustomObject(request);
        })
        .subscribe(customObject -> {
                    //do stuff
                }, throwable -> {
                    //handle error
                }
        );
</code>```

Body:
I have a bunch of observables that I'm running/subscribing to in a method (about 9 to be exact), that itself returns an observable. I narrowed it down to 2 observables for the purpose of this question. Here is my method that I created that returns an Observable that contains the other observables.

public static Observable<MyCustomObject> runAll(Service networkService) {
        return Observable.create(subscriber -> {

            networkService.getOne().subscribe(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                subscriber.onNext(case);
            }, exception -> {
                throw new OnErrorNotImplementedException(exception);
            });

            networkService.getTwo().subscribe(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                subscriber.onNext(case);
            }, exception -> {
                throw new OnErrorNotImplementedException(exception);
            });

            subscriber.onComplete();
        });
    }

I then use the Observable that's returned...

       runAll(networkService)
.subscribeOn(Schedulers.io())
.subscribe(case -> {
           //do stuff

        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                //handle error
            }
        });

I'm not sure if I'm creating an observable correctly. I'm essentially replacing a listener/interface that I had here before with an Observable, but I know using Observable.create() is something that is not easy. Should I do it another way? Is there anything wrong with doing what I'm doing?

EDIT: getOne() and getTwo() are network calls so they return Observables.

EDIT 2: Currently have this

public static Observable<MyCustomObject> quickRun(Service networkService) {
    return Observable.concat(
            networkService.getOne().map(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                return case;
            }),
            networkService.getTwo().map(response -> {
                Request request = response.raw().request();
                MyCustomObject case = new MyCustomObject(request);
                return case;
            })
    );
}

Body:
Yes, you should do it in a different way.

Whenever you're treating Observable like regular async callback this is a smell that you are not acting 'reactive'-ly.

As you said Observable.create() is non-trivial way with some pitfalls for creating Observable, that being said, you probably use older version of RxJava 1, with newer version (1.3+ I think), and with RxJava2, create is based on emitter and is safer. you can read here about the pitfalls of Create and the emitter approach. (as a side note with RxJava2 has another way of extending Observable).

All of those ways are to bridge between the async callback world to Reactive world, and wrap it any kind of async operation with Observable.

As for your case, as you have already Observables at your hand, what you need is to compose them together to single stream - Observable.
Rx has many operators for this purpose, according to your example Observable.merge seems the appropriate operator, all your Observable will run in asynchronously (note, you will need to apply to each of them the IO scheduler for that), and each Observable will emit its result on the merged stream, when all of the Observable will finish - onCompleted will be called on the merged Observable, which is by the way wrong at your example as it's called at the very start just after you've been fire all tasks.

Observable.merge(
        networkService.getOne()
                .subscribeOn(Schedulers.io()),
        networkService.getTwo()
                .subscribeOn(Schedulers.io())
)
        .map(response -> {
            Request request = response.raw().request();
            return new MyCustomObject(request);
        })
        .subscribe(customObject -> {
                    //do stuff
                }, throwable -> {
                    //handle error
                }
        );


问:
Centering my Logo Div
I have tried every possible method to center my logo div but no luck. I even ended up going back to old school align="center" but no luck.

Please help - http://rezaee.me/kel/

Cheers

答: Try removing position: fixed from your #logo declaration.

Title: Centering my Logo Div


问:
Sql conditional sum computation on other column value check
i have following sql query.

```<code>SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.
</code>```

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

答:
try this :</p>

```<code>SELECT
    isnull((
    SELECT SUM(Qty)
    From Bills
    inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
    where SessionID = '" + DBHandler.SessionID(Date) + "'
    and BillMaster.ShiftID = " + SHiftID + "
    and Bills.ProductID = products.id and isdeal=0
    ), 0) [qty],
products.price , products.name
FROM products
</code>```

Body:
i have following sql query.

SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

Body:
try this :

SELECT
    isnull((
    SELECT SUM(Qty)
    From Bills
    inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
    where SessionID = '" + DBHandler.SessionID(Date) + "'
    and BillMaster.ShiftID = " + SHiftID + "
    and Bills.ProductID = products.id and isdeal=0
    ), 0) [qty],
products.price , products.name
FROM products


问:
Text getting blurred after scaling in css
I am using scale transform to zoom a div in html but the text within is getting blurred. Is there any way I can make the text clear as original

@keyframes scaleText {
  from {
    transform: scale(0.5, 0.5);
  }
  to {
    transform: scale(2, 2);
  }
}

#para1Six {
  color: black;
  text-align: center;
  -webkit-font-smoothing: antialiased;
  font-size: 19px;
  font-family: 'Sacramento', cursive;
  z-index: 2;
}
#wrapper
{
  width: 500px;
  margin: 0 auto;
  animation-name: scaleText;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div class="envelope open">
    <div class="flap front"></div>
    <div class="flap top"></div>
    <div class="letter">
      <p id="para1Six">
        Hello World
      </p>
    </div>
  </div></code>```

答:
You can trnasform your text without scale.

Use font-size for text and transform:scale() for div separately.

Body:
I am using scale transform to zoom a div in html but the text within is getting blurred. Is there any way I can make the text clear as original

@keyframes scaleText {
  from {
    transform: scale(0.5, 0.5);
  }
  to {
    transform: scale(2, 2);
  }
}

#para1Six {
  color: black;
  text-align: center;
  -webkit-font-smoothing: antialiased;
  font-size: 19px;
  font-family: 'Sacramento', cursive;
  z-index: 2;
}
#wrapper
{
  width: 500px;
  margin: 0 auto;
  animation-name: scaleText;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

        Hello World


问:
How to get value of checkbox from checkboxlistFor using jquery ajax in MVC
I have a checkboxlistfor control in mvc 5 and want the value of the selected checkbox, once I get the value then send ajax request and fetch the data as per id,
below is the reference link where similar kind of functionality is achieved, in this he has used "for loop" for multiple checkboxes, and I am using checkboxlistfor, using this I am not able to get the value of the selected checkbox.

"https://forums.asp.net/t/2078931.aspx?How+to+get+data+from+checkbox+list+using+jquery+ajax+in+MVC+"

Below is the code I am using to bind checkboxlistfor code

view

```<code>@Html.CheckBoxListFor(model => model.sbuIDs,
                      model => model.Availablesbu,
                      sb => sb.sbuID,
                      sb => sb.sbuName,
                      model => model.Selectedsbu,
                      htmlListInfo)
</code>```

controller code

```<code>[HttpGet]
public ActionResult AddUsers()
{
    var Uvm = new UsersViewModel();

    var Selectedsbu = new List<sbu>();
    Uvm.Availablesbu = _User.Getallsbu();
    Uvm.Selectedsbu = Selectedsbu;
    return View(Uvm);
}

public class sbu
{
    public int UserID { get; set; }
    public int sbuID { get; set; }
    public string sbuName { get; set; }
}

public class UsersViewModel()
{
    public IEnumerable<sbu> sbu = null;
    sbu = new List<sbu>();
    public IEnumerable<sbu> Availablesbu { get; set; }
    public IEnumerable<sbu> Selectedsbu { get; set; }
    public string[] sbuIDs { get; set; }
}
</code>```

Update

Below is the ajax request i will use:

```<code><script>
    $("#CheckBoxListFor").change(function () {
        debugger;
        var favorite = [];
        $.each($("input[name='sbuIDs']:checked"), function () {
            favorite.push($(this).val());
        });

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url: '@Url.Action("Getvalues", "Home")',

            data: JSON.stringify({ values: favorite })
        });

    });
</script>
</code>```

Controller code

```<code>public JsonResult Getvalues(string[] values)
{
    //
}
</code>```

答:
Rendered in HTML a check box list will have a shared name but will have different ids being the name followed by a - and a number identifying the index.

You can use jQuery to get a list of those selected.

```<code>$('[name="checkBoxListName"]:checked');
</code>```

To get an array of their values:

```<code>var values = $('[name="checkBoxListName"]:checked').get();
</code>```

Your sample script should work with some minor changes. 1) use the name selector as your checkboxes will have different ids. 2) Wrap the code in $(document).ready. 3) Just post the raw object and not a string:

```<code><script>
$(document).ready(function() {
    $("[name='checkBoxListName']).change(function () {
        // code here.
        data: { values: favorite }
    });
 });
</script>
</code>```

Body:
I have a checkboxlistfor control in mvc 5 and want the value of the selected checkbox, once I get the value then send ajax request and fetch the data as per id,
below is the reference link where similar kind of functionality is achieved, in this he has used "for loop" for multiple checkboxes, and I am using checkboxlistfor, using this I am not able to get the value of the selected checkbox.

"https://forums.asp.net/t/2078931.aspx?How+to+get+data+from+checkbox+list+using+jquery+ajax+in+MVC+"

Below is the code I am using to bind checkboxlistfor code

view

@Html.CheckBoxListFor(model => model.sbuIDs,
                      model => model.Availablesbu,
                      sb => sb.sbuID,
                      sb => sb.sbuName,
                      model => model.Selectedsbu,
                      htmlListInfo)

controller code

[HttpGet]
public ActionResult AddUsers()
{
    var Uvm = new UsersViewModel();

    var Selectedsbu = new List<sbu>();
    Uvm.Availablesbu = _User.Getallsbu();
    Uvm.Selectedsbu = Selectedsbu;
    return View(Uvm);
}

public class sbu
{
    public int UserID { get; set; }
    public int sbuID { get; set; }
    public string sbuName { get; set; }
}

public class UsersViewModel()
{
    public IEnumerable<sbu> sbu = null;
    sbu = new List<sbu>();
    public IEnumerable<sbu> Availablesbu { get; set; }
    public IEnumerable<sbu> Selectedsbu { get; set; }
    public string[] sbuIDs { get; set; }
}

Update

Below is the ajax request i will use:

Controller code

public JsonResult Getvalues(string[] values)
{
    //
}

Body:
Rendered in HTML a check box list will have a shared name but will have different ids being the name followed by a - and a number identifying the index.

You can use jQuery to get a list of those selected.

$('[name="checkBoxListName"]:checked');

To get an array of their values:

var values = $('[name="checkBoxListName"]:checked').get();

Your sample script should work with some minor changes. 1) use the name selector as your checkboxes will have different ids. 2) Wrap the code in $(document).ready. 3) Just post the raw object and not a string:

<script>
$(document).ready(function() {
    $("[name='checkBoxListName']).change(function () {
        // code here.
        data: { values: favorite }
    });
 });
</script>


问:
Download dialog Box IE
I have use this code

Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA

But I get the error

"user defined type not defined"

on

```<code>Dim o As IUIAutomation
</code>```

Someone knows how  can I fix it?

答:
Add it using code

```<code>Public Sub AddReference()

ThisWorkbook.VBProject.References.AddFromFile
"C:\Windows\System32\UIAutomationCore.dll"

End Sub
</code>```

and goto excel>>option>>Trust Center>>Trust Center Setting>>Macro setting  and check on the Trust access to the VBA project object model

Title: Download dialog Box IE

Body:
I have use this code

Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA

But I get the error

"user defined type not defined"

on

Dim o As IUIAutomation

Someone knows how  can I fix it?

Body:
Add it using code

Public Sub AddReference()

ThisWorkbook.VBProject.References.AddFromFile
"C:\Windows\System32\UIAutomationCore.dll"

End Sub

and goto excel>>option>>Trust Center>>Trust Center Setting>>Macro setting  and check on the Trust access to the VBA project object model


问:
Access Device hardware (Camera Flash) Programically ina android
I have one question that can we access android device camera's flash light

  programmically.Is this possible to turn on and off flash light programmically?
  please give me my answer .
  thanks in advance.

```<code>    package com.thedevelopersinfo.tutorial.android.soundrecordingexample;

         import java.io.File;

         import android.app.Activity;
       import android.content.ContentResolver;
       import android.content.ContentValues;
     import android.content.Intent;
       import android.hardware.Camera;

     import android.media.MediaRecorder;
      import android.net.Uri;
     import android.os.Bundle;
      import android.os.Environment;
     import android.provider.MediaStore;
     import android.provider.MediaStore.MediaColumns;
      import android.view.View;
     import android.view.View.OnClickListener;
        import android.widget.Button;

         public class Main extends Activity {
    private MediaRecorder mediaRecorder;
    private File file = null;
    static final String PREFIX = "record";
    static final String EXTENSION = ".3gpp";
    private Button b1;
    Camera mCamera;
    public boolean isOn=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         mCamera = Camera.open();

        Camera.Parameters params = mCamera.getParameters();

        b1=(Button)findViewById(R.id.startBtn);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 setFlashlight();

            }
        });

    }
    public void setFlashlight()
    {
        if (mCamera == null)
        {

        }
        Camera.Parameters params = mCamera.getParameters();
        String value;
        if (isOn) // we are being ask to turn it on
        {
            value = Camera.Parameters.FLASH_MODE_TORCH;
        }
        else  // we are being asked to turn it off
        {
            value =  Camera.Parameters.FLASH_MODE_AUTO;
        }

        try{
            params.setFlashMode(value);
            mCamera.setParameters(params);

            String nowMode = mCamera.getParameters().getFlashMode();

            if (isOn)
            {
                 nowMode.equals(Camera.Parameters.FLASH_MODE_TORCH);
            }
            if (!isOn)
            {
                 nowMode.equals(Camera.Parameters.FLASH_MODE_AUTO);
            }

        }
        catch (Exception ex)
        {
        }
        }

}
</code>```

but i got following exception
03-10 18:47:34.907: ERROR/QualcommCameraHardware(1280): Parameter AntiBanding is not supported for this sensor

答: You can do so by using Camera.Parameters.setFlashMode. See: http://developer.android.com/reference/android/hardware/Camera.Parameters.html

Body:
I have one question that can we access android device camera's flash light

  programmically.Is this possible to turn on and off flash light programmically?
  please give me my answer .
  thanks in advance.

    package com.thedevelopersinfo.tutorial.android.soundrecordingexample;

         import java.io.File;

         import android.app.Activity;
       import android.content.ContentResolver;
       import android.content.ContentValues;
     import android.content.Intent;
       import android.hardware.Camera;

     import android.media.MediaRecorder;
      import android.net.Uri;
     import android.os.Bundle;
      import android.os.Environment;
     import android.provider.MediaStore;
     import android.provider.MediaStore.MediaColumns;
      import android.view.View;
     import android.view.View.OnClickListener;
        import android.widget.Button;

         public class Main extends Activity {
    private MediaRecorder mediaRecorder;
    private File file = null;
    static final String PREFIX = "record";
    static final String EXTENSION = ".3gpp";
    private Button b1;
    Camera mCamera;
    public boolean isOn=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         mCamera = Camera.open();

        Camera.Parameters params = mCamera.getParameters();

        b1=(Button)findViewById(R.id.startBtn);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 setFlashlight();

            }
        });

    }
    public void setFlashlight()
    {
        if (mCamera == null)
        {

        }
        Camera.Parameters params = mCamera.getParameters();
        String value;
        if (isOn) // we are being ask to turn it on
        {
            value = Camera.Parameters.FLASH_MODE_TORCH;
        }
        else  // we are being asked to turn it off
        {
            value =  Camera.Parameters.FLASH_MODE_AUTO;
        }

        try{
            params.setFlashMode(value);
            mCamera.setParameters(params);

            String nowMode = mCamera.getParameters().getFlashMode();

            if (isOn)
            {
                 nowMode.equals(Camera.Parameters.FLASH_MODE_TORCH);
            }
            if (!isOn)
            {
                 nowMode.equals(Camera.Parameters.FLASH_MODE_AUTO);
            }

        }
        catch (Exception ex)
        {
        }
        }

}

but i got following exception
03-10 18:47:34.907: ERROR/QualcommCameraHardware(1280): Parameter AntiBanding is not supported for this sensor


答:
you need to set DataTable instead of DataSet</p>

```<code>GridView1.DataSource = ds.Tables["Pm"];
</code>```

Title: Getting empty result in output when using Select statement in Grid-View

Body:
you need to set DataTable instead of DataSet

GridView1.DataSource = ds.Tables["Pm"];


问:
Why Umbraco replace hostname/subdomain in external link
I am using webforms with Umbraco 7.6.3 I have simple menu(not using template)  on my master page (/masterpages/Master.master) like this:

```<code>     <li class="dropdown">
        <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">Home</a>
          <ul class="dropdown-menu">
                 <li><a runat="server" href="https://sub1.test.mywebsite">Home</a></li>
           </ul>
     </li>
</code>```

if I don't add www In href Umbraco replace hostname/subdomain.
Am I missing any setting?

答:
You need write code like this:</p>

```<code><div>
    <ul>
      <li><a>Home</a></li>
      <li><a>aboutus</a></li>
      <li><a href="https://www.google.com">Search</a></li>
    </ul>
</div>
</code>```

Body:
I am using webforms with Umbraco 7.6.3 I have simple menu(not using template)  on my master page (/masterpages/Master.master) like this:

        Home

Home

if I don't add www In href Umbraco replace hostname/subdomain.
Am I missing any setting?

Body:
You need write code like this:

<div>
    <ul>
      <li><a>Home</a></li>
      <li><a>aboutus</a></li>
      <li><a href="https://www.google.com">Search</a></li>
    </ul>
</div>


问:
raise NeedDownloadError('Need ffmpeg exe. ' NeedDownloadError: Need ffmpeg exe)
I'm trying to execute a call to an unofficial Instagram API python library, after several errors for dependencies needed I fixed, I'm stuck at this one.</p>

```<code> File "C:\Users\Pablo\Desktop\txts_pys_phps_programacion\Instagram-API-python-master\InstagramAPI.py", line 15, in <module>
    from moviepy.editor import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\editor.py", line 22, in <module>
    from .video.io.VideoFileClip import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 3, in <module>
    from moviepy.video.VideoClip import VideoClip
  File "C:\Python27\lib\site-packages\moviepy\video\VideoClip.py", line 20, in <module>
    from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
  File "C:\Python27\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 15, in <module>
    from moviepy.config import get_setting
  File "C:\Python27\lib\site-packages\moviepy\config.py", line 38, in <module>
    FFMPEG_BINARY = get_exe()
  File "C:\Python27\lib\site-packages\imageio\plugins\ffmpeg.py", line 86, in get_exe
    raise NeedDownloadError('Need ffmpeg exe. '
NeedDownloadError: Need ffmpeg exe. You can download it by calling:
  imageio.plugins.ffmpeg.download()
</code>```

答:
For anyone using a mac do this.

pip install imageio (if not already installed).

Then create a .py file (python script).

In this file write this:

```<code>import imageio

imageio.plugins.ffmpeg.download()
</code>```

Run this script in the terminal (i.e "python (insert .py filename here)" )

It installs FFmpeg in a directory that should be automatically added to your path. If not, add it to your path.

Then type

```<code>   ffmpeg
</code>```

to make sure it's installed in your path.

Body:
I'm trying to execute a call to an unofficial Instagram API python library, after several errors for dependencies needed I fixed, I'm stuck at this one.

 File "C:\Users\Pablo\Desktop\txts_pys_phps_programacion\Instagram-API-python-master\InstagramAPI.py", line 15, in <module>
    from moviepy.editor import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\editor.py", line 22, in <module>
    from .video.io.VideoFileClip import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 3, in <module>
    from moviepy.video.VideoClip import VideoClip
  File "C:\Python27\lib\site-packages\moviepy\video\VideoClip.py", line 20, in <module>
    from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
  File "C:\Python27\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 15, in <module>
    from moviepy.config import get_setting
  File "C:\Python27\lib\site-packages\moviepy\config.py", line 38, in <module>
    FFMPEG_BINARY = get_exe()
  File "C:\Python27\lib\site-packages\imageio\plugins\ffmpeg.py", line 86, in get_exe
    raise NeedDownloadError('Need ffmpeg exe. '
NeedDownloadError: Need ffmpeg exe. You can download it by calling:
  imageio.plugins.ffmpeg.download()

Body:
For anyone using a mac do this.

pip install imageio (if not already installed).

Then create a .py file (python script).

In this file write this:

import imageio

imageio.plugins.ffmpeg.download()

Run this script in the terminal (i.e "python (insert .py filename here)" )

It installs FFmpeg in a directory that should be automatically added to your path. If not, add it to your path.

Then type

   ffmpeg

to make sure it's installed in your path.


问:
High memory usage of a windows forms method
I have a c# windows forms application which uses too much memory. The peace of code, that is the problem is this

```<code>private void mainTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                {
                    if (File.Exists(Globals.pathNotifFile + "1"))
                    {
                        File.Delete(Globals.pathNotifFile + "1");
                        File.Move(Globals.pathNotifFile, Globals.pathNotifFile + "1");
                    }
                    File.Move(Globals.pathNotifFile, Globals.pathNotifFile + "1");
                }

                if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                {
                    return;
                }

                if (Globals.shotsFired != true)
                {
                    CreateDLclient();
                    Globals.shotsFired = true;
                }

                if (Globals.pathNotifFile == null)
                {
                    return;
                }

                var data = Deserialize();

                foreach (var notifyData in data.@new)
                {
                    if (notifyData.Status == "1" || notifyData.Status == string.Empty)
                    {
                        if (DateTime.Now >= Convert.ToDateTime(notifyData.DateTime))
                        {
                            if (notifyData.Message != string.Empty)
                            {
                                notifyData.Status = SendMessageToUser(notifyData.Message, notifyData.Company, notifyData.EmojiCode);
                                Serialize(data);
                            }
                            else
                            {
                                notifyData.Status = "3";
                                Serialize(data);
                            }
                        }
                        else if (DateTime.Now >= Convert.ToDateTime(notifyData.DateTime).AddMinutes(5))
                        {
                            if (notifyData.Message != string.Empty)
                            {
                                notifyData.Status = SendMessageToUser(notifyData.Message, notifyData.Company, notifyData.EmojiCode);
                                Serialize(data);

                            }
                            else
                            {
                                notifyData.Status = "3";
                                Serialize(data);
                            }
                        }
                    }
                }
            }
</code>```

It causes a huge problem and the application crashes with 'out of memory' Can somebody give me an advice how can I reduce the memory usage of that. I've tried to invoke the GC /I know it is not a good idea/, but it didn't help.

Thank you in advance

答:
You have not provided any info on which serializer you used in your program but I am quite inclined to think it is XMLSerializer because it is prone to memory leak and you said in your comment that the program is crashing after working more then 10-12 hours.

XmlSerializer uses assembly generation, and assemblies cannot be collected. As far as I know It does some caching for re-use but only for simple cases.

So if you have code like the following,which is called pretty often→

```<code>XmlSerializer xml = new XmlSerializer(typeof(MyObject), ....
</code>```

Then you will get out of memory exception sooner or later.

Edit: How to avoid Memory Leak from XMLSerializer:
Please have a look at the Topic
Dynamically Generated Assemblies in the following link→MSDN Link
If I just summarize what is written in there is that, you have a couple of ways.

1) You can use the following constructors to avoid dynamic assembly

```<code>XmlSerializer.XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)
</code>```

2) Using a dictionary or hashtable, create your own caching

```<code>private Dictionary<Tuple<Type, XmlRootAttribute>, XmlSerializer> cacheSerializer = new Dictionary<Tuple<Type, XmlRootAttribute>, XmlSerializer>();
public XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute root) {
    var key = Tuple.Create(type, root);
    XmlSerializer xmlSerializer;
    if (cacheSerializer.TryGetValue(key, out xmlSerializer)) {
        return xmlSerializer;
    }
    xmlSerializer = new XmlSerializer(type, root);
    cacheSerializer.Add(key,xmlSerializer);
    return xmlSerializer;
}
</code>```

Body:
I have a c# windows forms application which uses too much memory. The peace of code, that is the problem is this

private void mainTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                {
                    if (File.Exists(Globals.pathNotifFile + "1"))
                    {
                        File.Delete(Globals.pathNotifFile + "1");
                        File.Move(Globals.pathNotifFile, Globals.pathNotifFile + "1");
                    }
                    File.Move(Globals.pathNotifFile, Globals.pathNotifFile + "1");
                }

                if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                {
                    return;
                }

                if (Globals.shotsFired != true)
                {
                    CreateDLclient();
                    Globals.shotsFired = true;
                }

                if (Globals.pathNotifFile == null)
                {
                    return;
                }

                var data = Deserialize();

                foreach (var notifyData in data.@new)
                {
                    if (notifyData.Status == "1" || notifyData.Status == string.Empty)
                    {
                        if (DateTime.Now >= Convert.ToDateTime(notifyData.DateTime))
                        {
                            if (notifyData.Message != string.Empty)
                            {
                                notifyData.Status = SendMessageToUser(notifyData.Message, notifyData.Company, notifyData.EmojiCode);
                                Serialize(data);
                            }
                            else
                            {
                                notifyData.Status = "3";
                                Serialize(data);
                            }
                        }
                        else if (DateTime.Now >= Convert.ToDateTime(notifyData.DateTime).AddMinutes(5))
                        {
                            if (notifyData.Message != string.Empty)
                            {
                                notifyData.Status = SendMessageToUser(notifyData.Message, notifyData.Company, notifyData.EmojiCode);
                                Serialize(data);

                            }
                            else
                            {
                                notifyData.Status = "3";
                                Serialize(data);
                            }
                        }
                    }
                }
            }

It causes a huge problem and the application crashes with 'out of memory' Can somebody give me an advice how can I reduce the memory usage of that. I've tried to invoke the GC /I know it is not a good idea/, but it didn't help.

Thank you in advance

Body:
You have not provided any info on which serializer you used in your program but I am quite inclined to think it is XMLSerializer because it is prone to memory leak and you said in your comment that the program is crashing after working more then 10-12 hours.

XmlSerializer uses assembly generation, and assemblies cannot be collected. As far as I know It does some caching for re-use but only for simple cases.

So if you have code like the following,which is called pretty often→

XmlSerializer xml = new XmlSerializer(typeof(MyObject), ....

Then you will get out of memory exception sooner or later.

Edit: How to avoid Memory Leak from XMLSerializer:
Please have a look at the Topic
Dynamically Generated Assemblies in the following link→MSDN Link
If I just summarize what is written in there is that, you have a couple of ways.

1) You can use the following constructors to avoid dynamic assembly

XmlSerializer.XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)

2) Using a dictionary or hashtable, create your own caching

private Dictionary<Tuple<Type, XmlRootAttribute>, XmlSerializer> cacheSerializer = new Dictionary<Tuple<Type, XmlRootAttribute>, XmlSerializer>();
public XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute root) {
    var key = Tuple.Create(type, root);
    XmlSerializer xmlSerializer;
    if (cacheSerializer.TryGetValue(key, out xmlSerializer)) {
        return xmlSerializer;
    }
    xmlSerializer = new XmlSerializer(type, root);
    cacheSerializer.Add(key,xmlSerializer);
    return xmlSerializer;
}


问:
Does runtime of an algorithm depends on processor?
I have given a project for finding all the primes below N.And for this the test case timeout condition is [TestMethod, Timeout(1000)],which means our algorithm should execute in <1sec.

When i run the same program on i5 processor it ran successfully but when i run it on i3 the testcases failed because of timeout error.

Does the runtime of an algorithm depends on processor?

What are the factors that effects run time of an algorithm?

答:
Does the runtime of an algorithm depends on processor?

Of course execution time depends on processor. That's why companies like Intel spend vast amounts of money on producing faster and faster processors.

For example: if an algorithm consists of 1 million operations, and a CPU is capable of performing 1 million operations per second, executing that algorithm would take 1 second. On the other hand, given a processor with performance of 10 million operations per second, that algorithm would take only 0.1s. That's very simplified example, as not every instruction takes the same time, and there's more factors involved (cache, memory bandwidth, special instructions like SSE), but it illustrates general point: faster processor executes code in shorter time - that's the point of faster processors.

Note: that's totally unrelated to time complexity.


问:
Dynamic ng-bind inside a custom directive merging
I have a button formed from my custom directive where once the user clicks it will go into $scope.countClicker in the controller where it will count the number of times the button has been clicked. The number of times it being clicked will associate the city name it will pass through to the Data factory. Then from the data from the Data factory it will create a panel as shown in directive.js

My problem is once I click more than once, all the expressions that SHOULD be unique turn to be the same. For example, $scope.name3 should only show "Osaka", but the previous 3 panels which all should have unique ID from my for loop ($scope.name0, $scope.name1, $scope.name2) all have "Osaka" as their title as well. I originally planned that the number of clicks could be used as an unique ID so each panel wouldn't clash with each other, but for some reason it is.

If anyone can please help point out why this is happening that would be greatly appreciated. Thank you!

directive.js:

```<code>app.directive('addbuttonsbutton', function() {
    return {
        restrict: "A",
        template: "<md-button addbuttons ng-click='clickCounter()' class='md-fab md-mini'>+</md-button>"
    }
});

//Directive for adding buttons on click that show an alert on click

 app.directive('addbuttons', function($compile) {
     return function(scope, element, attrs) {
         element.bind("click", function() {
             scope.count++;
             var counter = scope.count;
             console.log('this is scope count' + scope.count);
             angular.element(document.getElementById('space-for-buttons')).prepend($compile( //adding a panel to my view
                 "<div class= panel>" +
                 "<h3 id=title" + scope.count + ">{{name" + scope.count + "| uppercase}}</h3><br>" +
                 "<i ng-class=weatherClass id=icon></i>" +
                 "<h3 id= temp >{{fTemp" + scope.count + " | uppercase}}</h3>" +
                 "<p style= 'color: #FAFAFA;' >{{description" + scope.count + "| uppercase}}</p>" +
                 "<p>{{location}}</p><br>" +
                 "<div id= wrapper ><div id= first ><i id= smallIcons  class= 'wi wi-horizon-alt' ></i>" +
                 "<p id= eventID >SUNRISE</p><p id= subID >{{formattedSunrise" + scope.count + "}}</p></div>" +
                 "<div id= second ><i class=  'wi wi-strong-wind'  id= smallIcons ></i>" +
                 "<p id= eventID >WIND</p><p id= subID >{{speed" + scope.count + "}}</p></div>" +
                 "<div id= third ><i class=  'wi wi-humidity'  id= smallIcons ></i>" +
                 "<p id= eventID >HUMIDITY</p><p id= subID >{{humidity}}</p></div></div></div>")(scope));
         });
     };
 });
</code>```

Controller:

```<code>var app = angular.module('weatherApp.controllers', []);

app.controller('weatherCtrl', ['$scope', 'Data',

        function($scope, Data) {
            $scope.count = -1;

            $scope.city = 'Berkeley';
            var cityCounting = 0;
            var counter = 0;

            var cities = [
          'Sydney, AU',
          'Melbourne, AU',
          'Tokyo',
          'Osaka',
          'Seoul',
          'Hong Kong',
          'London',
          'Amsterdam',
          'Berlin',
          'Paris',
          'Barcelona',
          'New York',
          'Dubai',
          'Antarctica'
        ];

            $scope.clickCounter = function(){
                cityCounting = counter++;
                $scope.city = cities[cityCounting];
                console.log($scope.city);
                console.log(cityCounting);
               Data.getApps($scope.city).then(function(data) {

             for (var i = 0; i < 14; i++) {
                $scope.data = data;

                $scope['name' + i] = data.name;

                $scope['temp'+i] = data.main.temp;

                $scope['fTemp' + i ] = ($scope['temp' + i] * (9 / 5) - 459.67).toFixed(1) + " °F";
            }//end of for loop

            }); end of Data service
            }//end of controller
</code>```

答:
I realized my error was the for loop. In the for loop it was iterating 14 times and thus $scope.name[0-13] and all the other variables are firing per click, which is why all the panels were the same.

But with Vivz's help, I ditched the for loop and used my "cityCounter" variable instead.

Body:
I have a button formed from my custom directive where once the user clicks it will go into $scope.countClicker in the controller where it will count the number of times the button has been clicked. The number of times it being clicked will associate the city name it will pass through to the Data factory. Then from the data from the Data factory it will create a panel as shown in directive.js

My problem is once I click more than once, all the expressions that SHOULD be unique turn to be the same. For example, $scope.name3 should only show "Osaka", but the previous 3 panels which all should have unique ID from my for loop ($scope.name0, $scope.name1, $scope.name2) all have "Osaka" as their title as well. I originally planned that the number of clicks could be used as an unique ID so each panel wouldn't clash with each other, but for some reason it is.

If anyone can please help point out why this is happening that would be greatly appreciated. Thank you!

directive.js:

app.directive('addbuttonsbutton', function() {
    return {
        restrict: "A",
        template: "<md-button addbuttons ng-click='clickCounter()' class='md-fab md-mini'>+</md-button>"
    }
});

//Directive for adding buttons on click that show an alert on click

 app.directive('addbuttons', function($compile) {
     return function(scope, element, attrs) {
         element.bind("click", function() {
             scope.count++;
             var counter = scope.count;
             console.log('this is scope count' + scope.count);
             angular.element(document.getElementById('space-for-buttons')).prepend($compile( //adding a panel to my view
                 "
" +
                 "
{{name" + scope.count + "| uppercase}}

" +
                 "" +
                 "
{{fTemp" + scope.count + " | uppercase}}
" +
                 "
{{description" + scope.count + "| uppercase}}
" +
                 "
{{location}}

" +
                 "

" +
                 "
SUNRISE

{{formattedSunrise" + scope.count + "}}

" +
                 "
" +
                 "
WIND

{{speed" + scope.count + "}}

" +
                 "
" +
                 "
HUMIDITY

{{humidity}}

")(scope));
         });
     };
 });

Controller:

var app = angular.module('weatherApp.controllers', []);

app.controller('weatherCtrl', ['$scope', 'Data',

        function($scope, Data) {
            $scope.count = -1;

            $scope.city = 'Berkeley';
            var cityCounting = 0;
            var counter = 0;

            var cities = [
          'Sydney, AU',
          'Melbourne, AU',
          'Tokyo',
          'Osaka',
          'Seoul',
          'Hong Kong',
          'London',
          'Amsterdam',
          'Berlin',
          'Paris',
          'Barcelona',
          'New York',
          'Dubai',
          'Antarctica'
        ];

            $scope.clickCounter = function(){
                cityCounting = counter++;
                $scope.city = cities[cityCounting];
                console.log($scope.city);
                console.log(cityCounting);
               Data.getApps($scope.city).then(function(data) {

             for (var i = 0; i < 14; i++) {
                $scope.data = data;

                $scope['name' + i] = data.name;

                $scope['temp'+i] = data.main.temp;

                $scope['fTemp' + i ] = ($scope['temp' + i] * (9 / 5) - 459.67).toFixed(1) + " °F";
            }//end of for loop

            }); end of Data service
            }//end of controller