问:
Trouble getting a new activity to pop up on notification click
So I want to make this application that receives SMS texts, and when it does, it displays a notification, and when the user clicks on it, a new activity is popped up with the SMS message. So I have most if it done like the BroadcastReceiver class which works in receiving SMS texts and it displays a notification all fine and dandy.

```<code>public class SMSReceiver extends BroadcastReceiver {

    static final int notificationId = 1;

    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String message = currentMessage.getDisplayMessageBody();
                    newNotification(context, phoneNumber, message);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void newNotification(Context context, String title, String text) {

        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notifyIntent = new Intent(context, NotificationActivity.class);
        notifyIntent.putExtra("SMSText", text);
        notifyIntent.setAction(text);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentIntent(contentIntent)
                .setContentText(text)
                .setContentTitle(title)
                .setTicker(text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notifyMgr.notify(notificationId, notification);

    }

}
</code>```

The only problem is when I click on the notification. The first time it works perfectly, the NotificationActivity class pops up displaying the SMS message. But after that, the information never updates. I assume the app realizes that it already has NotificationActivity open, so it doesn't open another one. Even though I properly add the flag FLAG_ACTIVITY_NEW_TASK when I create the new notification. Also here is my NotificationActivity class

```<code>public class NotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                newString = null;
            } else {
                newString = extras.getString("SMSText");
            }
        } else {
            newString = (String) savedInstanceState.getSerializable("SMSText");
        }

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(newString);

    }
}
</code>```

I also do have a launcher activity, MainActivity, but felt it was unnecessary to show because all it does is register the SMSReceiver. Any help would be greatly appreciated, thanks!

答:
You can try overriding the method onNewIntent it is called whenever a new Intent is sent to the same Activity the original Intent will be kept using the getIntent method but this one will be called whenever there is a new Intent.

```<code>@Override
protected void onNewIntent(Intent intent)
{
    //Do what you want to do with this new Intent here!
}
</code>```

Body:
So I want to make this application that receives SMS texts, and when it does, it displays a notification, and when the user clicks on it, a new activity is popped up with the SMS message. So I have most if it done like the BroadcastReceiver class which works in receiving SMS texts and it displays a notification all fine and dandy.

public class SMSReceiver extends BroadcastReceiver {

    static final int notificationId = 1;

    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String message = currentMessage.getDisplayMessageBody();
                    newNotification(context, phoneNumber, message);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void newNotification(Context context, String title, String text) {

        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notifyIntent = new Intent(context, NotificationActivity.class);
        notifyIntent.putExtra("SMSText", text);
        notifyIntent.setAction(text);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentIntent(contentIntent)
                .setContentText(text)
                .setContentTitle(title)
                .setTicker(text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notifyMgr.notify(notificationId, notification);

    }

}

The only problem is when I click on the notification. The first time it works perfectly, the NotificationActivity class pops up displaying the SMS message. But after that, the information never updates. I assume the app realizes that it already has NotificationActivity open, so it doesn't open another one. Even though I properly add the flag FLAG_ACTIVITY_NEW_TASK when I create the new notification. Also here is my NotificationActivity class

public class NotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if (extras == null) {
                newString = null;
            } else {
                newString = extras.getString("SMSText");
            }
        } else {
            newString = (String) savedInstanceState.getSerializable("SMSText");
        }

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(newString);

    }
}

I also do have a launcher activity, MainActivity, but felt it was unnecessary to show because all it does is register the SMSReceiver. Any help would be greatly appreciated, thanks!

Body:
You can try overriding the method onNewIntent it is called whenever a new Intent is sent to the same Activity the original Intent will be kept using the getIntent method but this one will be called whenever there is a new Intent.

@Override
protected void onNewIntent(Intent intent)
{
    //Do what you want to do with this new Intent here!
}


来源: stackexchange

问:
Webforms - RadiobuttonLists client side click event not working
I have a server side RadioButtonList control that renders client side code as below. As you can see, I have attached client side javascript to show an alert when any of the radio buttons are clicked. This is in line with the examples I saw online. However, the alert doesn't show when I click any radio button. The console doesnt show any errors either. What could be wrong? I can only use pure javascript and not jQuery. I am running this in the latest Chrome browser.

```<code><span id="ctl00_ContentPlaceHolder1_rblApartmentType">
    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_0" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="1" onclick="javascript:alert('1');">
    <label for="ctl00_ContentPlaceHolder1_rblApartmentType_0">Apartment</label>
    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_1" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="2" onclick="javascript:alert('2');">
    <label for="ctl00_ContentPlaceHolder1_rblApartmentType_1">Town Home</label>
    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_2" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="3" checked="checked" onclick="javascript:alert('3');">
    <label for="ctl00_ContentPlaceHolder1_rblApartmentType_2">Condo</label>
</span>
</code>```

答:
not necessarily an answer, but for viewing, cuz there's s/t weird with the op's rendering:

page:

```<code><asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem Text="a" Value="1" onclick="alert('1');"></asp:ListItem>
    <asp:ListItem Text="b" Value="2" onclick="alert('2');"></asp:ListItem>
</asp:RadioButtonList>
</code>```

renders as:

```<code><table id="RadioButtonList1">
  <tbody>
    <tr>
      <td>
        <input id="RadioButtonList1_0" type="radio"
          name="ctl00$MainContent$RadioButtonList1" value="1" onclick="alert('1');">
        <label for="RadioButtonList1_0">a</label></td>
    </tr>
    <tr>
      <td>
        <input id="RadioButtonList1_1" type="radio"
          name="ctl00$MainContent$RadioButtonList1" value="2" onclick="alert('2');">
        <label for="RadioButtonList1_1">b</label></td>
    </tr>
  </tbody>
</table>
</code>```

note, i also use this in web.config so the IDs aren't so crazy when rendered (gets rid of a lot of stuff like ctl00$...:

```<code><system.web>
  <pages clientIDMode="Static">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a server side RadioButtonList control that renders client side code as below. As you can see, I have attached client side javascript to show an alert when any of the radio buttons are clicked. This is in line with the examples I saw online. However, the alert doesn't show when I click any radio button. The console doesnt show any errors either. What could be wrong? I can only use pure javascript and not jQuery. I am running this in the latest Chrome browser.

    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_0" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="1" onclick="javascript:alert('1');">
    Apartment
    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_1" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="2" onclick="javascript:alert('2');">
    Town Home
    <input id="ctl00_ContentPlaceHolder1_rblApartmentType_2" type="radio" name="ctl00$ContentPlaceHolder1$rblApartmentType" value="3" checked="checked" onclick="javascript:alert('3');">
    Condo

Body:
not necessarily an answer, but for viewing, cuz there's s/t weird with the op's rendering:

page:

<asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem Text="a" Value="1" onclick="alert('1');"></asp:ListItem>
    <asp:ListItem Text="b" Value="2" onclick="alert('2');"></asp:ListItem>
</asp:RadioButtonList>

renders as:

<table id="RadioButtonList1">
  <tbody>
    <tr>
      <td>
        <input id="RadioButtonList1_0" type="radio"
          name="ctl00$MainContent$RadioButtonList1" value="1" onclick="alert('1');">
        <label for="RadioButtonList1_0">a</label></td>
    </tr>
    <tr>
      <td>
        <input id="RadioButtonList1_1" type="radio"
          name="ctl00$MainContent$RadioButtonList1" value="2" onclick="alert('2');">
        <label for="RadioButtonList1_1">b</label></td>
    </tr>
  </tbody>
</table>

note, i also use this in web.config so the IDs aren't so crazy when rendered (gets rid of a lot of stuff like ctl00$...:

<system.web>
  <pages clientIDMode="Static">


问:
Pact - matching an array of integers
I'm using Pact and creating consumer tests. My response body for a specific request looks like:

```<code>PactDslJsonBody responseBody = new PactDslJsonBody()
                .stringType("response","success")
                .array("accounts")
                    .integerType()
                .closeArray()
                .asBody();
</code>```

I want to modify this so it returns an array of random integers (not objects) with 10 or less elements (now it only returns one and provider expects to match only one). Is this possible?

答: Random numbers are not recommended, as it means that when you publish a pact, it will change every time you publish, and you won't get the benefits of "pre-verification" as described in the Pact Broker wiki here: https://github.com/pact-foundation/pact_broker/wiki/Provider-verification-results#querying</p>

Title: Pact - matching an array of integers

Body:
I'm using Pact and creating consumer tests. My response body for a specific request looks like:

PactDslJsonBody responseBody = new PactDslJsonBody()
                .stringType("response","success")
                .array("accounts")
                    .integerType()
                .closeArray()
                .asBody();

I want to modify this so it returns an array of random integers (not objects) with 10 or less elements (now it only returns one and provider expects to match only one). Is this possible?


问:
How to adjust UIToolBar left and right padding
I create one UIToolbar with code and another with interface builder. But, found out the two toolbar having different left and right padding which shown below:

From Interface Builder:

From Code:

```<code>UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTest setTitle:@"Back" forState:UIControlStateNormal];
[btnTest.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
[btnTest setBackgroundImage:[imgToolbarButton stretchableImageWithLeftCapWidth:5 topCapHeight:0]  forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(clearDateEdit:) forControlEvents:UIControlEventTouchUpInside];
btnTest.frame = CGRectMake(0.0, 0.0, 50, 30);
UIBarButtonItem *btnTestItem = [[UIBarButtonItem alloc] initWithCustomView:btnTest];
[self.toolbar setItems:[NSArray arrayWithObjects:btnTestItem,nil]];
[btnTestItem release];
</code>```

My question is how can I adjust the left and right padding of UIToolbar by code?

Update

I discovered this alignment issue only happen to UIBarButtonItem with customView of UIButton, the alignment is fine with UIBarButtonItem. Any idea what cause this or to resolve this.

The only solution I can think of right now is to manually set the frame.

答:
I think a tricky way is to use Aspects (or method swizzling),as blew:</p>

```<code>[UINavigationBar aspect_hookSelector:@selector(layoutSubviews) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
        UINavigationBar *bar = info.instance;

        //[bar layoutSubviews];

        if ([bar isKindOfClass:[UINavigationBar class]]) {
            if (@available(iOS 11, *)) {
                bar.layoutMargins = UIEdgeInsetsZero;

                for (UIView *subview in bar.subviews) {
                    if ([NSStringFromClass([subview class]) containsString:@"ContentView"]) {
                        UIEdgeInsets oEdges = subview.layoutMargins;
                        subview.layoutMargins = UIEdgeInsetsMake(0, 0, 0, oEdges.right);
                    }
                }
            }
        }
    } error:nil];
</code>```

Body:
I create one UIToolbar with code and another with interface builder. But, found out the two toolbar having different left and right padding which shown below:

From Interface Builder:

From Code:

UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTest setTitle:@"Back" forState:UIControlStateNormal];
[btnTest.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
[btnTest setBackgroundImage:[imgToolbarButton stretchableImageWithLeftCapWidth:5 topCapHeight:0]  forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(clearDateEdit:) forControlEvents:UIControlEventTouchUpInside];
btnTest.frame = CGRectMake(0.0, 0.0, 50, 30);
UIBarButtonItem *btnTestItem = [[UIBarButtonItem alloc] initWithCustomView:btnTest];
[self.toolbar setItems:[NSArray arrayWithObjects:btnTestItem,nil]];
[btnTestItem release];

My question is how can I adjust the left and right padding of UIToolbar by code?

Update

I discovered this alignment issue only happen to UIBarButtonItem with customView of UIButton, the alignment is fine with UIBarButtonItem. Any idea what cause this or to resolve this.

The only solution I can think of right now is to manually set the frame.

Body:
I think a tricky way is to use Aspects (or method swizzling),as blew:

[UINavigationBar aspect_hookSelector:@selector(layoutSubviews) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
        UINavigationBar *bar = info.instance;

        //[bar layoutSubviews];

        if ([bar isKindOfClass:[UINavigationBar class]]) {
            if (@available(iOS 11, *)) {
                bar.layoutMargins = UIEdgeInsetsZero;

                for (UIView *subview in bar.subviews) {
                    if ([NSStringFromClass([subview class]) containsString:@"ContentView"]) {
                        UIEdgeInsets oEdges = subview.layoutMargins;
                        subview.layoutMargins = UIEdgeInsetsMake(0, 0, 0, oEdges.right);
                    }
                }
            }
        }
    } error:nil];


问:
Compare if two variables reference the same object in python
How to check whether two variables reference the same object?</p>

```<code>x = ['a', 'b', 'c']
y = x                 # x and y reference the same object
z = ['a', 'b', 'c']   # x and z reference different objects
</code>```

答:
I really like to have a visual feedback, that's why I sometimes  just open up http://www.pythontutor.com/visualize.html#mode=edit to see how the memory is allocated and what is referencing what.

Added this awesome gif as this reply is about visualizing..

Body:
How to check whether two variables reference the same object?

x = ['a', 'b', 'c']
y = x                 # x and y reference the same object
z = ['a', 'b', 'c']   # x and z reference different objects


问:
How to POST a String having length of more than 80k
I am trying to send two images with some related string data. Images are in form of Base64 string. Total length of the parameters are about 81000

here is my code:

```<code> HttpPost post = new HttpPost(postURL);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            entityBuilder.addPart("uname", new StringBody(GlobalUname, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("pwd", new StringBody(GlobalPassword, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("imeino", new StringBody(IMEINumber, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("role", new StringBody(role_code, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("filexml", new StringBody(Msr_encryXmlFile, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("img1", new StringBody(images.get(0), ContentType.TEXT_PLAIN));
            entityBuilder.addPart("img2", new StringBody(images.get(1), ContentType.TEXT_PLAIN));

            HttpEntity entity = entityBuilder.build();

            post.setEntity(entity);
            HttpResponse responsePOST = client.execute(post);
</code>```

But i am getting "" (blank string) as response.
I tried these images to send as FileBody but still i am getting the same.

The above code works perfect with single image.

I tried with HttpUrlConnection

like this:

```<code>URL url = new URL(postURL);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            http.setRequestMethod("POST");
            http.setInstanceFollowRedirects(false);
            http.setDoOutput(false);
            Map<String,String> arguments = new HashMap<>();
            arguments.put("uname", GlobalUname);
            arguments.put("pwd", GlobalPassword);
            arguments.put("imeino", IMEINumber);
            arguments.put("role", role_code);
            arguments.put("filexml", Msr_encryXmlFile);
            arguments.put("img1", imagePath.get(0));
            arguments.put("img2", imagePath.get(1));
            StringBuilder strBuilder = new StringBuilder("&");
            for(Map.Entry<String,String> entry : arguments.entrySet())
                strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
            byte[] out = strBuilder.toString().getBytes(Charset.forName("UTF-8"));
            int length = out.length;

            http.setFixedLengthStreamingMode(length);
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.connect();
            /*PrintWriter printWriter = new PrintWriter(http.getOutputStream());
            printWriter.print(out);
            printWriter.close();*/
            http.getOutputStream().write(out);

int code = http.getResponseCode();
            String msg = http.getResponseMessage();

            Reader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));
</code>```

I am getting status code 400 as Bad Request.

how to get it done.

here is my server code:

```<code>Public Function getMustrollNew() As System.Xml.XmlElement Implements Imustroll.getMustrollNew
        Dim uname, finyear As String
        check = New HandheldErrorLOg
        download_id = Guid.NewGuid()

        Try

            Dim con1 As String

            finyear = HttpContext.Current.Request.Form("finyear")

            uname = HttpContext.Current.Request.Form("uname")
            'pwd = mps.decrypt(Split(mps.decrypt(HttpContext.Current.Request.Form("pwd")), "||")(0))
            pwd = HttpContext.Current.Request.Form("pwd")
            Dim image1 as String = HttpContext.Current.Request.Form("img1")
            Dim image2 as String = HttpContext.Current.Request.Form("img2")
            imeino = mps.decrypt(HttpContext.Current.Request.Form("imeino"))

'Rest of code
        End Function
</code>```

答:
I also faced the same issue when I sent 3 images. Then now I fixed this issue.

First, check database field size. if the size of the field is smaller than Base64 string it will create the problem.

In my case, I used my moto g4 plus mobile to take images. when I take an image the size of an image is nearly 5MB. So, Base64 String gives a string length nearly 72,00,000. It is very big size. So. I could not successfully send the 3 images to the server. Then I reduced the image size to 250 kb. So, Base64 String gives a string length nearly 50k. It is a very big difference. After that, I can upload 3 images at a time successfully

Try the below code and let me know still you are facing the issue.

```<code>public static File file = null;
int TAKE_PICTURE = 1;
public static Uri imageUri;

private void cameraActivity(){

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
    Date now = new Date();
    String fileName = formatter.format(now) + ".JPEG";

    Intent intentCamera = new Intent("android.media.action.IMAGE_CAPTURE");
    file = new File(Environment.getExternalStorageDirectory()+"/folder/", fileName);
    imageUri = Uri.fromFile(file);
    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intentCamera, TAKE_PICTURE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentFromCamera) {
    super.onActivityResult(requestCode, resultCode, intentFromCamera);

    if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {

        if(file.exists()) {

            ExifInterface oldExif = null;
            String OldExifOrientation = null;
            try {
                oldExif = new ExifInterface(file.getAbsolutePath());
                OldExifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);

            } catch (IOException e) {
                e.printStackTrace();
            }
            scaleDown(BitmapFactory.decodeFile(file.getAbsolutePath()), 400, true);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);

            if (OldExifOrientation != null) {
                try {
                    ExifInterface newExif = new ExifInterface(file.getAbsolutePath());
                    newExif.setAttribute(ExifInterface.TAG_ORIENTATION, OldExifOrientation);
                    newExif.saveAttributes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            sendImageRequest();
        }
    }
}

private void sendImageRequest() {

    String encodedImage = "";
    if(file!=null) {
        if(file.exists()){

            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
            byte[] b = baos.toByteArray();

            encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("path : ", "--" + file.getPath());
            Log.e("name : ", "--" + file.getName());
            Log.e("AbsolutePath : ", "--" + file.getAbsolutePath());
            Log.e("length : ", "--" + encodedImage.length());
        }
    }

    **//your server request code here**
}

public Bitmap scaleDown(Bitmap realImage, float maxImageSize,
                        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    saveToInternalStorage(newBitmap);
    return newBitmap;
}

private String saveToInternalStorage(Bitmap bitmapImage){

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file.getAbsolutePath();
}
</code>```

Body:
I am trying to send two images with some related string data. Images are in form of Base64 string. Total length of the parameters are about 81000

here is my code:

 HttpPost post = new HttpPost(postURL);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            entityBuilder.addPart("uname", new StringBody(GlobalUname, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("pwd", new StringBody(GlobalPassword, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("imeino", new StringBody(IMEINumber, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("role", new StringBody(role_code, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("filexml", new StringBody(Msr_encryXmlFile, ContentType.TEXT_PLAIN));
            entityBuilder.addPart("img1", new StringBody(images.get(0), ContentType.TEXT_PLAIN));
            entityBuilder.addPart("img2", new StringBody(images.get(1), ContentType.TEXT_PLAIN));

            HttpEntity entity = entityBuilder.build();

            post.setEntity(entity);
            HttpResponse responsePOST = client.execute(post);

But i am getting "" (blank string) as response.
I tried these images to send as FileBody but still i am getting the same.

The above code works perfect with single image.

I tried with HttpUrlConnection

like this:

URL url = new URL(postURL);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            http.setRequestMethod("POST");
            http.setInstanceFollowRedirects(false);
            http.setDoOutput(false);
            Map<String,String> arguments = new HashMap<>();
            arguments.put("uname", GlobalUname);
            arguments.put("pwd", GlobalPassword);
            arguments.put("imeino", IMEINumber);
            arguments.put("role", role_code);
            arguments.put("filexml", Msr_encryXmlFile);
            arguments.put("img1", imagePath.get(0));
            arguments.put("img2", imagePath.get(1));
            StringBuilder strBuilder = new StringBuilder("&");
            for(Map.Entry<String,String> entry : arguments.entrySet())
                strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
            byte[] out = strBuilder.toString().getBytes(Charset.forName("UTF-8"));
            int length = out.length;

            http.setFixedLengthStreamingMode(length);
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.connect();
            /*PrintWriter printWriter = new PrintWriter(http.getOutputStream());
            printWriter.print(out);
            printWriter.close();*/
            http.getOutputStream().write(out);

int code = http.getResponseCode();
            String msg = http.getResponseMessage();

            Reader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));

I am getting status code 400 as Bad Request.

how to get it done.

here is my server code:

Public Function getMustrollNew() As System.Xml.XmlElement Implements Imustroll.getMustrollNew
        Dim uname, finyear As String
        check = New HandheldErrorLOg
        download_id = Guid.NewGuid()

        Try

            Dim con1 As String

            finyear = HttpContext.Current.Request.Form("finyear")

            uname = HttpContext.Current.Request.Form("uname")
            'pwd = mps.decrypt(Split(mps.decrypt(HttpContext.Current.Request.Form("pwd")), "||")(0))
            pwd = HttpContext.Current.Request.Form("pwd")
            Dim image1 as String = HttpContext.Current.Request.Form("img1")
            Dim image2 as String = HttpContext.Current.Request.Form("img2")
            imeino = mps.decrypt(HttpContext.Current.Request.Form("imeino"))

'Rest of code
        End Function

Body:
I also faced the same issue when I sent 3 images. Then now I fixed this issue.

First, check database field size. if the size of the field is smaller than Base64 string it will create the problem.

In my case, I used my moto g4 plus mobile to take images. when I take an image the size of an image is nearly 5MB. So, Base64 String gives a string length nearly 72,00,000. It is very big size. So. I could not successfully send the 3 images to the server. Then I reduced the image size to 250 kb. So, Base64 String gives a string length nearly 50k. It is a very big difference. After that, I can upload 3 images at a time successfully

Try the below code and let me know still you are facing the issue.

public static File file = null;
int TAKE_PICTURE = 1;
public static Uri imageUri;

private void cameraActivity(){

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
    Date now = new Date();
    String fileName = formatter.format(now) + ".JPEG";

    Intent intentCamera = new Intent("android.media.action.IMAGE_CAPTURE");
    file = new File(Environment.getExternalStorageDirectory()+"/folder/", fileName);
    imageUri = Uri.fromFile(file);
    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intentCamera, TAKE_PICTURE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentFromCamera) {
    super.onActivityResult(requestCode, resultCode, intentFromCamera);

    if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {

        if(file.exists()) {

            ExifInterface oldExif = null;
            String OldExifOrientation = null;
            try {
                oldExif = new ExifInterface(file.getAbsolutePath());
                OldExifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);

            } catch (IOException e) {
                e.printStackTrace();
            }
            scaleDown(BitmapFactory.decodeFile(file.getAbsolutePath()), 400, true);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);

            if (OldExifOrientation != null) {
                try {
                    ExifInterface newExif = new ExifInterface(file.getAbsolutePath());
                    newExif.setAttribute(ExifInterface.TAG_ORIENTATION, OldExifOrientation);
                    newExif.saveAttributes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            sendImageRequest();
        }
    }
}

private void sendImageRequest() {

    String encodedImage = "";
    if(file!=null) {
        if(file.exists()){

            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
            byte[] b = baos.toByteArray();

            encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("path : ", "--" + file.getPath());
            Log.e("name : ", "--" + file.getName());
            Log.e("AbsolutePath : ", "--" + file.getAbsolutePath());
            Log.e("length : ", "--" + encodedImage.length());
        }
    }

    **//your server request code here**
}

public Bitmap scaleDown(Bitmap realImage, float maxImageSize,
                        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    saveToInternalStorage(newBitmap);
    return newBitmap;
}

private String saveToInternalStorage(Bitmap bitmapImage){

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file.getAbsolutePath();
}


问:
Obj-C - TableView scroll to bottom after data reloaded?
I'm trying to have my tableview scroll to the bottom after new data is loaded. For example I have a chat window that is loading new messages once my 'sendReply' button is pressed, and I always want it to scroll to the most recent message (at the bottom) when data is posted. For some reason, my tableView won't scroll to the bottom after self.tableview reload?

I assume this is because of rowNumber-1 in my method, but when I try to change this to -0, I get the error:

Terminating app due to uncaught exception 'NSRangeException', reason:
  '-[UITableView
  _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]:
  row (16) beyond bounds (16) for section (0).'

ViewController.m

```<code>- (void)scrollTableToBottom {
    NSInteger rowNumber = [self. tableView numberOfRowsInSection:0];
    if (rowNumber > 0) {
        [self. tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rowNumber-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (IBAction)sendReply:(id)sender {

    if ([self.messageData count] > 0) {

        self.sendButton.hidden = YES;

        self.activityIndicator.hidden = NO;
        [self.activityIndicator startAnimating];

    NSMutableDictionary *nodeData = [NSMutableDictionary new];

    [nodeData setObject:@"messages" forKey:@"type"];

    NSDictionary *messageValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.replyField.text, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *finalMessage = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:messageValues] forKey:@"und"];

    [nodeData setObject:finalMessage forKey:@"body"];

   NSString *otherUID = [self.messageData objectForKey:@"uid"];

    NSString *userValue = otherUID;

    NSDictionary *targetMessage = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:userValue, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *finalUser = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:targetMessage] forKey:@"und"];

    [nodeData setObject:finalUser forKey:@"field_targetuser"];

    [nodeData setValue: @"Re:" forKey:@"title"];

        NSDictionary *userDictInfo = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"diosSession"]];

        DIOSSession *session = [DIOSSession sharedSession];
        [session setUser:userDictInfo];

        [session user];

    NSString *uid = [session user][@"user"][@"uid"];

    [DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {

           self.replyField.text = @"";
            [self.tableView reloadData];
             [self scrollTableToBottom];
             self.sendButton.hidden = NO;
             [self.activityIndicator stopAnimating];
             self.activityIndicator.hidden = YES;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Node did not save!");
    }];

    } else if ([self.messageDataFriends count] > 0) {

        self.sendButton.hidden = YES;

        self.activityIndicator.hidden = NO;
        [self.activityIndicator startAnimating];

        NSMutableDictionary *nodeData = [NSMutableDictionary new];

        [nodeData setObject:@"messages" forKey:@"type"];

        NSDictionary *messageValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.replyField.text, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
        NSDictionary *finalMessage = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:messageValues] forKey:@"und"];

        [nodeData setObject:finalMessage forKey:@"body"];

        NSString *otherUID = [self.messageDataFriends objectForKey:@"uid2"];

        NSString *userValue = otherUID;

        NSDictionary *targetMessage = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:userValue, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
        NSDictionary *finalUser = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:targetMessage] forKey:@"und"];

        [nodeData setObject:finalUser forKey:@"field_targetuser"];

        [nodeData setValue: @"Re:" forKey:@"title"];

        NSString *uid = [[[DIOSSession sharedSession] user] objectForKey:@"uid"];

        [DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {

            dispatch_async(dispatch_get_main_queue(), ^{

                self.replyField.text = @"";

                [self.tableView reloadData];
                       [self scrollTableToBottom];
                self.sendButton.hidden = NO;
                 [self.activityIndicator stopAnimating];
                self.activityIndicator.hidden = YES;

            });

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Node did not save!");
        }];

    }

}
</code>```

答:
Add to the first block

```<code>dispatch_async(dispatch_get_main_queue(), ^{
    self.replyField.text = @"";
    [self.tableView reloadData];
    [self scrollTableToBottom];
    self.sendButton.hidden = NO;
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
});
</code>```

Also add NSLog(@"rowNumber = %lu",rowNumber); after NSInteger
rowNumber = [self.tableView numberOfRowsInSection:0]; in
scrollTableToBottom method. And before [self.tableView reloadData];
If they are equal, this means that the data have not been reloaded yet.

Body:
I'm trying to have my tableview scroll to the bottom after new data is loaded. For example I have a chat window that is loading new messages once my 'sendReply' button is pressed, and I always want it to scroll to the most recent message (at the bottom) when data is posted. For some reason, my tableView won't scroll to the bottom after self.tableview reload?

I assume this is because of rowNumber-1 in my method, but when I try to change this to -0, I get the error:

Terminating app due to uncaught exception 'NSRangeException', reason:
  '-[UITableView
  _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]:
  row (16) beyond bounds (16) for section (0).'

ViewController.m

- (void)scrollTableToBottom {
    NSInteger rowNumber = [self. tableView numberOfRowsInSection:0];
    if (rowNumber > 0) {
        [self. tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rowNumber-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (IBAction)sendReply:(id)sender {

    if ([self.messageData count] > 0) {

        self.sendButton.hidden = YES;

        self.activityIndicator.hidden = NO;
        [self.activityIndicator startAnimating];

    NSMutableDictionary *nodeData = [NSMutableDictionary new];

    [nodeData setObject:@"messages" forKey:@"type"];

    NSDictionary *messageValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.replyField.text, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *finalMessage = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:messageValues] forKey:@"und"];

    [nodeData setObject:finalMessage forKey:@"body"];

   NSString *otherUID = [self.messageData objectForKey:@"uid"];

    NSString *userValue = otherUID;

    NSDictionary *targetMessage = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:userValue, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *finalUser = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:targetMessage] forKey:@"und"];

    [nodeData setObject:finalUser forKey:@"field_targetuser"];

    [nodeData setValue: @"Re:" forKey:@"title"];

        NSDictionary *userDictInfo = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"diosSession"]];

        DIOSSession *session = [DIOSSession sharedSession];
        [session setUser:userDictInfo];

        [session user];

    NSString *uid = [session user][@"user"][@"uid"];

    [DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {

           self.replyField.text = @"";
            [self.tableView reloadData];
             [self scrollTableToBottom];
             self.sendButton.hidden = NO;
             [self.activityIndicator stopAnimating];
             self.activityIndicator.hidden = YES;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Node did not save!");
    }];

    } else if ([self.messageDataFriends count] > 0) {

        self.sendButton.hidden = YES;

        self.activityIndicator.hidden = NO;
        [self.activityIndicator startAnimating];

        NSMutableDictionary *nodeData = [NSMutableDictionary new];

        [nodeData setObject:@"messages" forKey:@"type"];

        NSDictionary *messageValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.replyField.text, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
        NSDictionary *finalMessage = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:messageValues] forKey:@"und"];

        [nodeData setObject:finalMessage forKey:@"body"];

        NSString *otherUID = [self.messageDataFriends objectForKey:@"uid2"];

        NSString *userValue = otherUID;

        NSDictionary *targetMessage = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:userValue, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
        NSDictionary *finalUser = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:targetMessage] forKey:@"und"];

        [nodeData setObject:finalUser forKey:@"field_targetuser"];

        [nodeData setValue: @"Re:" forKey:@"title"];

        NSString *uid = [[[DIOSSession sharedSession] user] objectForKey:@"uid"];

        [DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {

            dispatch_async(dispatch_get_main_queue(), ^{

                self.replyField.text = @"";

                [self.tableView reloadData];
                       [self scrollTableToBottom];
                self.sendButton.hidden = NO;
                 [self.activityIndicator stopAnimating];
                self.activityIndicator.hidden = YES;

            });

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Node did not save!");
        }];

    }

}

Body:
Add to the first block

dispatch_async(dispatch_get_main_queue(), ^{
    self.replyField.text = @"";
    [self.tableView reloadData];
    [self scrollTableToBottom];
    self.sendButton.hidden = NO;
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
});

Also add NSLog(@"rowNumber = %lu",rowNumber); after NSInteger
rowNumber = [self.tableView numberOfRowsInSection:0]; in
scrollTableToBottom method. And before [self.tableView reloadData];
If they are equal, this means that the data have not been reloaded yet.


问:
logger printing same statement random number of times or not at all
I have python logger being defined in the global part of a python script like so:

```<code>import logging
import logging.handlers

FORMAT = '%(asctime)-15s %(threadName)s %(levelname)s %(message)s'
logfile = app.config['CONTROLROOM_WORKER_LOG_PATH']
loghandler = logging.handlers.TimedRotatingFileHandler(logfile, when='midnight', interval=1, backupCount=10, encoding=None, delay=False, utc=False)
fmt = logging.Formatter(FORMAT)
loghandler.setFormatter(fmt)
logger = logging.getLogger('controlroom_worker')
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)
</code>```

However issues I'm facing are the following:

Sometimes a logger statement prior to some logic is ignored (that is, not logged), even though the logic is executed. This behavior is amplified when a lot of stuff needs to be printed.

90% percent of the times, everything that is printed, is printed twice! Although I have seen a few cases where something is printed 3 times. Example logging:

2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.
```

<p>See how stuff is being printed twice or thrice?</p>

<p>Here's something interesting:</p>

<p>In addition to using the <code>logging</code> package, I also tried logging by simply writing to a file and writing to it whenever a log is needed:</p>

```manual_logger=open("manual_log.txt", "a+")
manual_logger.write("Some message here" + "\n")
```

<p>This manual logger always writes each log statement just <em>once</em> (as is to be expected), but <em>also</em> suffers from some logs being completely missed out randomly:</p>

<pre class="lang-none prettyprint-override"><code>Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
</code>```

How do I solve these issues? They're driving me mad.

答: Try ensuring that the logging configuration code is called only from a if __name__ == '__main__': clause in your main script, and nowhere else. In particular, it shouldn't be called just when a module is imported, only when it is run as a main script.

Body:
I have python logger being defined in the global part of a python script like so:

import logging
import logging.handlers

FORMAT = '%(asctime)-15s %(threadName)s %(levelname)s %(message)s'
logfile = app.config['CONTROLROOM_WORKER_LOG_PATH']
loghandler = logging.handlers.TimedRotatingFileHandler(logfile, when='midnight', interval=1, backupCount=10, encoding=None, delay=False, utc=False)
fmt = logging.Formatter(FORMAT)
loghandler.setFormatter(fmt)
logger = logging.getLogger('controlroom_worker')
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)

However issues I'm facing are the following:

Sometimes a logger statement prior to some logic is ignored (that is, not logged), even though the logic is executed. This behavior is amplified when a lot of stuff needs to be printed.

90% percent of the times, everything that is printed, is printed twice! Although I have seen a few cases where something is printed 3 times. Example logging:

2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,829 config_notifier INFO Notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Committed !!!
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:20,949 config_notifier INFO Notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Committed !!!
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.
2017-12-08 17:51:26,057 config_notifier INFO Notifying changes.

See how stuff is being printed twice or thrice?

Here's something interesting:

In addition to using the logging package, I also tried logging by simply writing to a file and writing to it whenever a log is needed:

manual_logger=open("manual_log.txt", "a+")
manual_logger.write("Some message here" + "\n")

This manual logger always writes each log statement just once (as is to be expected), but also suffers from some logs being completely missed out randomly:

Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!
Done notifying changes.
Notifying changes.
Committed !!!

How do I solve these issues? They're driving me mad.


问:
Calculator function is not working, is showing function undefined
Below funtion not working and showing "add is undefined". I am calculating by chaining the function calls.</p>

```<code>var calc = {
  x: 5,
  add: function(num) {
    x = x + num;
    return x;
  },
  sub: function(num) {
    x = x - num;
    return x;
  },
  set: function(num) {
    x = num;
    return x;
  },
  print: function() {
    console.log(x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();
</code>```

答:
You need to return reference to calc instead of number to allow chaining, also use this to reference x value:

var calc = {
  x : 5,
  add: function(num){
    this.x = this.x+num;
    return this;
  },
  sub :function(num){
    this.x =this.x-num;
    return this;
  },
  set :function(num){
    this.x= num;
    return this;
  },
  print : function(){
    console.log(this.x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();```
</div>
</div>
</p>

<p>Here is ES6 version with <code>class</code> syntax:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Calc {

  constructor(x = 0) {
    this.x = x;
  }

  add(num) {
    this.x = this.x + num;

    return this;
  }

  sub(num) {
    this.x = this.x - num;

    return this;
  }

  set(num) {
    this.x = num;

    return this;
  }

  print() {
    console.log(this.x);
  }

}

new Calc().set(5).add(3).sub(2).add(10).print();

// or with constructor
new Calc(5).add(3).sub(2).add(10).print();</code>```

Body:
Below funtion not working and showing "add is undefined". I am calculating by chaining the function calls.

var calc = {
  x: 5,
  add: function(num) {
    x = x + num;
    return x;
  },
  sub: function(num) {
    x = x - num;
    return x;
  },
  set: function(num) {
    x = num;
    return x;
  },
  print: function() {
    console.log(x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();

Body:
You need to return reference to calc instead of number to allow chaining, also use this to reference x value:

var calc = {
  x : 5,
  add: function(num){
    this.x = this.x+num;
    return this;
  },
  sub :function(num){
    this.x =this.x-num;
    return this;
  },
  set :function(num){
    this.x= num;
    return this;
  },
  print : function(){
    console.log(this.x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();

Here is ES6 version with class syntax:

class Calc {

  constructor(x = 0) {
    this.x = x;
  }

  add(num) {
    this.x = this.x + num;

    return this;
  }

  sub(num) {
    this.x = this.x - num;

    return this;
  }

  set(num) {
    this.x = num;

    return this;
  }

  print() {
    console.log(this.x);
  }

}

new Calc().set(5).add(3).sub(2).add(10).print();

// or with constructor
new Calc(5).add(3).sub(2).add(10).print();


问:
How do I add class to first paragraph and span to first letter
Example

```<code><p>Lorem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>
</code>```

I want add class for first paragraph and add span class to the first letter

```<code><p class="first-paragraph"><span class="first-letter">L</span>orem ipsum dolor sit amet</p>
</code>```

Let me know how can be with PHP

答:
```<code>$text = '<p>Lorem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>';

$text = substr_replace($text, '</span>', 4, 0);
$text = substr_replace($text, '<span class="first-letter">', 3, 0);
$text = substr_replace($text, ' class="first-paragraph"', 2, 0);

echo htmlspecialchars($text);
</code>```

<p>:-)</p>

ContentLicense: CC BY-SA 2.5

Body:
Example

Lorem ipsum dolor sit amet

Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.

I want add class for first paragraph and add span class to the first letter

Lorem ipsum dolor sit amet

Let me know how can be with PHP

Body:
$text = '<p>Lorem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>';

$text = substr_replace($text, '</span>', 4, 0);
$text = substr_replace($text, '<span class="first-letter">', 3, 0);
$text = substr_replace($text, ' class="first-paragraph"', 2, 0);

echo htmlspecialchars($text);

:-)


问:
Scikit-learn: Predicting new raw and unscaled instance using models trained with scaled data
I have produced different classifier models using scikit-learn and this has been smooth-sailing. Due to differences of units in the data (I got the data from different sensors labeled by their corresponding categories), I opted to scale the features using the StandardScale module.

Resulting accuracy scores of the different machine learning classifiers were fine. However, when I try to use the model to predict a raw instance (meaning unscaled) of sensor values, the models output wrong classification.

Should this really be the case because of the scaling done to the training data? If so, is there an easy way to scale the raw values too? I would like to use model persistence for this using joblib and it would be appreciated if there is a way to make this as modular as possible. Meaning to say, not to record mean and standard variation for each feature every time the training data changes.

答:
I've been struggling with this problem for days and googling a lot and finally, thanks to lejlot's posting, I solved the problem about what you exactly mentioned.

I was very annoyed that nobody wrote the means of how to predict an arbitrary number after standardizing X (objective function) (BTW, you should not standardize y. I was confused at first, coz everybody seemed confused and wrote wrongly.)

I'll put a code you can easily refer to below.

```<code>from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.preprocessing import StandardScaler
from numpy import *

X = array([ [0], [1],[2],[3],[4],[5],[6],[7] ])
y = 2*array([ [0], [1],[2],[3],[4],[5],[6],[7]  ])

scaler = StandardScaler()
X_train = scaler.fit_transform(X)
print(X_train)

model = MLPRegressor(hidden_layer_sizes=(3 ), activation='logistic', solver='lbfgs', alpha=0.0001, batch_size ="auto",
                    learning_rate= 'constant', learning_rate_init=0.001, power_t=0.5, max_iter=2000, shuffle=True, random_state=None,
                    tol=0.0001, verbose=True, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False,
                    validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)

model.fit(X_train, y)
# YOU CAN SEE I DIDN't STANDARDIZE y BUT ONLY X.

# Testing
# load scaler

scaled_instances = scaler.transform(array([ [1],[2] ]))
print(scaled_instances)

s = model.predict( scaled_instances )
print(s)
</code>```

I tested several numbers and showed the correct values.
And it was very helpful information from lejlot's posting that while training 'scaler' is saved. <- I absolutely had no idea about it.

Thanks to this feature, whatever number we use to "predict", this saved scaler scales the input number which we're going to use to predict unknown output.

ContentLicense: CC BY-SA 4.0

Body:
I've been struggling with this problem for days and googling a lot and finally, thanks to lejlot's posting, I solved the problem about what you exactly mentioned.

I was very annoyed that nobody wrote the means of how to predict an arbitrary number after standardizing X (objective function) (BTW, you should not standardize y. I was confused at first, coz everybody seemed confused and wrote wrongly.)

I'll put a code you can easily refer to below.

from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.preprocessing import StandardScaler
from numpy import *

X = array([ [0], [1],[2],[3],[4],[5],[6],[7] ])
y = 2*array([ [0], [1],[2],[3],[4],[5],[6],[7]  ])

scaler = StandardScaler()
X_train = scaler.fit_transform(X)
print(X_train)

model = MLPRegressor(hidden_layer_sizes=(3 ), activation='logistic', solver='lbfgs', alpha=0.0001, batch_size ="auto",
                    learning_rate= 'constant', learning_rate_init=0.001, power_t=0.5, max_iter=2000, shuffle=True, random_state=None,
                    tol=0.0001, verbose=True, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False,
                    validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)

model.fit(X_train, y)
# YOU CAN SEE I DIDN't STANDARDIZE y BUT ONLY X.

# Testing
# load scaler

scaled_instances = scaler.transform(array([ [1],[2] ]))
print(scaled_instances)

s = model.predict( scaled_instances )
print(s)

I tested several numbers and showed the correct values.
And it was very helpful information from lejlot's posting that while training 'scaler' is saved. <- I absolutely had no idea about it.

Thanks to this feature, whatever number we use to "predict", this saved scaler scales the input number which we're going to use to predict unknown output.


问:
Append a clone of a div to the child of an another div using $(this) selector
How can I clone a div to the child of an another div, and I may need to access the destination div by $(this).find(). My html structure is similar to

```<code><div class="destination-wrapper">
  <div class="destination">
  </div>
</div>

<div class="source">
  <p>Content</p>
</div>
</code>```

So i need to clone the 'source' to the 'destination' When I click on the 'destination-wrapper'. There are many 'destination-wrapper' in the page, So I may need to use $(this).find('.destination')

the jquery I used is the following

```<code>$('.destination-wrapper').click(function(){
  $('.source').clone().appendTo($(this).find('.destination'));
});
</code>```

答:
Here, $(this) is referring to $('.source'). If you want to refer to $('.destination-wrapper'), you need to store it into a variable like :

```<code>$('.destination-wrapper').click(function(){
  var destination = $(this).find('.destination')
  $('.source').clone().appendTo(destination);
});
</code>```

Body:
How can I clone a div to the child of an another div, and I may need to access the destination div by $(this).find(). My html structure is similar to

Content

So i need to clone the 'source' to the 'destination' When I click on the 'destination-wrapper'. There are many 'destination-wrapper' in the page, So I may need to use $(this).find('.destination')

the jquery I used is the following

$('.destination-wrapper').click(function(){
  $('.source').clone().appendTo($(this).find('.destination'));
});

Body:
Here, $(this) is referring to $('.source'). If you want to refer to $('.destination-wrapper'), you need to store it into a variable like :

$('.destination-wrapper').click(function(){
  var destination = $(this).find('.destination')
  $('.source').clone().appendTo(destination);
});


问:
How to put header file to .tab.h in Bison?
I wrote bison code header:

```<code>%{
#include "foo.h"
%}
</code>```

And I defined a struct named 'Foo' in header. I'd like to use it as token type in Bison.

```<code>%define api.value.type union
%token <Foo*> bar
</code>```

Then I use -d option to generate bison.tab.h file.

```<code>bison -d bison.y
</code>```

But there is no #include foo.h in bison.tab.h, and it use struct Foo to define the union YYSTYPE.

```<code>//bison.tab.h
union YYSTPE {
    Foo* bar;
    ...
};
</code>```

It caused error when compile this program: error: ‘Foo’ does not name a type

Is there a way to include header file in bison.tab.h or another solution of this case?

答:
For includes that should appear in both the .c and the .h file (before the definition for the %union), you should use %code requires { ... }. %{ ...  } inserts code in the .c file only.

For more information on the various %code options, you can look at the "Prologue Alternatives" chapter of the Bison docs.

Body:
I wrote bison code header:

%{
#include "foo.h"
%}

And I defined a struct named 'Foo' in header. I'd like to use it as token type in Bison.

%define api.value.type union
%token <Foo*> bar

Then I use -d option to generate bison.tab.h file.

bison -d bison.y

But there is no #include foo.h in bison.tab.h, and it use struct Foo to define the union YYSTYPE.

//bison.tab.h
union YYSTPE {
    Foo* bar;
    ...
};

It caused error when compile this program: error: ‘Foo’ does not name a type

Is there a way to include header file in bison.tab.h or another solution of this case?


问:
POST Json String to Remote PHP Script using Json.NET
I am encountering an unusually strange behavior when POSTing a Json string to a PHP webserver. I use the JsonTextWriter object to create the Json string. I then send the Json string as a POST request. Please see comments. The HTML response in the code is returning the correct output, but when viewed in a browser, the web page displays either NULL or array(0) { }.

```<code>private void HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
try
{ // Send the Post Data
    webRequest.ContentLength = bytes.Length;
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    Console.WriteLine(String.Format(@"{0}", byteString));     // <- This matches the Json object
}
catch (WebException ex)
{ //Handle Error }

try
{ // Get the response
    WebResponse webResponse = webRequest.GetResponse();
    if (webResponse == null) { return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    Console.WriteLine(sr.ReadToEnd().Trim());                // <- Server returns string response (full HTML page)
}
catch (WebException ex)
{ //Handle Error }
}
</code>```

Relevant PHP code on the server:

```<code>$json = json_encode($_POST);   # Not 'standard way'
var_dump(json_decode($json));
</code>```

Any suggestions would be greatly appreciated.

Thanks

答:
Try using "application/json" as the content type.  Also, check the request logs or maybe do a port 80 trace if you can to view what's being sent to the server in the request body.

You can also narrow the scope of the problem -- is it the C# code or the PHP code that's bad -- by writing a quick JQuery ajax function that sends some JSON to the PHP server.  This isolation of the PHP code from the C# code will tell you if the PHP is at least working correctly.  If it is, then the problem is in the C# code.

Body:
I am encountering an unusually strange behavior when POSTing a Json string to a PHP webserver. I use the JsonTextWriter object to create the Json string. I then send the Json string as a POST request. Please see comments. The HTML response in the code is returning the correct output, but when viewed in a browser, the web page displays either NULL or array(0) { }.

private void HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
try
{ // Send the Post Data
    webRequest.ContentLength = bytes.Length;
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);

    Console.WriteLine(String.Format(@"{0}", byteString));     // <- This matches the Json object
}
catch (WebException ex)
{ //Handle Error }

try
{ // Get the response
    WebResponse webResponse = webRequest.GetResponse();
    if (webResponse == null) { return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    Console.WriteLine(sr.ReadToEnd().Trim());                // <- Server returns string response (full HTML page)
}
catch (WebException ex)
{ //Handle Error }
}

Relevant PHP code on the server:

$json = json_encode($_POST);   # Not 'standard way'
var_dump(json_decode($json));

Any suggestions would be greatly appreciated.

Thanks


问:
static resource in angular and ionic application

in my ionic project i have the hierarchy as in the image , i am trying to get products.json, but after starting the application i am trying to access the json file products.json , it says resources not available.

http://localhost:8100/pages/login/products.json

答:
Put your json file in assets folder

try code like below example :

```<code>import {Injectable} from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HomePage {
private data: any;

 constructor(private http: Http) { }

 getData(){
   this.http.get('assets/data/products.json')
   .map((res) => res.json())
   .subscribe(data => {
      this.data = data;
   }, (rej) => {
          console.error("Could not load local data",rej)
   });
 }
}
</code>```

Body:
Put your json file in assets folder

try code like below example :

import {Injectable} from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HomePage {
private data: any;

 constructor(private http: Http) { }

 getData(){
   this.http.get('assets/data/products.json')
   .map((res) => res.json())
   .subscribe(data => {
      this.data = data;
   }, (rej) => {
          console.error("Could not load local data",rej)
   });
 }
}


问:
Azure Web Deploy "Could not find a part of the path 'D:\home\site\wwwroot\bin\roslyn\csc.exe'."
I've been browsing the web for a couple hours now looking for an answer to my problem. I am trying to deploy a Web API on Azure Web App Service using VS2017. Everything builds and works fine when running locally but once deployed on Azure (through VS2017) I get this error:

D:\home\site\wwwroot\bin\roslyn\csc.exe

My project is an ASP.NET Web Application (Using Azure Web API template) .NET Framework 4.6.1. I use Microsoft.CodeDom.Providers.DotNetCompilerPlatform Version=1.0.6.0

I also made sure that csc.exe is located in:

Visual Studio 2017\Projects\DeviceManagementAPI\DeviceManagementAPI\bin\roslyn

答: Upgrading Microsoft.CodeDom.Providers.DotNetCompilerPlatform to 1.08 worked for me</p>


问:
window.location.reload(true) reloads page but page needs refreshing to show changes
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

```<code>if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li><a href="" onclick="window.location.reload(true);return toggleLive(this, ' . $post->ID . ');">' . $text . '</a></li>';
}
</code>```

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

```<code>add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});
</code>```

JS

```<code>function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}
</code>```

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR

答:
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into href=""> within the function.

I believe @cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.

Body:
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '
ID . ');">' . $text . '
';
}

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});

JS

function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR

Body:
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.

I believe @cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.


问:
Laravel, jquery - Fill input box as per select box
I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

```<code>$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});
</code>```

My laravel function to return gigs list:

```<code>public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;
</code>```

Can somebody help how to achieve this?

答:
you can disable unchanged items like following,

```<code>$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    $.each( $( "#proposed_product" ).children('option'), function (index, item) {
        if(selectedItem.val() != $(item).val()) {
            $(this).prop('disabled', true)
        }
    })
});
</code>```

Also, you can change option items  by data which result of request you send.

```<code>$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    // Example Request
    $.get('https://httpbin.org/get', function(data) {
        $.each( $( "#proposed_product" ).children('option'), function (index, item) {
            if(selectedItem.val() != $(item).val()) {
                $(this).text(data.origin)
            }
        })
    })
});
</code>```

Also, your response must be json format,

```<code>public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json($gig, 200);
}
</code>```

Body:
I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});

My laravel function to return gigs list:

public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;

Can somebody help how to achieve this?

Body:
you can disable unchanged items like following,

$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    $.each( $( "#proposed_product" ).children('option'), function (index, item) {
        if(selectedItem.val() != $(item).val()) {
            $(this).prop('disabled', true)
        }
    })
});

Also, you can change option items  by data which result of request you send.

$( "#proposed_product" ).change(function() {

    var selectedItem = $(this)

    // Example Request
    $.get('https://httpbin.org/get', function(data) {
        $.each( $( "#proposed_product" ).children('option'), function (index, item) {
            if(selectedItem.val() != $(item).val()) {
                $(this).text(data.origin)
            }
        })
    })
});

Also, your response must be json format,

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json($gig, 200);
}


问:
Function is looping infinitely - do/while functions
Goal:

Implement a program that prints out a double half-pyramid of a specified height, per the below.

```<code>$ ./mario
Height: 4
   #  #
  ##  ##
 ###  ###
####  ####
</code>```

Problem:

Have been messing with the code for the past 3 hours or so. I got the first line to work, but everything beyond that was just 2 parallel pillars consisting of a singular hash mark. At present, the program is indefinitely printing a hash mark.

Code:

```<code>int main (void) {
    // user gives height value for pyramid
    // h = height
    int h;
    do {
        printf (
            "How tall do you want your pyramid to be? Please type a number "
            "between 0 and 23.\n");
        h = get_int ();

    } while (h < 0 || h > 23);

    // Left side of pyramid says spaces first, followed by hashes. Two spaces
    // inbetween sides of the pyramid. Right side renders hashes first, then
    // inputs newline character.
    // r = row
    // s = space
    // p = hash
    // q = hash right
    int q;
    int p;
    int s;
    int r;
    for (r = 0; r < h; r++) {
        do {
            do {
                printf (" ");
                s++;
            } while (s < h - r);

            // says spaces

            do {
                printf ("#");
                p++;
            } while (p < r++);

            // says left hashes

            // always print 2 spaces inbetween
            printf ("  "); // two spaces

            do {
                printf ("#");
                q++;
            } while (q < r++);
            // says right hashes

            printf ("\n");
            q = 0;
            p = 0;
            s = 0;
            // reset q,p,s values

        } // end bracket of encompassing 'do' function
        while (r < h);
        //'for' function should execute once, increment 'r' by 1, and repeat
        //until row height becomes height provided by user.

    } // end bracket of for loop

} // end bracket of int main
</code>```

Expected Result:

Program creates pyramid formed by hash symbols and spaces.

Actual Result:

Infinitely looping print function.

答:
the end of your loop is like:

```<code> p++;
}
while (p < r++);
</code>```

so r is always ahead of p because you're incrementing both. That's your infinite loop.

I get a pretty good result moving r++ after the second while inner loop, like this:

```<code>   #  #
  #  #
 ##  ##
###  ###
</code>```

so still a bit of tuning and you're here. The other issue is with do/while which execute once even if the condition is false. Replace by while loops or you're one off like above:

```<code>    do
    {
        while (s < h - r)
        {
            printf(" ");
            s++;
        }
        //says spaces

        while (p < r)
        {
            printf("#");
            p++;
        }

        //says left hashes

        //always print 2 spaces inbetween
        printf("  ");

        //two spaces

        while(q < r)
        {
            printf("#");
            q++;
        }

        //says right hashes
        r++;
        printf("\n");
        q = 0;
        p = 0;
        s = 0;
        // reset q,p,s values

    }//end bracket of encompassing 'do' function
    while(r < h);
</code>```

Note that it's also cheap to autoindent your code using "Notepad++ / TextFX / TextFX edit / Reindent C++ code"

```<code>         #  #
        ##  ##
       ###  ###
      ####  ####
     #####  #####
    ######  ######
   #######  #######
  ########  ########
 #########  #########
</code>```

Body:
Goal:

Implement a program that prints out a double half-pyramid of a specified height, per the below.

$ ./mario
Height: 4
   #  #
  ##  ##
 ###  ###
####  ####

Problem:

Have been messing with the code for the past 3 hours or so. I got the first line to work, but everything beyond that was just 2 parallel pillars consisting of a singular hash mark. At present, the program is indefinitely printing a hash mark.

Code:

int main (void) {
    // user gives height value for pyramid
    // h = height
    int h;
    do {
        printf (
            "How tall do you want your pyramid to be? Please type a number "
            "between 0 and 23.\n");
        h = get_int ();

    } while (h < 0 || h > 23);

    // Left side of pyramid says spaces first, followed by hashes. Two spaces
    // inbetween sides of the pyramid. Right side renders hashes first, then
    // inputs newline character.
    // r = row
    // s = space
    // p = hash
    // q = hash right
    int q;
    int p;
    int s;
    int r;
    for (r = 0; r < h; r++) {
        do {
            do {
                printf (" ");
                s++;
            } while (s < h - r);

            // says spaces

            do {
                printf ("#");
                p++;
            } while (p < r++);

            // says left hashes

            // always print 2 spaces inbetween
            printf ("  "); // two spaces

            do {
                printf ("#");
                q++;
            } while (q < r++);
            // says right hashes

            printf ("\n");
            q = 0;
            p = 0;
            s = 0;
            // reset q,p,s values

        } // end bracket of encompassing 'do' function
        while (r < h);
        //'for' function should execute once, increment 'r' by 1, and repeat
        //until row height becomes height provided by user.

    } // end bracket of for loop

} // end bracket of int main

Expected Result:

Program creates pyramid formed by hash symbols and spaces.

Actual Result:

Infinitely looping print function.

Body:
the end of your loop is like:

 p++;
}
while (p < r++);

so r is always ahead of p because you're incrementing both. That's your infinite loop.

I get a pretty good result moving r++ after the second while inner loop, like this:

   #  #
  #  #
 ##  ##
###  ###

so still a bit of tuning and you're here. The other issue is with do/while which execute once even if the condition is false. Replace by while loops or you're one off like above:

    do
    {
        while (s < h - r)
        {
            printf(" ");
            s++;
        }
        //says spaces

        while (p < r)
        {
            printf("#");
            p++;
        }

        //says left hashes

        //always print 2 spaces inbetween
        printf("  ");

        //two spaces

        while(q < r)
        {
            printf("#");
            q++;
        }

        //says right hashes
        r++;
        printf("\n");
        q = 0;
        p = 0;
        s = 0;
        // reset q,p,s values

    }//end bracket of encompassing 'do' function
    while(r < h);

Note that it's also cheap to autoindent your code using "Notepad++ / TextFX / TextFX edit / Reindent C++ code"

         #  #
        ##  ##
       ###  ###
      ####  ####
     #####  #####
    ######  ######
   #######  #######
  ########  ########
 #########  #########