问:
How to Change previous button color when pressed the next button?
I have a number of buttons in a horizontal UIScrollView added programmatically. I have to change the color of the user selected button. But if user select another button the previous button color must be change to default color.
how can I do this? Please help me...

```<code>func createHorizontalScroll()
{
    let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))

    var buttonX: CGFloat = 0

    for index in 0..<btnNames.count
    {
        //add an element and the previous element together
        let sum = btnNames[index]

        button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))

        print("btnNames:\(sum)")

        button.setTitle("\(sum)",for:.normal)
        button.layer.borderWidth = 2.5
        button.layer.borderWidth = 2.5
        button.layer.borderColor = UIColor.white.cgColor
        button.layer.backgroundColor = UIColor.black.cgColor
        button.tag = index
        scrollView.addSubview(button)
        buttonX = button.frame.size.width + buttonX

        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
    }

    scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
    scrollView.backgroundColor = UIColor.clear
    view.addSubview(scrollView)
}

func changeView(_ sender: UIButton)
{
   print("I Clicked a button \(Int(sender.tag))")
}
</code>```

答:
Since you're already using tags it shouldn't be a problem. The changeView function should work like this:

```<code>func changeView(_ sender: UIButton)
{
    let scrollView = sender.superview as! UIScrollView //This is mildly hacky - store your scroll view in an instance variable
    for view in scrollView.subviews {
        guard let button = view as? UIButton else {
            continue
        }

        button.backgroundColor = sender.tag == button.tag ? UIColor.red : UIColor.black
    }
}
</code>```

Body:
I have a number of buttons in a horizontal UIScrollView added programmatically. I have to change the color of the user selected button. But if user select another button the previous button color must be change to default color.
how can I do this? Please help me...

func createHorizontalScroll()
{
    let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))

    var buttonX: CGFloat = 0

    for index in 0..<btnNames.count
    {
        //add an element and the previous element together
        let sum = btnNames[index]

        button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))

        print("btnNames:\(sum)")

        button.setTitle("\(sum)",for:.normal)
        button.layer.borderWidth = 2.5
        button.layer.borderWidth = 2.5
        button.layer.borderColor = UIColor.white.cgColor
        button.layer.backgroundColor = UIColor.black.cgColor
        button.tag = index
        scrollView.addSubview(button)
        buttonX = button.frame.size.width + buttonX

        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
    }

    scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
    scrollView.backgroundColor = UIColor.clear
    view.addSubview(scrollView)
}

func changeView(_ sender: UIButton)
{
   print("I Clicked a button \(Int(sender.tag))")
}

Body:
Since you're already using tags it shouldn't be a problem. The changeView function should work like this:

func changeView(_ sender: UIButton)
{
    let scrollView = sender.superview as! UIScrollView //This is mildly hacky - store your scroll view in an instance variable
    for view in scrollView.subviews {
        guard let button = view as? UIButton else {
            continue
        }

        button.backgroundColor = sender.tag == button.tag ? UIColor.red : UIColor.black
    }
}


来源: stackexchange

问:
Multiple Context.Forward calls gives exception "execution finished with multiple resume handlers specified through IDialogStack"
I am inside a dialog called as "ParentCustSvcDialog", called from within the "RootDialog". Within this dialog, I am trying to forward the call to LUIS.

Based on what LUIS responds, I am forwarding a call to QnAMaker. I would like to keep this conditional logic within the parent dialog.

However, the conversation does not get through and the call to QnAMaker, and gives exception as below:

Exception: IDialog method execution finished with multiple resume handlers specified through IDialogStack

I pasted the code below. Any idea where is the issue?

ParentCustSvcDialog.cs

```<code>    LuisDialogCustomResult luisDialogCustomResult = null;
    QnAMakerDialogCustomResult qnAMakerDialogCustomResult = null;

    private async Task MessageReceived(IDialogContext context, IAwaitable<object> result)
    {
            await context.Forward<LuisDialogCustomResult>(new LuisLeavesDialog(), ResumeAfterLuisDoneDialog, context.Activity.AsMessageActivity());
            if (null == luisDialogCustomResult.MainIntent)  // No meaningful response from LUIS
            {
                // POST to the QnA Maker via the QnA Maker Dialog
                await context.Forward<QnAMakerDialogCustomResult>(new QnAMakerLeavesDialog(), ResumeAfterQnAMakerDoneDialog, context.Activity.AsMessageActivity());
            }
            else    // Meaningful Response from LUIS.
            {
                await context.PostAsync($"(DEBUG:LUIS) Here is what I found: </br> { customMessage }");
            }

            context.Wait(MessageReceived);
    }

    private async Task ResumeAfterLuisDoneDialog(IDialogContext context, IAwaitable<LuisDialogCustomResult> result)
    {
        // Control Comes to Parent Dialog once done with Luis Portion
        luisDialogCustomResult = (await result as LuisDialogCustomResult);
    }

    private async Task ResumeAfterQnAMakerDoneDialog(IDialogContext context, IAwaitable<QnAMakerDialogCustomResult> result)
    {
        // Control Comes to Parent Dialog once done with QnA Portion
        qnAMakerDialogCustomResult = await result as QnAMakerDialogCustomResult;
    }
</code>```

答:
It's very simple. as the exceptions say, when your bot is looking at the code it says multiple ways to go forward through the code.

Your guiding the waterfall to multiple points, which basically means you have an architectural problem.
Try to keep up the waterfall model nd keep the bot to exit through only one point at a time.

Bot framework does not like multiple endpoints for the same IDialog.

You can limit it by changing the way you are looking into the problem you are trying to solve.

todo:

Remove multiple exit points for the code.

If you need
multiple, Have them differentiated in such a way that only one shows up at a time.

Always make the architecture in such a way that the waterfall model is followed.

ContentLicense: CC BY-SA 3.0

Body:
I am inside a dialog called as "ParentCustSvcDialog", called from within the "RootDialog". Within this dialog, I am trying to forward the call to LUIS.

Based on what LUIS responds, I am forwarding a call to QnAMaker. I would like to keep this conditional logic within the parent dialog.

However, the conversation does not get through and the call to QnAMaker, and gives exception as below:

Exception: IDialog method execution finished with multiple resume handlers specified through IDialogStack

I pasted the code below. Any idea where is the issue?

ParentCustSvcDialog.cs

    LuisDialogCustomResult luisDialogCustomResult = null;
    QnAMakerDialogCustomResult qnAMakerDialogCustomResult = null;

    private async Task MessageReceived(IDialogContext context, IAwaitable<object> result)
    {
            await context.Forward<LuisDialogCustomResult>(new LuisLeavesDialog(), ResumeAfterLuisDoneDialog, context.Activity.AsMessageActivity());
            if (null == luisDialogCustomResult.MainIntent)  // No meaningful response from LUIS
            {
                // POST to the QnA Maker via the QnA Maker Dialog
                await context.Forward<QnAMakerDialogCustomResult>(new QnAMakerLeavesDialog(), ResumeAfterQnAMakerDoneDialog, context.Activity.AsMessageActivity());
            }
            else    // Meaningful Response from LUIS.
            {
                await context.PostAsync($"(DEBUG:LUIS) Here is what I found:
 { customMessage }");
            }

            context.Wait(MessageReceived);
    }

    private async Task ResumeAfterLuisDoneDialog(IDialogContext context, IAwaitable<LuisDialogCustomResult> result)
    {
        // Control Comes to Parent Dialog once done with Luis Portion
        luisDialogCustomResult = (await result as LuisDialogCustomResult);
    }

    private async Task ResumeAfterQnAMakerDoneDialog(IDialogContext context, IAwaitable<QnAMakerDialogCustomResult> result)
    {
        // Control Comes to Parent Dialog once done with QnA Portion
        qnAMakerDialogCustomResult = await result as QnAMakerDialogCustomResult;
    }


问:
Font looks blurry on Firefox
It just ok with chrome and opera. But it looks blurry on Internet explorer and Firefox. I researched and apply these css, but still no luck. My firefox and Internet explorer versions are up to date. I'm not using google font. Here is my styles.

```<code>@font-face {
  font-family: 'Gotham-Bold';
  src: url('../fonts/Gothambold/Gotham-Bold.eot');
  src: url('../fonts/Gothambold/Gotham-Bold.eot?#iefix') format('embedded-opentype'), url('../fonts/Gothambold/Gotham-Bold.woff') format('woff'), url('../fonts/Gothambold/Gotham-Bold.ttf') format('truetype'), url('../fonts/Gothambold/Gotham-Bold.svg#') format('svg');
}

body{
text-rendering: optimizeLegibility;
text-rendering: geometricPrecision;
font-smooth: always;

font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-webkit-font-smoothing: antialiased;
-webkit-font-smoothing: subpixel-antialiased;
}
</code>```

View in firefox.

View in chrome

Still no luck. Any ideas?

答:
This issue was raised a while back (and fixed) in this thread.

Just to summarize...

The cause:

This firefox issue occurs on Macs where the option: "Use LCD font smoothing when available" (Settings > General > Use LCD font smoothing when available) is checked. (It is checked by default).

Note: From experience, this issue doesn't occur on the actual retina screen of the mac - but rather on non-retina screens connected to the mac.

Uncheck that option and restart firefox and you'll see the font looks fine!

The fix:

To overcome this for users with the above option enabled - simple add the following declaration in the body:

```<code>-moz-osx-font-smoothing: grayscale;
</code>```

You'll be pleasantly surprised.

Title: Font looks blurry on Firefox

Body:
It just ok with chrome and opera. But it looks blurry on Internet explorer and Firefox. I researched and apply these css, but still no luck. My firefox and Internet explorer versions are up to date. I'm not using google font. Here is my styles.

@font-face {
  font-family: 'Gotham-Bold';
  src: url('../fonts/Gothambold/Gotham-Bold.eot');
  src: url('../fonts/Gothambold/Gotham-Bold.eot?#iefix') format('embedded-opentype'), url('../fonts/Gothambold/Gotham-Bold.woff') format('woff'), url('../fonts/Gothambold/Gotham-Bold.ttf') format('truetype'), url('../fonts/Gothambold/Gotham-Bold.svg#') format('svg');
}

body{
text-rendering: optimizeLegibility;
text-rendering: geometricPrecision;
font-smooth: always;

font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-webkit-font-smoothing: antialiased;
-webkit-font-smoothing: subpixel-antialiased;
}

View in firefox.

View in chrome

Still no luck. Any ideas?

Body:
This issue was raised a while back (and fixed) in this thread.

Just to summarize...

The cause:

This firefox issue occurs on Macs where the option: "Use LCD font smoothing when available" (Settings > General > Use LCD font smoothing when available) is checked. (It is checked by default).

Note: From experience, this issue doesn't occur on the actual retina screen of the mac - but rather on non-retina screens connected to the mac.

Uncheck that option and restart firefox and you'll see the font looks fine!

The fix:

To overcome this for users with the above option enabled - simple add the following declaration in the body:

-moz-osx-font-smoothing: grayscale;

You'll be pleasantly surprised.


问:
Changing position of the Dialog on screen android
I made a simple AlertDialog in my Activity:

```<code>View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)
                    .create();

infoDialog.show();
</code>```

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??

答:
```<code>dialog.getWindow().getAttributes().gravity = Gravity.BOTTOM;
</code>```

Body:
I made a simple AlertDialog in my Activity:

View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)
                    .create();

infoDialog.show();

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??


问:
How to Append two different hash map on a particular node without replacing other in Firebase?
I want to append two different hash map pairs on a particular node one with key value both being String and other String and Array List. But problem is Later one is replacing first one in Fire base database. what should i do? I cant use push() all the time.Link of my code. Please help  </p>

答:
You can achieve this if you generate a unique random key. This can be done using push() method.

As we know, in the case of HashMap, it replaces the old value with the new one.

Don't forget to use updatechildren() method, and not setValue() method directly on the refrence when you want to update data.

Hope it helps.


问:
AWS Lambda - Send URL as GET Parameter from PHP to Java Lambda function
I have a AWS lambda function that takes 5 parameters. One of the parameter is a Url, that is passed from PHP backend, as a get parameter. The url is encoded while passing, and the parameters are passed as a JSONObject. Please note, i am using JSONObject from amazonaws sdk (com.amazonaws.util.json).

The input object is converted to a JSONObject in the lambda function, before getting the values from it. The problem comes when converting to input to Json, because of the url. If i pass a string in place of url, the lambda works just fine.

Here is the relevant code and outputs:

```<code>@Override
    public String handleRequest(Object input, Context context) {

        LambdaLogger logger = context.getLogger();

        if (DEBUG)
            logger.log("Starting LambdaFunction");

        TwilioRestClient client = new TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);

        try {

            if (DEBUG)
                logger.log("Input: " + input.toString());

            JSONObject object = new JSONObject(input.toString());//Problem here

            if (DEBUG)
                logger.log("Object: " + object.toString());

            String name = object.getString("name");
            String message = object.getString("message");
            String survey_url = object.getString("url");
            String user_id = object.getString("user_id");
            String number = object.getString("number");

            if (DEBUG) {
                logger.log("Name: " + name);
                logger.log("Message: " + message);
                logger.log("Survey Url: " + survey_url);
                logger.log("User ID: " + user_id);
                logger.log("Number: " + number);
            }

            // Other functionality
        }

        catch (JSONException e) {
            logger.log("JSONException");
            e.printStackTrace();
        } catch (TwilioRestException e) {
            logger.log("TwilioRestException");
            e.printStackTrace();
        }

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

        return "End of SendSMSLambdaFunction";
    }
</code>```

call from php -> Lambda ::: https://xxx.amazonaws.com/prod/sendsmsapiresource?name=test&number=9618143233&url=http%3A%2F%2Fexample.com%2F&message=testmesage&user_id=1

output from cloudwatch for Lambda :::

```<code>Input: {name=test, number=9618143233, message=test, url=http://www.example.com, user_id=1}
JSONException
com.amazonaws.util.json.JSONException: Expected a ',' or '}' at 55 [character 56 line 1]
</code>```

How can i pass url as get parameter to lambda function?

答: The problem got solved, when i added ' ' for the url, in the lambda call from php. So now invoke call looks like, https://xxx.amazonaws.com/prod/sendsmsapiresource?name=test&number=9618143233&url=%27http%3A%2F%2Fexample.com%2F%27&message=testmesage&user_id=1 and my input to lambda comes as Input: {name=test, number=9618143233, message=test, url='http://www.example.com', user_id=1}

Body:
I have a AWS lambda function that takes 5 parameters. One of the parameter is a Url, that is passed from PHP backend, as a get parameter. The url is encoded while passing, and the parameters are passed as a JSONObject. Please note, i am using JSONObject from amazonaws sdk (com.amazonaws.util.json).

The input object is converted to a JSONObject in the lambda function, before getting the values from it. The problem comes when converting to input to Json, because of the url. If i pass a string in place of url, the lambda works just fine.

Here is the relevant code and outputs:

@Override
    public String handleRequest(Object input, Context context) {

        LambdaLogger logger = context.getLogger();

        if (DEBUG)
            logger.log("Starting LambdaFunction");

        TwilioRestClient client = new TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);

        try {

            if (DEBUG)
                logger.log("Input: " + input.toString());

            JSONObject object = new JSONObject(input.toString());//Problem here

            if (DEBUG)
                logger.log("Object: " + object.toString());

            String name = object.getString("name");
            String message = object.getString("message");
            String survey_url = object.getString("url");
            String user_id = object.getString("user_id");
            String number = object.getString("number");

            if (DEBUG) {
                logger.log("Name: " + name);
                logger.log("Message: " + message);
                logger.log("Survey Url: " + survey_url);
                logger.log("User ID: " + user_id);
                logger.log("Number: " + number);
            }

            // Other functionality
        }

        catch (JSONException e) {
            logger.log("JSONException");
            e.printStackTrace();
        } catch (TwilioRestException e) {
            logger.log("TwilioRestException");
            e.printStackTrace();
        }

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

        return "End of SendSMSLambdaFunction";
    }

call from php -> Lambda ::: https://xxx.amazonaws.com/prod/sendsmsapiresource?name=test&number=9618143233&url=http%3A%2F%2Fexample.com%2F&message=testmesage&user_id=1

output from cloudwatch for Lambda :::

Input: {name=test, number=9618143233, message=test, url=http://www.example.com, user_id=1}
JSONException
com.amazonaws.util.json.JSONException: Expected a ',' or '}' at 55 [character 56 line 1]

How can i pass url as get parameter to lambda function?


问:
Cannot implicitly convert type 'double' to 'long'
In this code i got the above error in lines i commented.

```<code>public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
</code>```

Whats is the problem? Thanks!

答:
Change types

```<code>long x;
long y;
long w;
long z;
</code>```

to

```<code>double x;
double y;
double w;
double z;
</code>```

Or make use of

```<code>Convert.ToInt64
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In this code i got the above error in lines i commented.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter = seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}

Whats is the problem? Thanks!

Body:
Change types

long x;
long y;
long w;
long z;

to

double x;
double y;
double w;
double z;

Or make use of

Convert.ToInt64


问:
Save into array with for loop laravel
I have a method to handle the request from the dynamic form.

```<code>public function step2(Request $request)
{
    $this->validate($request, [
      'title.*' => 'required',
      'f_name.*'   =>'required',
      'l_name.*'   =>'required',
      'dob_month.*'   =>'required',
      'dob_day.*'   =>'required',
      'dob_year.*'   =>'required',
      'gender.*'   =>'required',
      'email.*'   =>'required',
      'contact.*'   =>'required',
      'address1.*'   =>'required',
      'address2.*'   =>'required',
      'town.*'   =>'required',
      'state.*'   =>'required',
      'mailbox.*'   =>'required',
      'insurance.*'   =>'required',
    ]);

$data = array(
    for ($i=0; $i <$request->limit ; $i++){
        "title$i" => $request->title[$i],
        "f_name$i" => $request->f_name[$i],
        if (!isEmpty($request->m_name)) {
            "m_name$i" => $request->m_name[$i],
        }
        "l_name$i" => $request->l_name[$i],
        "dob_month$i" => $request->dob_month[$i],
        "dob_day$i" => $request->dob_day[$i],
        "dob_year$i" => $request->dob_year[$i],
        "gender$i" => $request->gender[$i],
        "email$i" => $request->email[$i],
        "contact$i" => $request->contact[$i],
        "address1$i" => $request->address1[$i],
        if (!isEmpty($request->m_name)) {
            "address2$i" => $request->address2[$i],
        }
        "town$i" => $request->town[$i],
        "mailbox$i" => $request->mailbox[$i],
        "insurance$i" => $request->insurance[$i],
    }

    Mail::send('emails.contact', $data, function($message) use ($data){
    $message->from(''sender@demo.com);
    $message->to('receiver@demo.com');
    $message->subject("!!New Mail!!");
      });

    );
  return view('success');
}
</code>```

I'm trying to save all the incoming request in array using for loop in order to send it as email. But I'm getting error of
Parse error: syntax error, unexpected 'for' (T_FOR), expecting ')'. What would be the best approach for this problem.

答:
You can use $key => $value pair to create array like this:

```<code>$data = array();

foreach($request->title as $key=>$value){

    $insert = array();

    $insert['title'.$key] = $value;
    $insert['f_name'.$key] = $request->f_name[$key];

    if (!isEmpty($request->m_name)) {
        $insert['m_name'.$key] = $request->m_name[$key];
    }

    $insert['l_name'.$key] = $request->l_name[$key];
    $insert['dob_month'.$key] = $request->dob_month[$key];
    $insert['dob_day'.$key] = $request->dob_day[$key];
    $insert['dob_year'.$key] = $request->dob_year[$key];
    $insert['gender'.$key] = $request->gender[$key];
    $insert['email'.$key] = $request->email[$key];
    $insert['contact'.$key] = $request->contact[$key];
    $insert['address1'.$key] = $request->address1[$key];

    if (!isEmpty($request->m_name)) {
        $insert['address2'.$key] = $request->address2[$key];
    }

    $insert['town'.$key] = $request->town[$key];
    $insert['mailbox'.$key] = $request->mailbox[$key];
    $insert['insurance'.$key] = $request->insurance[$key];

    array_push($data, $insert);
}
</code>```

Now, send this $data along with mail.

Title: Save into array with for loop laravel

Body:
I have a method to handle the request from the dynamic form.

public function step2(Request $request)
{
    $this->validate($request, [
      'title.*' => 'required',
      'f_name.*'   =>'required',
      'l_name.*'   =>'required',
      'dob_month.*'   =>'required',
      'dob_day.*'   =>'required',
      'dob_year.*'   =>'required',
      'gender.*'   =>'required',
      'email.*'   =>'required',
      'contact.*'   =>'required',
      'address1.*'   =>'required',
      'address2.*'   =>'required',
      'town.*'   =>'required',
      'state.*'   =>'required',
      'mailbox.*'   =>'required',
      'insurance.*'   =>'required',
    ]);

$data = array(
    for ($i=0; $i <$request->limit ; $i++){
        "title$i" => $request->title[$i],
        "f_name$i" => $request->f_name[$i],
        if (!isEmpty($request->m_name)) {
            "m_name$i" => $request->m_name[$i],
        }
        "l_name$i" => $request->l_name[$i],
        "dob_month$i" => $request->dob_month[$i],
        "dob_day$i" => $request->dob_day[$i],
        "dob_year$i" => $request->dob_year[$i],
        "gender$i" => $request->gender[$i],
        "email$i" => $request->email[$i],
        "contact$i" => $request->contact[$i],
        "address1$i" => $request->address1[$i],
        if (!isEmpty($request->m_name)) {
            "address2$i" => $request->address2[$i],
        }
        "town$i" => $request->town[$i],
        "mailbox$i" => $request->mailbox[$i],
        "insurance$i" => $request->insurance[$i],
    }

    Mail::send('emails.contact', $data, function($message) use ($data){
    $message->from(''sender@demo.com);
    $message->to('receiver@demo.com');
    $message->subject("!!New Mail!!");
      });

    );
  return view('success');
}

I'm trying to save all the incoming request in array using for loop in order to send it as email. But I'm getting error of
Parse error: syntax error, unexpected 'for' (T_FOR), expecting ')'. What would be the best approach for this problem.

Body:
You can use $key => $value pair to create array like this:

$data = array();

foreach($request->title as $key=>$value){

    $insert = array();

    $insert['title'.$key] = $value;
    $insert['f_name'.$key] = $request->f_name[$key];

    if (!isEmpty($request->m_name)) {
        $insert['m_name'.$key] = $request->m_name[$key];
    }

    $insert['l_name'.$key] = $request->l_name[$key];
    $insert['dob_month'.$key] = $request->dob_month[$key];
    $insert['dob_day'.$key] = $request->dob_day[$key];
    $insert['dob_year'.$key] = $request->dob_year[$key];
    $insert['gender'.$key] = $request->gender[$key];
    $insert['email'.$key] = $request->email[$key];
    $insert['contact'.$key] = $request->contact[$key];
    $insert['address1'.$key] = $request->address1[$key];

    if (!isEmpty($request->m_name)) {
        $insert['address2'.$key] = $request->address2[$key];
    }

    $insert['town'.$key] = $request->town[$key];
    $insert['mailbox'.$key] = $request->mailbox[$key];
    $insert['insurance'.$key] = $request->insurance[$key];

    array_push($data, $insert);
}

Now, send this $data along with mail.


问:
preparedStatement with TimeStamp compare two date
i have this code

```<code>    preparedStatement = jdbcManager.getConnection().prepareStatement(query);
    Date start; /*get from postgres column type-> Timestamp without time zone*/
    java.sql.Timestamp timestamp = new java.sql.Timestamp(start.getTime());

    log.debug("Parametro d'ingresso query: "+timestamp);
    preparedStatement.setTimestamp(1, timestamp);
</code>```

and i have this query

```<code>SELECT
DATA
FROM MY_TABLE
WHERE DATA > ?
</code>```

the  column DATA is DATA_TYPE = DATE   in a Oracle db

the compare in the query not working,
what am I doing wrong?

答: You're comparing date with timestamp. Instead of fetching time stamp, get java.sql.Date. And also in prepared statement,  use setDate instead of setTimeStamp.

Body:
i have this code

    preparedStatement = jdbcManager.getConnection().prepareStatement(query);
    Date start; /*get from postgres column type-> Timestamp without time zone*/
    java.sql.Timestamp timestamp = new java.sql.Timestamp(start.getTime());

    log.debug("Parametro d'ingresso query: "+timestamp);
    preparedStatement.setTimestamp(1, timestamp);

and i have this query

SELECT
DATA
FROM MY_TABLE
WHERE DATA > ?

the  column DATA is DATA_TYPE = DATE   in a Oracle db

the compare in the query not working,
what am I doing wrong?


问:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

```<code>String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);
</code>```

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

答:
java is kind of different to python....

this is invalid as reflected in the doc

```<code> substring(5, 2)
</code>```

the second integer must be bigger than the first one

```<code>if (endIndex > value.length) {
      throw new StringIndexOutOfBoundsException(endIndex);
}
</code>```

if you mean to get 2 chars after the first parameter then do something like

```<code>substring(5, 5 + 2);
</code>```

or even better:

```<code>int beginIndex = 5;
String dateB = date.substring(beginIndex, beginIndex + 2);
</code>```

Body:
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

Body:
java is kind of different to python....

this is invalid as reflected in the doc

 substring(5, 2)

the second integer must be bigger than the first one

if (endIndex > value.length) {
      throw new StringIndexOutOfBoundsException(endIndex);
}

if you mean to get 2 chars after the first parameter then do something like

substring(5, 5 + 2);

or even better:

int beginIndex = 5;
String dateB = date.substring(beginIndex, beginIndex + 2);


问:
how to use babel decorators for mobx in project generated by create-react-app
I created a project create-react-app and installed mobx, and mobx-react
modules when I use this simple state class in my project I always got this error below.

```<code>import {autorun, observable} from 'mobx'

export default class AppState{
    @observable teams =[]

    @computed addNewTeam(){
        this.teams.push('Team 1')
    }
}

autorun(()=>{
    console.log(this.teams[0]);
})
</code>```

Also installed Babel with this guide

how can fix this issue?

答:
There were 2 possible solution for me, one is here; using mobx without decorators and babeljs transpiler.

second and more close to my need is here; starter kit which using custom react scripts including babeljs config

Body:
I created a project create-react-app and installed mobx, and mobx-react
modules when I use this simple state class in my project I always got this error below.

import {autorun, observable} from 'mobx'

export default class AppState{
    @observable teams =[]

    @computed addNewTeam(){
        this.teams.push('Team 1')
    }
}

autorun(()=>{
    console.log(this.teams[0]);
})

Also installed Babel with this guide

how can fix this issue?


问:
Move UIView with relation to touch
i'm trying to move a UIView with relation to the user's touches.

Here's what I have at the moment:

```<code>int oldX, oldY;
BOOL dragging;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation)) {
        dragging = YES;
        oldX = touchLocation.x;
        oldY = touchLocation.y;
    }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation) && dragging) {
        CGRect frame;
        frame.origin.x = (window.frame.origin.x + touchLocation.x - oldX);
        frame.origin.y = (window.frame.origin.y + touchLocation.y - oldY);
        window.frame = frame;

    }

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    dragging = NO;
}
</code>```

The view keeps flickering from one location to another, and I don't know what else to do.

Any help appreciated.

答:
What you want is to use a UIPanGestureRecognizer, introduced in iOS 3.2. You use it with something as easy as this (from your UIViewController subclass):

```<code>-(void)viewDidLoad;
{
   [super viewDidLoad];
   UIPanGestureRecognizer* pgr = [[UIPanGestureRecognizer alloc]
                                       initWithTarget:self
                                               action:@selector(handlePan:)];
   [self.panningView addGestureRecognizer:pgr];
   [pgr release];
}

-(void)handlePan:(UIPanGestureRecognizer*)pgr;
{
   if (pgr.state == UIGestureRecognizerStateChanged) {
      CGPoint center = pgr.view.center;
      CGPoint translation = [pgr translationInView:pgr.view];
      center = CGPointMake(center.x + translation.x,
                           center.y + translation.y);
      pgr.view.center = center;
      [pgr setTranslation:CGPointZero inView:pgr.view];
   }
}
</code>```

Title: Move UIView with relation to touch

Body:
i'm trying to move a UIView with relation to the user's touches.

Here's what I have at the moment:

int oldX, oldY;
BOOL dragging;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation)) {
        dragging = YES;
        oldX = touchLocation.x;
        oldY = touchLocation.y;
    }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation) && dragging) {
        CGRect frame;
        frame.origin.x = (window.frame.origin.x + touchLocation.x - oldX);
        frame.origin.y = (window.frame.origin.y + touchLocation.y - oldY);
        window.frame = frame;

    }

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    dragging = NO;
}

The view keeps flickering from one location to another, and I don't know what else to do.

Any help appreciated.

Body:
What you want is to use a UIPanGestureRecognizer, introduced in iOS 3.2. You use it with something as easy as this (from your UIViewController subclass):

-(void)viewDidLoad;
{
   [super viewDidLoad];
   UIPanGestureRecognizer* pgr = [[UIPanGestureRecognizer alloc]
                                       initWithTarget:self
                                               action:@selector(handlePan:)];
   [self.panningView addGestureRecognizer:pgr];
   [pgr release];
}

-(void)handlePan:(UIPanGestureRecognizer*)pgr;
{
   if (pgr.state == UIGestureRecognizerStateChanged) {
      CGPoint center = pgr.view.center;
      CGPoint translation = [pgr translationInView:pgr.view];
      center = CGPointMake(center.x + translation.x,
                           center.y + translation.y);
      pgr.view.center = center;
      [pgr setTranslation:CGPointZero inView:pgr.view];
   }
}


答:
read javadoc for java.lang.String.substring(int, int)</p>

```<code>String date = "14000101";
    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
    System.out.println(repayDate);
</code>```

Title: java.lang.StringIndexOutOfBoundsException: String index out of range: -4

Body:
read javadoc for java.lang.String.substring(int, int)

String date = "14000101";
    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
    System.out.println(repayDate);


问:
How to get the inner array from json in android?
```<code>{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}
</code>```

This my json response.This json have a inner array how can i get the value

This my code:

```<code>class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }
</code>```

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

答:
May this will help you </p>

```<code>JSONObject mainObj = = new JSONObject(response);

JSONArray Suggestionslist = mainObj.getJSONArray("Suggestions");
    if(Suggestionslist != null){

    for(int i = 0; i < Suggestionslist.length();i++){
             JSONObject elem = list.getJSONObject(i);
            if(elem != null){
                 JSONArray Itinerary = elem.getJSONArray("Itinerary_"+ (i+1));
                if(Itinerary != null){

                       for(int j = 0; j < Itinerary.length();j++){
                        JSONObject innerElem = Itinerary.getJSONObject(j);
                        if(innerElem != null){
                            String Cities = innerELem.getString("Cities");
                            String Citieids = innerElem.getString("Citieids");
                            String Kms = innerElem.getString("Kms");
                        }
                    }

                 }
    }

}
</code>```

Body:
{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}

This my json response.This json have a inner array how can i get the value

This my code:

class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

Body:
May this will help you

JSONObject mainObj = = new JSONObject(response);

JSONArray Suggestionslist = mainObj.getJSONArray("Suggestions");
    if(Suggestionslist != null){

    for(int i = 0; i < Suggestionslist.length();i++){
             JSONObject elem = list.getJSONObject(i);
            if(elem != null){
                 JSONArray Itinerary = elem.getJSONArray("Itinerary_"+ (i+1));
                if(Itinerary != null){

                       for(int j = 0; j < Itinerary.length();j++){
                        JSONObject innerElem = Itinerary.getJSONObject(j);
                        if(innerElem != null){
                            String Cities = innerELem.getString("Cities");
                            String Citieids = innerElem.getString("Citieids");
                            String Kms = innerElem.getString("Kms");
                        }
                    }

                 }
    }

}


问:
Using SQLBulkCopy to Insert into Related Tables
I am using SQL Bulk copy to read data form Excel to SQL DB. In the Database, I have two tables into which I need to insert this data from Excel. Table A and Table B which uses the ID(primary Key IDENTITY) from Table A to insert corresponding row records into Table B.

I am able to insert into one table (Table A) using the following Code.

```<code>using (SqlConnection connection = new SqlConnection(strConnection)) {
    connection.Open();
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
        bulkCopy.DestinationTableName = "dbo.[EMPLOYEEINFO]";
        try {
            // Write from the source to the destination.
            SqlBulkCopyColumnMapping NameMap = new SqlBulkCopyColumnMapping(data.Columns[0].ColumnName, "EmployeeName");
            SqlBulkCopyColumnMapping GMap = new SqlBulkCopyColumnMapping(data.Columns[1].ColumnName, "Gender");
            SqlBulkCopyColumnMapping CMap = new SqlBulkCopyColumnMapping(data.Columns[2].ColumnName, "City");
            SqlBulkCopyColumnMapping AMap = new SqlBulkCopyColumnMapping(data.Columns[3].ColumnName, "HomeAddress");

            bulkCopy.ColumnMappings.Add(NameMap);
            bulkCopy.ColumnMappings.Add(GMap);
            bulkCopy.ColumnMappings.Add(CMap);
            bulkCopy.ColumnMappings.Add(AMap);

            bulkCopy.WriteToServer(data);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}
</code>```

But then I am not sure how to extend it for two tables which are bound by Foreign Key relationship.Especially, Table B uses the Identity value from Table A Any example would be great. I googled it and none of the threads on SO couldn't give a Working example.

答:
AFAIK bulk copy can only be used to upload into a single table. In order to achieve a bulk upload into two tables, you will therefore need two bulk uploads.  Your problem comes from using a foreign key which is an identity.  You can work around this, however. I am pretty sure that bulk copy uploads sequentially, which means that if you upload 1,000 records and the last record gets an ID of 10,197, then the ID of the first record is 9,198!  So my recommendation would be to upload your first table, check the max id after the upload, deduct the number of records and work from there!

Of course in a high use database, someone might insert after you, so you would need to get the top id by selecting the record which matches your last one by other details (assuming a combination of (upto) all fields would be guaranteed to be unique).  Only you know if this is likely to be a problem.

The alternative is not to use an identity column in the first place, but I presume you have no control over the design? In my younger days, I made the mistake of using identities, I never do now. They always find a way of coming back to bite!

For example to add the second data:

```<code>DataTable secondTable = new DataTable("SecondTable");
secondTable.Columns.Add("ForeignKey", typeof(int));
secondTable.Columns.Add("DataField", typeof(yourDataType));
</code>```

...

Add data to secondTable.

(Depends on format of second data)

```<code>int cnt = 0;
foreach (var d in mySecondData)
{
    DataRow newRow = secondTable.NewRow();
    newRow["ForeignKey"] = cnt;
    newRow["DataField"] = d.YourData;
    secondTable.Rows.Add(newRow);
}
</code>```

Then after you found out the starting identity (int startID).

```<code>for (int i = 0; i < secondTable.Rows.Count; i++)
{
    secondTable["ForeignKey"] = secondTable["ForeignKey"] + startID;
}
</code>```

Finally:

```<code>bulkCopy.DestinationTableName = "YourSecondTable";
bulkCopy.WriteToServer(secondTable);
</code>```

Body:
I am using SQL Bulk copy to read data form Excel to SQL DB. In the Database, I have two tables into which I need to insert this data from Excel. Table A and Table B which uses the ID(primary Key IDENTITY) from Table A to insert corresponding row records into Table B.

I am able to insert into one table (Table A) using the following Code.

using (SqlConnection connection = new SqlConnection(strConnection)) {
    connection.Open();
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
        bulkCopy.DestinationTableName = "dbo.[EMPLOYEEINFO]";
        try {
            // Write from the source to the destination.
            SqlBulkCopyColumnMapping NameMap = new SqlBulkCopyColumnMapping(data.Columns[0].ColumnName, "EmployeeName");
            SqlBulkCopyColumnMapping GMap = new SqlBulkCopyColumnMapping(data.Columns[1].ColumnName, "Gender");
            SqlBulkCopyColumnMapping CMap = new SqlBulkCopyColumnMapping(data.Columns[2].ColumnName, "City");
            SqlBulkCopyColumnMapping AMap = new SqlBulkCopyColumnMapping(data.Columns[3].ColumnName, "HomeAddress");

            bulkCopy.ColumnMappings.Add(NameMap);
            bulkCopy.ColumnMappings.Add(GMap);
            bulkCopy.ColumnMappings.Add(CMap);
            bulkCopy.ColumnMappings.Add(AMap);

            bulkCopy.WriteToServer(data);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}

But then I am not sure how to extend it for two tables which are bound by Foreign Key relationship.Especially, Table B uses the Identity value from Table A Any example would be great. I googled it and none of the threads on SO couldn't give a Working example.

Body:
AFAIK bulk copy can only be used to upload into a single table. In order to achieve a bulk upload into two tables, you will therefore need two bulk uploads.  Your problem comes from using a foreign key which is an identity.  You can work around this, however. I am pretty sure that bulk copy uploads sequentially, which means that if you upload 1,000 records and the last record gets an ID of 10,197, then the ID of the first record is 9,198!  So my recommendation would be to upload your first table, check the max id after the upload, deduct the number of records and work from there!

Of course in a high use database, someone might insert after you, so you would need to get the top id by selecting the record which matches your last one by other details (assuming a combination of (upto) all fields would be guaranteed to be unique).  Only you know if this is likely to be a problem.

The alternative is not to use an identity column in the first place, but I presume you have no control over the design? In my younger days, I made the mistake of using identities, I never do now. They always find a way of coming back to bite!

For example to add the second data:

DataTable secondTable = new DataTable("SecondTable");
secondTable.Columns.Add("ForeignKey", typeof(int));
secondTable.Columns.Add("DataField", typeof(yourDataType));

...

Add data to secondTable.

(Depends on format of second data)

int cnt = 0;
foreach (var d in mySecondData)
{
    DataRow newRow = secondTable.NewRow();
    newRow["ForeignKey"] = cnt;
    newRow["DataField"] = d.YourData;
    secondTable.Rows.Add(newRow);
}

Then after you found out the starting identity (int startID).

for (int i = 0; i < secondTable.Rows.Count; i++)
{
    secondTable["ForeignKey"] = secondTable["ForeignKey"] + startID;
}

Finally:

bulkCopy.DestinationTableName = "YourSecondTable";
bulkCopy.WriteToServer(secondTable);


问:
Java regex expression to include underscore
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

```<code>String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);
</code>```

I tried the below options:

```<code>String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"
</code>```

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

答:
If you want to capture everything between $ and assert that underscore is present use this regex:

```<code>\\$(.*?)_([^_]*)\\$
</code>```

(.*?) matches one symbol and next it tries to match underscore. If it doesn't, (.*?) matches this symbol and regex tries to match underscore again.

After underscore is matched, ([^_]*) matches everything that is not underscore for 0 or more times.

Body:
I am trying with the below line, which ignores underscore but I want to change it to include underscore.

String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);

I tried the below options:

String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"

It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like:
"$SF_Update$"
"$SF_Updateone"
Please provide a solution.

Body:
If you want to capture everything between $ and assert that underscore is present use this regex:

\\$(.*?)_([^_]*)\\$

(.*?) matches one symbol and next it tries to match underscore. If it doesn't, (.*?) matches this symbol and regex tries to match underscore again.

After underscore is matched, ([^_]*) matches everything that is not underscore for 0 or more times.


问:
What is the difference between valueforKey:, objectForKey:, and valueForKeyPath:?
I have 2 questions:

What is the difference between valueForKey: and objectForKey:? Is it that one is for NSDictionarys (objectForKey:) and for others it is valueforKey:, or is it the reverse?

Also what is the difference between valueForKey: and valueForKeyPath:? Has it got something to do with Core Data?

Please help.

答:
valueForKey: and valueAtKeyPath: are methods defined in the NSKeyValueCoding informal  protocol, and default implementations for both are provided by the root class NSObject.

objectForKey: is a method on NSDictionary.

valueForKey: takes a key to a property, while valueAtKeyPath: takes a so-called keypath. A keypath is a period-delimeted path to a specific property, like @"relationship.property".


问:
How can I merge 2 spotfire tables by a regex match?
I am working on a spotfire tool, and I am using a calculated column in my main data table to group data rows into 'families' through a regex match. For example, one row might have a 'name' of ABC1234xyz, so it would be part of the ABC family because it contains the string 'ABC'. Another rows could be something like AQRST31x2af, and belong to the QRST family. The main point is that the 'family' is decided by matching a substring in the the name, but that substring could be any length, and isn't necessarily the beginning of the name string.

Right now I am doing this by a large nested If statement with a calculated column. However, this is tedious for adding new families, and maintaining the current list of families. What I would like to do is create a table with 2 columns, the string match and the family name. Then, I would like to match from this table to determine family instead of the nested if. So, it might look like the below tables:

```<code>Match Table:

id_string | family
----------------------
ABC       | ABC
QRST      | QRST
SUP       | Super

Main Data Table:

name        | data        | family
---------------------------------------
ABC1234     | 1.02342     | ABC
ABC1215     | 1.23749     | ABC
AQRST31x2af | 1.04231     | QRST
BQRST32x2ac | 1.12312     | QRST
1903xSUP    | 1.51231     | Super
1204xSUP    | 1.68123     | Super
</code>```

If you have any suggestions, I would appreciate it.

Thanks.

答:
@wcase6- As far as I know, you cannot add columns from one table to another based on expression. When you add columns, the value in one matching column should exactly match with the other one.

Instead, you can try the below solution on your 'Main Data Table'.

Note: This solution is based on the scenarios posted. If there are more/different scenarios, you might have to tweak the custom expressions provided.

Step 1: Add a calculated column 'ID_string' which ignores lower case letters and digits.

```<code>Trim(RXReplace([Name],"[a-z0-9]","","g"))
</code>```

Step 2: Add a calculated column 'family'.

```<code>If([ID_string]="SUP","Super",If(Len([ID_string])>3,right([ID_string],4),[ID_string]))
</code>```

Final Output:

Hope this helps!

Body:
I am working on a spotfire tool, and I am using a calculated column in my main data table to group data rows into 'families' through a regex match. For example, one row might have a 'name' of ABC1234xyz, so it would be part of the ABC family because it contains the string 'ABC'. Another rows could be something like AQRST31x2af, and belong to the QRST family. The main point is that the 'family' is decided by matching a substring in the the name, but that substring could be any length, and isn't necessarily the beginning of the name string.

Right now I am doing this by a large nested If statement with a calculated column. However, this is tedious for adding new families, and maintaining the current list of families. What I would like to do is create a table with 2 columns, the string match and the family name. Then, I would like to match from this table to determine family instead of the nested if. So, it might look like the below tables:

Match Table:

id_string | family
----------------------
ABC       | ABC
QRST      | QRST
SUP       | Super

Main Data Table:

name        | data        | family
---------------------------------------
ABC1234     | 1.02342     | ABC
ABC1215     | 1.23749     | ABC
AQRST31x2af | 1.04231     | QRST
BQRST32x2ac | 1.12312     | QRST
1903xSUP    | 1.51231     | Super
1204xSUP    | 1.68123     | Super

If you have any suggestions, I would appreciate it.

Thanks.

Body:
@wcase6- As far as I know, you cannot add columns from one table to another based on expression. When you add columns, the value in one matching column should exactly match with the other one.

Instead, you can try the below solution on your 'Main Data Table'.

Note: This solution is based on the scenarios posted. If there are more/different scenarios, you might have to tweak the custom expressions provided.

Step 1: Add a calculated column 'ID_string' which ignores lower case letters and digits.

Trim(RXReplace([Name],"[a-z0-9]","","g"))

Step 2: Add a calculated column 'family'.

If([ID_string]="SUP","Super",If(Len([ID_string])>3,right([ID_string],4),[ID_string]))

Final Output:

Hope this helps!


问:
SAPUI5 ObjectListItem icon not aligned
I'm using an ObjectListItem with an icon in my SAPUI5 but the icon isn't always aligned to the text.

I have:

```<code><List>
<ObjectListItem title="title" type="Active" number="{/data/value}"
icon="{= ${/data/value === '1' ? 'sap-icon://accept' : 'sap-icon://decline'}">
</ObjectListItem>
</List>
</code>```

and styles:

```<code>.sapMObjLIconDiv {
    float: right;
    height: 0;}

.sapMObjLIcon.sapUiIcon {
    font-size: 18px;
    line-height: 1.5rem;
    margin: 0 auto;}
</code>```

and value has different lengths and sometimes the icon appears over the text:

Thanks

答:
Your custom CSS is the reason for the overlapping. You could add a margin to the the text so that it does not overlap the icon.

```<code>.sapMObjLNumberDiv{
    margin-right:60px;
}
</code>```

Also I would recommend that you add a custom CSS class to the List and apply all your styling relative to that class. This will prevent any issues with other controls where similar standard classes are used.

Title: SAPUI5 ObjectListItem icon not aligned

Body:
I'm using an ObjectListItem with an icon in my SAPUI5 but the icon isn't always aligned to the text.

I have:

<List>
<ObjectListItem title="title" type="Active" number="{/data/value}"
icon="{= ${/data/value === '1' ? 'sap-icon://accept' : 'sap-icon://decline'}">
</ObjectListItem>
</List>

and styles:

.sapMObjLIconDiv {
    float: right;
    height: 0;}

.sapMObjLIcon.sapUiIcon {
    font-size: 18px;
    line-height: 1.5rem;
    margin: 0 auto;}

and value has different lengths and sometimes the icon appears over the text:

Thanks

Body:
Your custom CSS is the reason for the overlapping. You could add a margin to the the text so that it does not overlap the icon.

.sapMObjLNumberDiv{
    margin-right:60px;
}

Also I would recommend that you add a custom CSS class to the List and apply all your styling relative to that class. This will prevent any issues with other controls where similar standard classes are used.


问:
Can not access disposed object in CellEditFinished event popup messages of ObjectListView
When I click on the 'Open Modal Window' button in [Main form], it shows the
[subform] that is built with a data list by using the ObjectListView component.

When I click on the "Age" column to edit it and changed the value in the cell to be a non zero value, then click on the blank of the ObjectListView component(if I press Enter, the exception will not come out), it popup a message. I left this message in front of all the opened windows and wait 10 seconds for the application timeout. At that time, an exception shows:

Cannot access a disposed object. Object name: 'ObjectListView'.

Here is the code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    modalForm = new Form2();
    StartTimeOutTimer();
    var result = modalForm.ShowDialog(this);
}

private void ProcessTimeOut()
{
    timer1.Stop();
    seconds = 0;
    List<Form> openForms = Application.OpenForms.Cast<Form>().Where(frm => !string.Equals(frm.Name, "Form1") && !frm.IsDisposed).ToList();
    for (var i = openForms.Count - 1; i >= 0; i--)
    {
        openForms[i].Dispose();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    seconds++;
    if (seconds == 10)
    {
        ProcessTimeOut();
    }
}
</code>```

the exception come out in this line:

var result = modalForm.ShowDialog(this);

My reputation is too low to upload more links, so I post the code to OneDrive.
The sample code and solution is here:

https://1drv.ms/u/s!AmQYEYkCV6gqgw6iPMVFPBKlSx1V

I tried to add the source code of ObjectListView in my solution, and the error occurred in the GetHeaderControl method in the source code of v2.9.0

Please download my sample code to reproduce the exception. How do I fix this exception? Any suggestion will be appreciated.

答:
I download the code and it seems a bug of objeclistview. I cannot fix it, but I have a workaround to resolve your issue: you can ShowDialog() by asynchronously, like this:</p>

```<code> this.BeginInvoke(new Action(() => {
         var myMsgBox = new MyMsgBox("Must be 0");
         myMsgBox.ShowDialog();
      }));
</code>```

Body:
When I click on the 'Open Modal Window' button in [Main form], it shows the
[subform] that is built with a data list by using the ObjectListView component.

When I click on the "Age" column to edit it and changed the value in the cell to be a non zero value, then click on the blank of the ObjectListView component(if I press Enter, the exception will not come out), it popup a message. I left this message in front of all the opened windows and wait 10 seconds for the application timeout. At that time, an exception shows:

Cannot access a disposed object. Object name: 'ObjectListView'.

Here is the code:

private void button1_Click(object sender, EventArgs e)
{
    modalForm = new Form2();
    StartTimeOutTimer();
    var result = modalForm.ShowDialog(this);
}

private void ProcessTimeOut()
{
    timer1.Stop();
    seconds = 0;
    List<Form> openForms = Application.OpenForms.Cast<Form>().Where(frm => !string.Equals(frm.Name, "Form1") && !frm.IsDisposed).ToList();
    for (var i = openForms.Count - 1; i >= 0; i--)
    {
        openForms[i].Dispose();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    seconds++;
    if (seconds == 10)
    {
        ProcessTimeOut();
    }
}

the exception come out in this line:

var result = modalForm.ShowDialog(this);

My reputation is too low to upload more links, so I post the code to OneDrive.
The sample code and solution is here:

https://1drv.ms/u/s!AmQYEYkCV6gqgw6iPMVFPBKlSx1V

I tried to add the source code of ObjectListView in my solution, and the error occurred in the GetHeaderControl method in the source code of v2.9.0

Please download my sample code to reproduce the exception. How do I fix this exception? Any suggestion will be appreciated.

Body:
I download the code and it seems a bug of objeclistview. I cannot fix it, but I have a workaround to resolve your issue: you can ShowDialog() by asynchronously, like this:

 this.BeginInvoke(new Action(() => {
         var myMsgBox = new MyMsgBox("Must be 0");
         myMsgBox.ShowDialog();
      }));


问:
Is Grails worth it?
This is half rant, half question.

Is it worth using Grails? I'm trying to develop a relatively simple database-driven web application. My expertise is in Java, so naturally Grails seemed like a good choice. At first I thought of using Spring, JPA and Hibernate, but I’ve used that previously and have run into all sorts of tedious configuration and coding work. Grails advertises itself as solving this.

My biggest frustration with Grails is all of the little things that don't work. What I mean is that it doesn't work as one would intuitively think it should. It's very rough around the edges. I run into problems constantly. Sometimes it's my lack of Grails understanding — other times I've discovered legitimate Grails bugs.

One major issue is the lack of good Eclipse integration. There is a Groovy and Grails plugin, but it doesn't do much other than syntax highlighting. Calling Groovy from Java and vice versa is very painful to configure. Not having good IDE support is a major bummer.

What happens is I sit down trying to develop my web application. At the end of the day I realize that I've spent about 85% of the day debugging Grails-related issues. If it isn't Eclipse problems then it's eager loading, fetching in the view, one-to-many relationships, weird empty file bug behavior, a weird property/getter bug — it just goes on and on. This is just a sample of the issues I ran into today. My last sit-down with Grails yielded a whole bunch of different issues.

I sometimes wonder if it's worth it. I'm curious if others have experienced this. Are there people actually using Grails to productively crank out a web application? Are there other frameworks for rapid web development that I should be considering?

答:
Totally.  There are so many Java frameworks that the bar is set quite high for newcomers, and it's a testament to Grails that it was able to rise above in such a crowded space.

It still has a few edges that are sharp, but those are just a matter of time before they're matted down, the underlying project is VERY much worth it.

OwnerDisplayName: Steve Kuo

Title: Is Grails worth it?

LastEditorDisplayName: Steve Kuo

OwnerDisplayName: hendrixski


问:
Play sound in Angular 4
I'm working on an Electron app with Angular 4. I want to play sound on some specific action. Is there any module or code for that? It can be in the angular 4 or if electron is providing some service for that it should also work

As I want to play it on some action I can't use the HTML audio tag and audio() of javascript

I only want to play the sound of 2-3 seconds so no other functionalities are needed.

It can be of electron or Angular 4 any of them can work...

答:
As per Robin's comment, i have checked that link we can use it using the audio() object in the ts file like this:

this.audio = new Audio();
this.audio.src = "../../../assets/sounds/button_1.mp3";
this.audio.load();
this.audio.play();
```

Title: Play sound in Angular 4

ContentLicense: CC BY-SA 4.0


问:
count number of rows for a timestamp
I am working on the dataset

https://pastebin.com/PEFUspiU

I have to group it and count how many requests are there for a particular period of time and then it will be easy to draw me a chart time vs the number of requests.

for an example

```<code>**timestamp - number of request**

21-06-2016 09:00:00 - 2

21-06-2016 10:00:00 - 1

21-06-2016 11:00:00 - 5
</code>```

how can I get this count?

Thanks

P.S I tried use data['timestamp'].value_counts() but got errors:

```<code>import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6

dateparse = lambda dates: pd.datetime.strptime(dates, '%d-%m-%Y %H:%M:%S')
data = pd.read_csv('/home/amfirnas/Desktop/localhost_access_log.2016-06-21.csv',
                   parse_dates=['timestamp'], index_col='timestamp',date_parser=dateparse)

print data.head(25)

# print data['time'].value_counts()

# print data.groupby(['time']).groups.keys()

ts = data['timestamp'].value_counts()

# plt.plot(ts)
# plt.show()
</code>```

答:
If you want to count them for each hour, instead of value_count() you can group them and then count, for that, make sure that your timestamp is pandas datetime:</p>

```<code>df['timestamp'] = pd.to_datetime(df['timestamp'])
df.groupby(pd.Grouper(key='timestamp', freq="1H")).count()
</code>```

Title: count number of rows for a timestamp

Body:
I am working on the dataset

https://pastebin.com/PEFUspiU

I have to group it and count how many requests are there for a particular period of time and then it will be easy to draw me a chart time vs the number of requests.

for an example

**timestamp - number of request**

21-06-2016 09:00:00 - 2

21-06-2016 10:00:00 - 1

21-06-2016 11:00:00 - 5

how can I get this count?

Thanks

P.S I tried use data['timestamp'].value_counts() but got errors:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6

dateparse = lambda dates: pd.datetime.strptime(dates, '%d-%m-%Y %H:%M:%S')
data = pd.read_csv('/home/amfirnas/Desktop/localhost_access_log.2016-06-21.csv',
                   parse_dates=['timestamp'], index_col='timestamp',date_parser=dateparse)

print data.head(25)

# print data['time'].value_counts()

# print data.groupby(['time']).groups.keys()

ts = data['timestamp'].value_counts()

# plt.plot(ts)
# plt.show()

Body:
If you want to count them for each hour, instead of value_count() you can group them and then count, for that, make sure that your timestamp is pandas datetime:

df['timestamp'] = pd.to_datetime(df['timestamp'])
df.groupby(pd.Grouper(key='timestamp', freq="1H")).count()


问:
Fire event on binding values to dropdown
I need to manipulate the values during the bind of those to the select. Which of the event can pass the binding value as parameter and return the same with a added property or fetch the option direct and return with adding a property?

Something like this,

```<code>@Html.DropDownListFor(m => m.UserId, Model.UserList, "Select Name", new { @class = "target", @id = "ddlNames" })

$( ".target" ).xxx(function() {
  //Fetch the options here and add a property (selected="selected")
});
</code>```

Any ideas?

答:
Yes , you can. Iterate over options.

```<code>// initially set options to select.
$( ".target" ).xxx(function() {
  $("select option").each(function(){
  if ($(this).text() == "something")
    $(this).attr("selected","selected");
 });
});
</code>```

Remember that you can select only one option at a time. So make sure you know the option which you want to select.

Body:
I need to manipulate the values during the bind of those to the select. Which of the event can pass the binding value as parameter and return the same with a added property or fetch the option direct and return with adding a property?

Something like this,

@Html.DropDownListFor(m => m.UserId, Model.UserList, "Select Name", new { @class = "target", @id = "ddlNames" })

$( ".target" ).xxx(function() {
  //Fetch the options here and add a property (selected="selected")
});

Any ideas?

Body:
Yes , you can. Iterate over options.

// initially set options to select.
$( ".target" ).xxx(function() {
  $("select option").each(function(){
  if ($(this).text() == "something")
    $(this).attr("selected","selected");
 });
});

Remember that you can select only one option at a time. So make sure you know the option which you want to select.


问:
Converting Integer to Long
I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:

```<code>@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}
</code>```

And use this method like:

```<code>Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
</code>```

or

```<code>Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
</code>```

The problem is that I can't seem to cast Integer to Long:

```<code>java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
</code>```

Is there a better way to achieve this?

I am using Java 1.6.

答:
If the Integer is not null

```<code>Integer i;
Long long = Long.valueOf(i);
</code>```

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

Title: Converting Integer to Long

Body:
I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:

@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}

And use this method like:

Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);

or

Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);

The problem is that I can't seem to cast Integer to Long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Is there a better way to achieve this?

I am using Java 1.6.

Body:
If the Integer is not null

Integer i;
Long long = Long.valueOf(i);

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.


问:
Error addressing memory when using`esp*scale
The memory addressing general form (found it here) is:

```<code>[base + index*scale + disp]
</code>```

When I try to assemble/compile the following code:

```<code>mov eax, [ebx + esp*4 + 2]
</code>```

NASM gives the following error: "error: invalid effective address".

But the following works fine:

```<code> mov eax, [ebx + esp + 2]
</code>```

And the following works fine also:

```<code>mov eax, [ebx + ecx*4 + 2]
</code>```

So it looks like using a scale with esp as the index register causes the error.

Am I correct? and where can I read more about this (other than the Intel manual, which is 4000+ pages long!).

答:
The "rules" here are covered well in the Intel IA-32 Architecture manuals. In particular, Volume 1: Basic Architecture contains the following information:

3.7.5 Specifying an Offset

The offset part of a memory address can be specified directly as a static value (called a displacement) or through an address computation made up of one or more of the following components:

Displacement — An 8-, 16-, or 32-bit value.

Base — The value in a general-purpose register.

Index — The value in a general-purpose register.

Scale factor — A value of 2, 4, or 8 that is multiplied by the index value.

The offset which results from adding these components is called an effective address. Each of these components can have either a positive or negative (2s complement) value, with the exception of the scaling factor. Figure 3-11 shows all the possible ways that these components can be combined to create an effective address in the selected segment.

  Figure 3-11. Offset (or Effective Address) Computation

The uses of general-purpose registers as base or index components are restricted in the following manner:

The ESP register cannot be used as an index register.

When the ESP or EBP register is used as the base, the SS segment is the default segment. In all other cases, the DS segment is the default segment.

The base, index, and displacement components can be used in any combination, and any of these components can be NULL. A scale factor may be used only when an index also is used. Each possible combination is useful for data structures commonly used by programmers in high-level languages and assembly language.

The following addressing modes suggest uses for common combinations of address components.

Displacement ⎯ A displacement alone represents a direct (uncomputed) offset to the operand. Because the displacement is encoded in the instruction, this form of an address is sometimes called an absolute or static address. It is commonly used to access a statically allocated scalar operand.

Base ⎯ A base alone represents an indirect offset to the operand. Since the value in the base register can change, it can be used for dynamic storage of variables and data structures.

Base + Displacement ⎯ A base register and a displacement can be used together for two distinct purposes:

As an index into an array when the element size is not 2, 4, or 8 bytes—The displacement component encodes the static offset to the beginning of the array. The base register holds the results of a calculation to determine the offset to a specific element within the array.

To access a field of a record: the base register holds the address of the beginning of the record, while the displacement is a static offset to the field.

An important special case of this combination is access to parameters in a procedure activation record. A procedure activation record is the stack frame created when a procedure is entered. Here, the EBP register is the best choice for the base register, because it automatically selects the stack segment. This is a compact encoding for this common function.

(Index ∗ Scale) + Displacement ⎯ This address mode offers an efficient way to index into a static array when the element size is 2, 4, or 8 bytes. The displacement locates the beginning of the array, the index register holds the subscript of the desired array element, and the processor automatically converts the subscript into an index by applying the scaling factor.

Base + Index + Displacement ⎯ Using two registers together supports either a two-dimensional array (the displacement holds the address of the beginning of the array) or one of several instances of an array of records (the displacement is an offset to a field within the record).

Base + (Index ∗ Scale) + Displacement ⎯ Using all the addressing components together allows efficient indexing of a two-dimensional array when the elements of the array are 2, 4, or 8 bytes in size.

Read and follow these rules, and you will be fine. You don't need to read all 4000 pages, but you really should be familiar enough with the manual's contents that you can look stuff up when needed (like when the assembler coughs up an error message). It's pretty difficult to program a microprocessor without being at all familiar with its design or programming model.

```<code>mov eax, [ebx + esp*4 + 2]
</code>```

is indeed an invalid addressing mode because you are trying to use ESP as an index. Figure 3-11 says that you can't use ESP as an index, as does the first bullet point immediately underneath. The logic here is that ESP is the stack pointer, which contains an address.

It doesn't make sense to scale an address. it does, however, make sense to offset from an address, which is why ESP can be used as a base. That's why this is fine:

```<code>mov eax, [ebx + esp + 2]
</code>```

This is also fine:

```<code>mov eax, [ebx + ecx*4 + 2]
</code>```

because ECX can be used as an index.

In the comments, you present this instruction:

```<code>mov eax, [ebx + esp + 2]
</code>```

As Ross Ridge already replied, this is legal because you aren't actually scaling ESP, so the assembler is smart enough to use ESP as the base and EBX as the index. In other words, it has reordered it to:

```<code>mov eax, [2 + esp + ebx]
          ^    ^     ^
          |    |     |
displacement   |    index
              base
</code>```

with an implicit 1 as the scale factor.

Body:
The memory addressing general form (found it here) is:

[base + index*scale + disp]

When I try to assemble/compile the following code:

mov eax, [ebx + esp*4 + 2]

NASM gives the following error: "error: invalid effective address".

But the following works fine:

 mov eax, [ebx + esp + 2]

And the following works fine also:

mov eax, [ebx + ecx*4 + 2]

So it looks like using a scale with esp as the index register causes the error.

Am I correct? and where can I read more about this (other than the Intel manual, which is 4000+ pages long!).

Body:
The "rules" here are covered well in the Intel IA-32 Architecture manuals. In particular, Volume 1: Basic Architecture contains the following information:

3.7.5 Specifying an Offset

The offset part of a memory address can be specified directly as a static value (called a displacement) or through an address computation made up of one or more of the following components:

Displacement — An 8-, 16-, or 32-bit value.

Base — The value in a general-purpose register.

Index — The value in a general-purpose register.

Scale factor — A value of 2, 4, or 8 that is multiplied by the index value.

The offset which results from adding these components is called an effective address. Each of these components can have either a positive or negative (2s complement) value, with the exception of the scaling factor. Figure 3-11 shows all the possible ways that these components can be combined to create an effective address in the selected segment.

  Figure 3-11. Offset (or Effective Address) Computation

The uses of general-purpose registers as base or index components are restricted in the following manner:

The ESP register cannot be used as an index register.

When the ESP or EBP register is used as the base, the SS segment is the default segment. In all other cases, the DS segment is the default segment.

The base, index, and displacement components can be used in any combination, and any of these components can be NULL. A scale factor may be used only when an index also is used. Each possible combination is useful for data structures commonly used by programmers in high-level languages and assembly language.

The following addressing modes suggest uses for common combinations of address components.

Displacement ⎯ A displacement alone represents a direct (uncomputed) offset to the operand. Because the displacement is encoded in the instruction, this form of an address is sometimes called an absolute or static address. It is commonly used to access a statically allocated scalar operand.

Base ⎯ A base alone represents an indirect offset to the operand. Since the value in the base register can change, it can be used for dynamic storage of variables and data structures.

Base + Displacement ⎯ A base register and a displacement can be used together for two distinct purposes:

As an index into an array when the element size is not 2, 4, or 8 bytes—The displacement component encodes the static offset to the beginning of the array. The base register holds the results of a calculation to determine the offset to a specific element within the array.

To access a field of a record: the base register holds the address of the beginning of the record, while the displacement is a static offset to the field.

An important special case of this combination is access to parameters in a procedure activation record. A procedure activation record is the stack frame created when a procedure is entered. Here, the EBP register is the best choice for the base register, because it automatically selects the stack segment. This is a compact encoding for this common function.

(Index ∗ Scale) + Displacement ⎯ This address mode offers an efficient way to index into a static array when the element size is 2, 4, or 8 bytes. The displacement locates the beginning of the array, the index register holds the subscript of the desired array element, and the processor automatically converts the subscript into an index by applying the scaling factor.

Base + Index + Displacement ⎯ Using two registers together supports either a two-dimensional array (the displacement holds the address of the beginning of the array) or one of several instances of an array of records (the displacement is an offset to a field within the record).

Base + (Index ∗ Scale) + Displacement ⎯ Using all the addressing components together allows efficient indexing of a two-dimensional array when the elements of the array are 2, 4, or 8 bytes in size.

Read and follow these rules, and you will be fine. You don't need to read all 4000 pages, but you really should be familiar enough with the manual's contents that you can look stuff up when needed (like when the assembler coughs up an error message). It's pretty difficult to program a microprocessor without being at all familiar with its design or programming model.

mov eax, [ebx + esp*4 + 2]

is indeed an invalid addressing mode because you are trying to use ESP as an index. Figure 3-11 says that you can't use ESP as an index, as does the first bullet point immediately underneath. The logic here is that ESP is the stack pointer, which contains an address.

It doesn't make sense to scale an address. it does, however, make sense to offset from an address, which is why ESP can be used as a base. That's why this is fine:

mov eax, [ebx + esp + 2]

This is also fine:

mov eax, [ebx + ecx*4 + 2]

because ECX can be used as an index.

In the comments, you present this instruction:

mov eax, [ebx + esp + 2]

As Ross Ridge already replied, this is legal because you aren't actually scaling ESP, so the assembler is smart enough to use ESP as the base and EBX as the index. In other words, it has reordered it to:

mov eax, [2 + esp + ebx]
          ^    ^     ^
          |    |     |
displacement   |    index
              base

with an implicit 1 as the scale factor.


问:
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!

答: If you have everything defined like Thomas described, can you check if the adjustAlpha method is called on the main thread?

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!


问:
convert REGEXP to LIKE in MYSQL query
I have MYSQL query that looks as below

```<code>select * from table1 where host REGEXP 'host1';
</code>```

I want to execute the same query using LIKE
Please suggest how it can be achieved

答:
Try this:

```<code>select * from table1 where host LIKE '%host1%';
</code>```

REGEXP 'host1' will match host1 anywhere in the string.  To phrase this using the LIKE operator we need to surround host1 with wildcards.

Title: convert REGEXP to LIKE in MYSQL query

Body:
I have MYSQL query that looks as below

select * from table1 where host REGEXP 'host1';

I want to execute the same query using LIKE
Please suggest how it can be achieved

Body:
Try this:

select * from table1 where host LIKE '%host1%';

REGEXP 'host1' will match host1 anywhere in the string.  To phrase this using the LIKE operator we need to surround host1 with wildcards.