问:
Obj-C - Dismiss keyboard by tapping anywhere on screen from UITextView?
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

```<code> - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }
</code>```

答:
Your problem is not related to gesture recognizer.
Problem caused by line:

```<code>self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
</code>```

You set frame for self.view from self.inputView with offset.

And when self.view size is changed, its subviews (including text view) may have positions out of superview bound. And UIView doesn't respond touch event if touch point is out of superview bounds.
You can easily check this by setting background color for views and show they frames in log:

```<code>...
- (void) animateTextView:(BOOL) up
{
    NSLog(@"self.view state1:%@", self.view);
    NSLog(@"self.replyField state1:%@", self.replyField);
    self.view.backgroundColor = [UIColor redColor];
    self.replyField.backgroundColor = [UIColor blueColor];

    const int movementDistance = 206;
    const float movementDuration = 0.3f;
    int movement= movement = (up ? -movementDistance : movementDistance);
    NSLog(@"%d",movement);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    //self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
    self.replyField.frame = CGRectOffset(self.replyField.frame, 0, movement);
    [UIView setAnimationDidStopSelector:@selector(afterAnimationStops)];
    [UIView commitAnimations];
}

- (void)afterAnimationStops {
    NSLog(@"self.view state2:%@", self.view);
    NSLog(@"self.replyField state2:%@", self.replyField);
}
...
</code>```

Also what is self.inputView? is it properly set?

BTW: What goal of the code? Do you want to move text view to avoid overlapping by keyboard? Then consider placing it in UIScrollView.
e.g see discussion here: How to make a UITextField move up when keyboard is present?.

Body:
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

 - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }

Body:
Your problem is not related to gesture recognizer.
Problem caused by line:

self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);

You set frame for self.view from self.inputView with offset.

And when self.view size is changed, its subviews (including text view) may have positions out of superview bound. And UIView doesn't respond touch event if touch point is out of superview bounds.
You can easily check this by setting background color for views and show they frames in log:

...
- (void) animateTextView:(BOOL) up
{
    NSLog(@"self.view state1:%@", self.view);
    NSLog(@"self.replyField state1:%@", self.replyField);
    self.view.backgroundColor = [UIColor redColor];
    self.replyField.backgroundColor = [UIColor blueColor];

    const int movementDistance = 206;
    const float movementDuration = 0.3f;
    int movement= movement = (up ? -movementDistance : movementDistance);
    NSLog(@"%d",movement);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    //self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
    self.replyField.frame = CGRectOffset(self.replyField.frame, 0, movement);
    [UIView setAnimationDidStopSelector:@selector(afterAnimationStops)];
    [UIView commitAnimations];
}

- (void)afterAnimationStops {
    NSLog(@"self.view state2:%@", self.view);
    NSLog(@"self.replyField state2:%@", self.replyField);
}
...

Also what is self.inputView? is it properly set?

BTW: What goal of the code? Do you want to move text view to avoid overlapping by keyboard? Then consider placing it in UIScrollView.
e.g see discussion here: How to make a UITextField move up when keyboard is present?.


来源: stackexchange

问:
Write ML function
I'm new to ML so I'm doing my best to understand.

Write an ML function called alternate : 'a list -> 'a list, that takes two lists, having the same length, as input and produces an output list whose elements are alternately taken from the first and second input list respectively.

Example

```<code>alternate ([1,3,5],[2,4,6]) = [1,2,3,4,5,6]
</code>```

This is my work : fun alternate ( x::xs,y::ys) = x::alternate(x,y);

答:
You split the problem in two: A recursive case and a base case. (1) In the recursive case you solve some unit of the problem, in this case placing a single element from each list in front of the result, and recursively try to solve the rest of the problem in the same fashion. (2) In the base case, the lists are empty and the result is the empty list.

```<code>fun alternate (x::xs, y::ys) = x::y::alternate(xs, ys)
  | alternate ([], []) = []
  | alternate _ = raise Fail "xs and ys don't have the same length"
</code>```

(3) Because the function is only well-defined for input of even length, the catch-all pattern _ matches the two-tuple containing lists where one is empty and the other isn't and raises an exception.

ContentLicense: CC BY-SA 3.0

Title: Write ML function

Body:
I'm new to ML so I'm doing my best to understand.

Write an ML function called alternate : 'a list -> 'a list, that takes two lists, having the same length, as input and produces an output list whose elements are alternately taken from the first and second input list respectively.

Example

alternate ([1,3,5],[2,4,6]) = [1,2,3,4,5,6]

This is my work : fun alternate ( x::xs,y::ys) = x::alternate(x,y);

Body:
You split the problem in two: A recursive case and a base case. (1) In the recursive case you solve some unit of the problem, in this case placing a single element from each list in front of the result, and recursively try to solve the rest of the problem in the same fashion. (2) In the base case, the lists are empty and the result is the empty list.

fun alternate (x::xs, y::ys) = x::y::alternate(xs, ys)
  | alternate ([], []) = []
  | alternate _ = raise Fail "xs and ys don't have the same length"

(3) Because the function is only well-defined for input of even length, the catch-all pattern _ matches the two-tuple containing lists where one is empty and the other isn't and raises an exception.


问:
UFT API Test: How to read the User Variables and System Variables in custom code
I want to read the User Variables and System Variables in custom code of my UFT API test. How can I do the same.

答:
It's pretty straight forward, just insert this code in your custom code activity and it will take care of it.

Just replace the variable names that you want to capture.

```<code>string systemVar = System.Environment.GetEnvironmentVariable("JAVA_HOME");
CodeActivity4.Report("systemVar", systemVar);

string userVar = this.CodeActivity4.Input.myVar;
CodeActivity4.Report("userVar", userVar);

string testVar = this.Context.TestProfile.GetVariableValue("TestName");
CodeActivity4.Report("testVar", testVar);
</code>```

Here here is the result:

Body:
It's pretty straight forward, just insert this code in your custom code activity and it will take care of it.

Just replace the variable names that you want to capture.

string systemVar = System.Environment.GetEnvironmentVariable("JAVA_HOME");
CodeActivity4.Report("systemVar", systemVar);

string userVar = this.CodeActivity4.Input.myVar;
CodeActivity4.Report("userVar", userVar);

string testVar = this.Context.TestProfile.GetVariableValue("TestName");
CodeActivity4.Report("testVar", testVar);

Here here is the result:


问:
use explicit type to limit visibility of method in object to the module defining it
I have a coordinate "class" (implemented using a factory function returning an object literal) in OCaml and am trying to figure out how to restrict the visibility of a method on that object to the module it was defined in.

Here's the source file

```<code>(* coordinate.ml *)
type coordinate = < get_x : int; get_y : int >

let create_coord ~x ~y = object
  val x = x
  val y = y
  method get_x = x
  method get_y = y
  (* hide this method from public interface *)
  method debug_print = Printf.printf "(x=%d, y=%d)\n"
end
</code>```

and here's the interface

```<code>(* coordinate.mli *)
(* the type synonym coordinate is compatible with the "real"
 * type, but does not expose the debug_print method *)
type coordinate = < get_x : int; get_y : int >

val create_coord : x:int -> y:int -> coordinate
</code>```

My intent was to allow the object returned by create_coord to have all of methods visible inside the body of the Coordinate module. The only reason the coordinate type alias is repeated in the .ml file is to satisfy the compiler/allow it to be used in the .mli.

However, I want to prevent consumers of this module from using the debug_print method. I figured that, "since OCaml supports structural typing", an object type with strictly fewer methods would be a "compatible" type for the purposes of type ascription.

However, when I attempt to compile the files I get the following error:

```<code>$ ocamlc coordinate.mli
$ ocamlc coordinate.ml
File "coordinate.ml", line 1:
Error: The implementation coordinate.ml
       does not match the interface coordinate.cmi:
       Values do not match:
         val create_coord :
           x:'a ->
           y:'b ->
           < debug_print : int -> int -> unit; get_x : 'a; get_y : 'b >
       is not included in
         val create_coord : x:int -> y:int -> coordinate
       File "coordinate.ml", line 3, characters 4-16: Actual declaration
Exit 2
</code>```

Is there a way to limit the visibility of debug_print outside of Coordinate while making it freely accessible inside?

答:
I think the best solution is to use private row type:

```<code>module M : sig
  type t = private < x : int; y : int; .. >
  val make : int -> int -> t
  val f: t -> unit
end = struct
  type t = < x : int; y : int; z : [`Not_exposed] >

  let make x y = object
    method x = x
    method y = y
    method z = `Not_exposed
  end

  let f o =
    (* Access a method not exposed outside of the module *)
    assert (o#z = `Not_exposed)
end;;
</code>```

This way, you don't need any coercion function. Still, any object of type t is seen with his private methods inside module M, but only the public one (xand y) can be accessed outside. Find more information in the manual.

Body:
I have a coordinate "class" (implemented using a factory function returning an object literal) in OCaml and am trying to figure out how to restrict the visibility of a method on that object to the module it was defined in.

Here's the source file

(* coordinate.ml *)
type coordinate = < get_x : int; get_y : int >

let create_coord ~x ~y = object
  val x = x
  val y = y
  method get_x = x
  method get_y = y
  (* hide this method from public interface *)
  method debug_print = Printf.printf "(x=%d, y=%d)\n"
end

and here's the interface

(* coordinate.mli *)
(* the type synonym coordinate is compatible with the "real"
 * type, but does not expose the debug_print method *)
type coordinate = < get_x : int; get_y : int >

val create_coord : x:int -> y:int -> coordinate

My intent was to allow the object returned by create_coord to have all of methods visible inside the body of the Coordinate module. The only reason the coordinate type alias is repeated in the .ml file is to satisfy the compiler/allow it to be used in the .mli.

However, I want to prevent consumers of this module from using the debug_print method. I figured that, "since OCaml supports structural typing", an object type with strictly fewer methods would be a "compatible" type for the purposes of type ascription.

However, when I attempt to compile the files I get the following error:

$ ocamlc coordinate.mli
$ ocamlc coordinate.ml
File "coordinate.ml", line 1:
Error: The implementation coordinate.ml
       does not match the interface coordinate.cmi:
       Values do not match:
         val create_coord :
           x:'a ->
           y:'b ->
           < debug_print : int -> int -> unit; get_x : 'a; get_y : 'b >
       is not included in
         val create_coord : x:int -> y:int -> coordinate
       File "coordinate.ml", line 3, characters 4-16: Actual declaration
Exit 2

Is there a way to limit the visibility of debug_print outside of Coordinate while making it freely accessible inside?

Body:
I think the best solution is to use private row type:

module M : sig
  type t = private < x : int; y : int; .. >
  val make : int -> int -> t
  val f: t -> unit
end = struct
  type t = < x : int; y : int; z : [`Not_exposed] >

  let make x y = object
    method x = x
    method y = y
    method z = `Not_exposed
  end

  let f o =
    (* Access a method not exposed outside of the module *)
    assert (o#z = `Not_exposed)
end;;

This way, you don't need any coercion function. Still, any object of type t is seen with his private methods inside module M, but only the public one (xand y) can be accessed outside. Find more information in the manual.

ContentLicense: CC BY-SA 4.0


问:
using reference libraries in android
Have a great day...

I am still stuck with my bug...
I am using an android app. to login a website using the twitter account..
I am using the twitter4j api for this...
I have imported the classes from the jar files to my activity...
I also have my activity 'MainActivity'added in the manifest file..
but still the application is force closing ...!
Any one have an Idea..?

LogCat Error:
Error

答:
checkNotBuilt of ConfigurationBuilder class is throwing exception, probably before calling setOAuthConsumerKey API in onCreate, it may be required to initialize some configuration.

I never used twitter4j and can just give this pointer to debug further.

ContentLicense: CC BY-SA 2.5

Title: using reference libraries in android


问:
Unable to use = operator in a "If" statement
Why can't I use = operator over here. Anyway to solve this problem ?

```<code> If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If
</code>```

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'

答: You can't compare Images to Bitmaps, they are different things.

Body:
Why can't I use = operator over here. Anyway to solve this problem ?

 If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'


问:
Range bug after upgrading Android Studio - Value must be ≤ 1.0 (was 100) less
After Android Studio upgrade to version 3.0 I get the following warning: "Value must be ≤ 1.0 (was 100) less."

But the project is normally compiled. What's wrong with the number 100?

I drew attention to this because the Android Studio marks this as an error, not an ordinary warning.

答:
Odd — for some reason, I'm not seeing android.support.v4.graphics.ColorUtils in the JavaDocs. Regardless, based on source code, the return value has @FloatRange(from = 0.0, to = 1.0), which is where the Lint error is getting its data from.

In terms of why you are seeing an error, that feels like a Lint bug. You might consider filing an issue with a reproducible test case.

In terms of why you are seeing an error now, each new version of Android Studio has new Lint rules, some of which may have bugs.


问:
get IPA file in Visual Studio 2017 Cross platform app (Xamarin)
Where is Ad hoc in Visual Studio 2017 Cross platform app (xamarin)?
How can i export IPA file in Visual studio Cross platform app (xamarin)?</p>

答:
Right click on your ios project in your solution pad and go to options.
Navigate to "iOS IPA Options".

Make sure "Build iTunes Package Archive (IPA) is checked.

Your IPA will be available after you run the app in your bin folder.


问:
Dynamic center div bootstrap
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

```

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

答:
you can use flex-container with flex-wrap like this

.my-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container my-container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>

</div></code>```

Title: Dynamic center div bootstrap

Body:
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

Body:
you can use flex-container with flex-wrap like this

.my-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container my-container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>

</div>


问:
Move a view up only when the keyboard covers an input field
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}
</code>```

答:
Swift 4 Updated my solution

with constraint animation on keyboard show/hide,
enjoy.

```<code>import Foundation
import UIKit

class PhoneController: UIViewController, UITextFieldDelegate{

    var phoneLayoutYConstraint: NSLayoutConstraint?

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = .white

        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        phoneField.delegate = self

        view.addSubview(phoneField)

        NSLayoutConstraint.activate([phoneField.heightAnchor.constraint(equalToConstant: 50),
                                     phoneField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                                     phoneField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                                     phoneField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)])

        phoneLayoutYConstraint = NSLayoutConstraint(item: phoneField, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
        phoneLayoutYConstraint?.isActive = true

    }

    let phoneField: UITextField = {
        let text = UITextField()
        text.translatesAutoresizingMaskIntoConstraints = false
        text.keyboardType = .numberPad
        text.font = UIFont.systemFont(ofSize: 30)
        text.layer.cornerRadius = 5.0
        text.layer.masksToBounds = true
        text.layer.borderColor = UIColor.darkGray.cgColor
        text.layer.borderWidth = 2.0

        return text
    }()

    override func viewDidDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

   @objc func handleKeyBoardNotification(_ notification: NSNotification) {

        if let info = notification.userInfo {

            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
            let isKeyBoardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

            var aRect : CGRect = self.phoneField.frame
            aRect.size.height -= keyboardSize!.height

            phoneLayoutYConstraint?.constant = isKeyBoardShowing ? -keyboardSize!.height : 0

            UIView.animate(withDuration: 0, delay: 0, options: .curveEaseOut, animations: {
                self.view.layoutIfNeeded()
            }, completion: { (boo) in

            })

        }
    }

}
</code>```

Body:
I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom.
When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen.
I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}

Body:
Swift 4 Updated my solution

with constraint animation on keyboard show/hide,
enjoy.

import Foundation
import UIKit

class PhoneController: UIViewController, UITextFieldDelegate{

    var phoneLayoutYConstraint: NSLayoutConstraint?

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = .white

        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        phoneField.delegate = self

        view.addSubview(phoneField)

        NSLayoutConstraint.activate([phoneField.heightAnchor.constraint(equalToConstant: 50),
                                     phoneField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                                     phoneField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                                     phoneField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)])

        phoneLayoutYConstraint = NSLayoutConstraint(item: phoneField, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
        phoneLayoutYConstraint?.isActive = true

    }

    let phoneField: UITextField = {
        let text = UITextField()
        text.translatesAutoresizingMaskIntoConstraints = false
        text.keyboardType = .numberPad
        text.font = UIFont.systemFont(ofSize: 30)
        text.layer.cornerRadius = 5.0
        text.layer.masksToBounds = true
        text.layer.borderColor = UIColor.darkGray.cgColor
        text.layer.borderWidth = 2.0

        return text
    }()

    override func viewDidDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

   @objc func handleKeyBoardNotification(_ notification: NSNotification) {

        if let info = notification.userInfo {

            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
            let isKeyBoardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

            var aRect : CGRect = self.phoneField.frame
            aRect.size.height -= keyboardSize!.height

            phoneLayoutYConstraint?.constant = isKeyBoardShowing ? -keyboardSize!.height : 0

            UIView.animate(withDuration: 0, delay: 0, options: .curveEaseOut, animations: {
                self.view.layoutIfNeeded()
            }, completion: { (boo) in

            })

        }
    }

}


问:
Pandas dataframe in pyspark to hive
How to send a pandas dataframe to a hive table?

I know if I have a spark dataframe, I can register it to a temporary table using

```<code>df.registerTempTable("table_name")
sqlContext.sql("create table table_name2 as select * from table_name")
</code>```

but when I try to use the pandas dataFrame to registerTempTable, I get the below error:

```<code>AttributeError: 'DataFrame' object has no attribute 'registerTempTable'
</code>```

Is there a way for me to use a pandas dataFrame to register a temp table or convert it to a spark dataFrame and then use it register a temp table so that I can send it back to hive.

答:
I converted my pandas df to a temp table by

1) Converting the pandas dataframe to spark dataframe:

```<code>spark_df=sqlContext.createDataFrame(Pandas_df)
</code>```

2) Make sure that the data is migrated properly

```<code>spark_df.select("*").show()
</code>```

3) Convert the spark dataframe to a temp table for querying.

```<code>spark_df.registerTempTable("table_name").
</code>```

Cheers..

Title: Pandas dataframe in pyspark to hive

Body:
How to send a pandas dataframe to a hive table?

I know if I have a spark dataframe, I can register it to a temporary table using

df.registerTempTable("table_name")
sqlContext.sql("create table table_name2 as select * from table_name")

but when I try to use the pandas dataFrame to registerTempTable, I get the below error:

AttributeError: 'DataFrame' object has no attribute 'registerTempTable'

Is there a way for me to use a pandas dataFrame to register a temp table or convert it to a spark dataFrame and then use it register a temp table so that I can send it back to hive.

Body:
I converted my pandas df to a temp table by

1) Converting the pandas dataframe to spark dataframe:

spark_df=sqlContext.createDataFrame(Pandas_df)

2) Make sure that the data is migrated properly

spark_df.select("*").show()

3) Convert the spark dataframe to a temp table for querying.

spark_df.registerTempTable("table_name").

Cheers..


问:
Branch IO UNity getting first install
I Have integrated branch plugin in my Unity game.
How to get to know if current install was done by branch link and is it new install??
How to get to know if any user has installed from another user invite and reward the referrer.
what is "+is_first_session" used for??</p>

答:
The problem was with the true string on iOS and android ,
In IOS it comes as "True" while in android we get "true"</p>

Title: Branch IO UNity getting first install


问:
How to return values in a query only if the subtraction of two queries are greater than 0 in MySQL
I know, is duplicated, but I do not know how to do it without a single query. Here is my problem:

Description of the model:
The "t_factura_detalle" stores the details of an invoce.
The posible products for the invoce details are stored in "t_licencia".
The table "t_asignacion" stores the product of a invoice (for the moment, is not important to save the invoice id from which each product is assigned) than has be assigned to a pc "id_pc" (only one license for record in the table assign).

Process in which I need help:
When i do the assignation process, i need return a list in which i return "t_licencia.id_licencia" and "t_licencia.licencia_name", but i need to sustract all the licenses already asigned stored in the "t_asignation" table. An example:

"t_licencia":

```<code>+-------------+--------------------------+
| id_licencia | licencia_name            |
+-------------+--------------------------+
|           6 | Adobe Photoshop CS6 Pro  |
|           4 | Microsoft Office 2013 SP |
+-------------+--------------------------+
</code>```

"t_factura_detalle":

```<code>+------------+---------------------+-------------+----------+
| id_factura | id_factura_licencia | id_licencia | cantidad |
+------------+---------------------+-------------+----------+
|          6 |                   1 |           6 |       30 |
|          6 |                   3 |           4 |       40 |
|          7 |                   4 |           4 |       40 |
|          6 |                   6 |           6 |       40 |
|          6 |                   8 |           6 |       40 |
+------------+---------------------+-------------+----------+
</code>```

So, the quantity of products (licenses) are:

```<code>+--------------------------+---------------+
| licencia_name            | sum(cantidad) |
+--------------------------+---------------+
| Adobe Photoshop CS6 Pro  |           110 |
| Microsoft Office 2013 SP |            80 |
+--------------------------+---------------+

# At the moment I do not care what invoice is associated,
# I just want to know the amount
select t_licencia.licencia_name, sum(cantidad)
from t_licencia, t_factura_detalle
where t_licencia.id_licencia = t_factura_detalle.id_licencia
group by licencia_name;
</code>```

And a example of the "t_asignation":

```<code>+---------------+---------------------+-------+------------------+
| id_asignacion | id_factura_licencia | id_pc | fecha_asignacion |
+---------------+---------------------+-------+------------------+
|             2 |                   3 |     1 | 2017-00-00       |
+---------------+---------------------+-------+------------------+
</code>```

So, the "t_asignacion" points to an "t_facture_detalle" record, where are a product.

How can i return values only if the the {substraction of the [sum of the available licenses] and the [sum of assigned licenses]} is greater than 0 in a stored procedure or a simply query (preferably)?

I do not know if I explain well.
Thank so much!

答:
If I understood correctly your question you want to select all the id_licensia who are not in t_licencia.

```<code>SELECT  id_licencia,
    licencia_name
FROM t_licencia t_l
LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
WHERE tfd.id_licencia IS NULL
</code>```

If you need to display only the license key who aren't in t_asignation then :

```<code>SELECT  t_l.id_licencia,
        t_l.licencia_name
    FROM t_licencia t_l
    LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
    LEFT JOIN t_asignation t_a ON t_a.id_factura_licencia = tfd.id_factura
    WHERE t_a.id_factura_licencia IS NULL
</code>```

Then for the sum :

```<code>SELECT  t_l.id_licencia,
        t_l.licencia_name,
        SUM(cantidad)
FROM t_licencia t_l
LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
LEFT JOIN t_asignation t_a ON t_a.id_factura_licencia = tfd.id_factura
WHERE t_a.id_factura_licencia IS NULL
GROUP BY _l.id_licencia,
        t_l.licencia_name
</code>```

Body:
I know, is duplicated, but I do not know how to do it without a single query. Here is my problem:

Description of the model:
The "t_factura_detalle" stores the details of an invoce.
The posible products for the invoce details are stored in "t_licencia".
The table "t_asignacion" stores the product of a invoice (for the moment, is not important to save the invoice id from which each product is assigned) than has be assigned to a pc "id_pc" (only one license for record in the table assign).

Process in which I need help:
When i do the assignation process, i need return a list in which i return "t_licencia.id_licencia" and "t_licencia.licencia_name", but i need to sustract all the licenses already asigned stored in the "t_asignation" table. An example:

"t_licencia":

+-------------+--------------------------+
| id_licencia | licencia_name            |
+-------------+--------------------------+
|           6 | Adobe Photoshop CS6 Pro  |
|           4 | Microsoft Office 2013 SP |
+-------------+--------------------------+

"t_factura_detalle":

+------------+---------------------+-------------+----------+
| id_factura | id_factura_licencia | id_licencia | cantidad |
+------------+---------------------+-------------+----------+
|          6 |                   1 |           6 |       30 |
|          6 |                   3 |           4 |       40 |
|          7 |                   4 |           4 |       40 |
|          6 |                   6 |           6 |       40 |
|          6 |                   8 |           6 |       40 |
+------------+---------------------+-------------+----------+

So, the quantity of products (licenses) are:

+--------------------------+---------------+
| licencia_name            | sum(cantidad) |
+--------------------------+---------------+
| Adobe Photoshop CS6 Pro  |           110 |
| Microsoft Office 2013 SP |            80 |
+--------------------------+---------------+

# At the moment I do not care what invoice is associated,
# I just want to know the amount
select t_licencia.licencia_name, sum(cantidad)
from t_licencia, t_factura_detalle
where t_licencia.id_licencia = t_factura_detalle.id_licencia
group by licencia_name;

And a example of the "t_asignation":

+---------------+---------------------+-------+------------------+
| id_asignacion | id_factura_licencia | id_pc | fecha_asignacion |
+---------------+---------------------+-------+------------------+
|             2 |                   3 |     1 | 2017-00-00       |
+---------------+---------------------+-------+------------------+

So, the "t_asignacion" points to an "t_facture_detalle" record, where are a product.

How can i return values only if the the {substraction of the [sum of the available licenses] and the [sum of assigned licenses]} is greater than 0 in a stored procedure or a simply query (preferably)?

I do not know if I explain well.
Thank so much!

Body:
If I understood correctly your question you want to select all the id_licensia who are not in t_licencia.

SELECT  id_licencia,
    licencia_name
FROM t_licencia t_l
LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
WHERE tfd.id_licencia IS NULL

If you need to display only the license key who aren't in t_asignation then :

SELECT  t_l.id_licencia,
        t_l.licencia_name
    FROM t_licencia t_l
    LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
    LEFT JOIN t_asignation t_a ON t_a.id_factura_licencia = tfd.id_factura
    WHERE t_a.id_factura_licencia IS NULL

Then for the sum :

SELECT  t_l.id_licencia,
        t_l.licencia_name,
        SUM(cantidad)
FROM t_licencia t_l
LEFT JOIN t_factura_detalle tfd ON tfd.id_licencia = t_l.id_licencia
LEFT JOIN t_asignation t_a ON t_a.id_factura_licencia = tfd.id_factura
WHERE t_a.id_factura_licencia IS NULL
GROUP BY _l.id_licencia,
        t_l.licencia_name


问:
Swift: Clearing .sharedApplication().shortcutItems on application quit
I'm having a very simple problem with my implemented 3D Touch dynamic quick action shortcuts.

I want the shortcuts to be cleared whenever the app is terminated (by double clicking the Home button and swiping up).

I am calling UIApplication.sharedApplication().shortcutItems.removeAll() as follows:

```<code>func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    UIApplication .sharedApplication().shortcutItems?.removeAll()
    self.saveContext()
}
</code>```

However it has no effect, and the quick actions still show when 3D touch is used.

If I place UIApplication.sharedApplication().shortcutItems?.removeAll() inside
    func applicationDidEnterBackground(application: UIApplication), this works exactly as intended...

I read something about applicationDidEnterBackground being the function used in most cases due to background processing or something...but there has to be a way to achieve what I want when the user terminates the app using the app monitor swipe up.

Thanks

答:
There are dynamic and static quick actions. The first kind you define through the shortcutItems property of the UIApplication instance (like in your example). The second kind you register in the plist file.

From the documentation:

Your code creates dynamic quick actions, and registers them with your app object, at runtime.

The system registers your static quick actions when your app is installed.

If a user installs an update for your app but has not yet launched the update, pressing your Home screen icon shows the dynamic quick actions for the previously-installed version.

This means that even when the app is closed the system remembers about both kinds of quick actions. While your app is in memory, such as when going into background, the system can still query the UIApplication for the dynamic actions but it must keep some other sort of persistence of quick actions when the app is closed.

I think there is just no guarantee about the point at which the system synchronizes with the dynamic quick actions. My guess is that the system does not necessarily synchronize when closing the app, yours might be an unsupported use case.

Body:
I'm having a very simple problem with my implemented 3D Touch dynamic quick action shortcuts.

I want the shortcuts to be cleared whenever the app is terminated (by double clicking the Home button and swiping up).

I am calling UIApplication.sharedApplication().shortcutItems.removeAll() as follows:

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    UIApplication .sharedApplication().shortcutItems?.removeAll()
    self.saveContext()
}

However it has no effect, and the quick actions still show when 3D touch is used.

If I place UIApplication.sharedApplication().shortcutItems?.removeAll() inside
    func applicationDidEnterBackground(application: UIApplication), this works exactly as intended...

I read something about applicationDidEnterBackground being the function used in most cases due to background processing or something...but there has to be a way to achieve what I want when the user terminates the app using the app monitor swipe up.

Thanks


问:
Print all verticies in graph's cycle
I've tried according to this Algorithm to find and print simple cycle in complexity of O(n) on undirected graph.
Did it in C++ according to my tutor and following is my code:

```<code>int parent[1000] = {0};
int status[1000] = {0};
bool oriented = true;

#include ...

using namespace std;
array<list<int>, 1000 + 1> g;

void PrintCycle(int v, int u) {
    do {
        printf("%d",u);
        u = parent[u];
    } while (u != v);
}

bool DFS_cycle(int u) {
    status[u] = 1;
    for (int v:g[u]) {
        if (status[v] == 0) {
            parent[v] = u;
            DFS_cycle(v);
        }
        if (status[v] == 1 && v != parent[u]) {
            PrintCycle(v,u);
        }
    }
    status[u] = 2;
}

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int N, u, v;
    cin >> N;
    while (cin >> u >> v) {
        g[u].push_back(v);
        g[v].push_back(u);
    }

    parent[1] = 1;
    DFS_cycle(1);
    return 0;
}
</code>```

But it doesn't work for the following input: (First line is the number of vertices. Vertices are numbered from 1. After that each line describes an edge.)

8

3  1

3  4

3  2

2  5

2  6

6  7

6  8

What did I do wrong?

答:
First of all you have used C++ not C.

For the given input there is no cycle. It doesn't print any cycle either. So it does work for the given input.

However your code has bug. If we add another edge (5,8) a cycle is formed (2 -> 5 -> 8 -> 6). But your code prints the cycle as (6 -> 8 -> 5).

Check out my code for your bug :

```<code>void PrintCycle(int v, int u) {
    while(u != v)
    {
        printf("%d ",u); // You didn't give any space after %d
        // It could not be possible to differentitate between '1''2'
        // and '12'

        u = parent[u];
    }

    printf("%d \n", v);

}

bool DFS_cycle(int u) {

    status[u] = 1;
    for (int v:g[u]) {
        if (status[v] == 0) {
            parent[v] = u;
            DFS_cycle(v);
        }
        else if (status[v] == 1 && v != parent[u]) { // It should be 'else if' NOT 'if'
            PrintCycle(v,u);
            break;
        }
    }
    status[u] = 2;
}
</code>```

And it is a good idea to #define WHITE 0, #define GRAY 1 etc and then using WHITE, GRAY etc instead of using bare 1, 2 etc.

Title: Print all verticies in graph's cycle

Body:
I've tried according to this Algorithm to find and print simple cycle in complexity of O(n) on undirected graph.
Did it in C++ according to my tutor and following is my code:

int parent[1000] = {0};
int status[1000] = {0};
bool oriented = true;

#include ...

using namespace std;
array<list<int>, 1000 + 1> g;

void PrintCycle(int v, int u) {
    do {
        printf("%d",u);
        u = parent[u];
    } while (u != v);
}

bool DFS_cycle(int u) {
    status[u] = 1;
    for (int v:g[u]) {
        if (status[v] == 0) {
            parent[v] = u;
            DFS_cycle(v);
        }
        if (status[v] == 1 && v != parent[u]) {
            PrintCycle(v,u);
        }
    }
    status[u] = 2;
}

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int N, u, v;
    cin >> N;
    while (cin >> u >> v) {
        g[u].push_back(v);
        g[v].push_back(u);
    }

    parent[1] = 1;
    DFS_cycle(1);
    return 0;
}

But it doesn't work for the following input: (First line is the number of vertices. Vertices are numbered from 1. After that each line describes an edge.)

8

3  1

3  4

3  2

2  5

2  6

6  7

6  8

What did I do wrong?

Body:
First of all you have used C++ not C.

For the given input there is no cycle. It doesn't print any cycle either. So it does work for the given input.

However your code has bug. If we add another edge (5,8) a cycle is formed (2 -> 5 -> 8 -> 6). But your code prints the cycle as (6 -> 8 -> 5).

Check out my code for your bug :

void PrintCycle(int v, int u) {
    while(u != v)
    {
        printf("%d ",u); // You didn't give any space after %d
        // It could not be possible to differentitate between '1''2'
        // and '12'

        u = parent[u];
    }

    printf("%d \n", v);

}

bool DFS_cycle(int u) {

    status[u] = 1;
    for (int v:g[u]) {
        if (status[v] == 0) {
            parent[v] = u;
            DFS_cycle(v);
        }
        else if (status[v] == 1 && v != parent[u]) { // It should be 'else if' NOT 'if'
            PrintCycle(v,u);
            break;
        }
    }
    status[u] = 2;
}

And it is a good idea to #define WHITE 0, #define GRAY 1 etc and then using WHITE, GRAY etc instead of using bare 1, 2 etc.


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
Thomas, what kind of data access logic are you using in your application?

If you are looking for a way to interact with the database and store/retrieve objects from it, you could also have a look at Entity Framework or NHibernate, such ORMs allow you to focus on what really matters in your application and not on the way objects/entities are loaded or saved.


答:
```<code>SELECT A.name, SUM(A.total) as sum_tot, COALESCE(B.sum_qty, 0) as sum_qty
FROM tbl1 A
LEFT JOIN (
    SELECT id, SUM(qty) as sum_qty
    FROM tbl2
    GROUP BY id
) B ON B.id = A.id
GROUP BY A.name
</code>```

Title: SQL - How can I JOIN two tables and SUM a column based on IDs between them?

Body:
I have two tables. One table is with master data

Table tbl1:

+-------------+------------+------------+
| ID          | Name       | Total      |
+-------------+------------+------------+
| 1           | a          | 10         |
| 2           | b          | 5          |
| 3           | c          | 4          |
| 4           | a          | 4          |
+-------------+------------+------------+

Second table tbl2 contains child data. The key between tables is ID

Table tbl2:

+-------------+------------+
|id           | qty        |
+-------------+------------+
| 1           | 4          |
| 1           | 3          |
| 1           | 1          |
| 3           | 1          |
| 3           | 3          |
+-------------+------------+

I need to get output like this:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 14         | 8          |
| b           | 5          | 0          |
| c           | 4          | 4          |
+-------------+------------+------------+

I had tried with this:

select tbl1.name, SUM(tbl1.total), SUM(tbl2.qty)
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name

The output that I get is:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 34         | 8          |
| b           | 5          |null        |
| c           | 8          | 4          |
+-------------+------------+------------+

Which is not correct.

Here is the sql fiddle:

The summary from first table is not in relation with second table. It seems that somehow query runs three times.


问:
Setting Your Own Key When Adding an Object to Firebase - AngularFire
I can use the following to add an object to my Firebase data store:

```<code>var uniqueId = {
    name: "a name",
    location: "new york"
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
    // do something on success
}, function(){
    // do something if call fails
});
</code>```

The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned.  The object I just added is saved under this key.

Is there a way for me to specify what the key name is when I add to my data store?

答:
.set still working in angularfire api

So, try this...

```<code>var gT = $scope.ultima[0].guia + 1;
var _db = firebase.database().ref('/guias/' + gT);
                      _db.set({
                    'artigo': _dt.artigo,
                    'inicio': $scope.ultima[0].fim + 1,
                    'guia': $scope.ultima[0].guia + 1,
                    'fim': $scope.ultima[0].fim + 1 + (1 * _dt.quantidade),
                    'quantidade': _dt.quantidade,
                });
</code>```

Body:
I can use the following to add an object to my Firebase data store:

var uniqueId = {
    name: "a name",
    location: "new york"
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
    // do something on success
}, function(){
    // do something if call fails
});

The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned.  The object I just added is saved under this key.

Is there a way for me to specify what the key name is when I add to my data store?

Body:
.set still working in angularfire api

So, try this...

var gT = $scope.ultima[0].guia + 1;
var _db = firebase.database().ref('/guias/' + gT);
                      _db.set({
                    'artigo': _dt.artigo,
                    'inicio': $scope.ultima[0].fim + 1,
                    'guia': $scope.ultima[0].guia + 1,
                    'fim': $scope.ultima[0].fim + 1 + (1 * _dt.quantidade),
                    'quantidade': _dt.quantidade,
                });


问:
Vararg as table parameter - OpenL-Tablets
This question is specific to OpenL-Tablets (no tag currently exists)

In trying to abstract code from business users creating rules through the creation of a Method table which will take variable number of objects.

However when trying to use the varargs parameter, the following error is thrown:

Parsing Error: Error: Encountered " "..." "... "" at line 1, column 45. Was expecting one of: "[" ...  ...

Openl Code Fragment:
  ======================= ResolvedResponse setResolvedResponse(Section... section) ^^^^^^^

How else can this be achieved without having to explicitly create a method with x number of arguments?

Since OpenL's aim is to remain business analyst friendly, we are advised to abstract things such that a BA would never need to work with a structure such as setResolvedReponse(new Section[]{section1, section2, section3}) as it requires some knowledge of Java syntax. Perhaps there is another way the parameter must to be formatted such that it understands the vararg type properly?

答:
You can declare as an array.

```<code>setResolvedResponse(Section[] secs)
</code>```

So instead of:

```<code>setResolvedResponse(obj1, obj2, obj3)
</code>```

Call:

```<code>setResolvedResponse(new String[]{ obj1, obj2, obj3})
</code>```

Body:
You can declare as an array.

setResolvedResponse(Section[] secs)

So instead of:

setResolvedResponse(obj1, obj2, obj3)

Call:

setResolvedResponse(new String[]{ obj1, obj2, obj3})


问:
How to transpose a Hive table
Could anyone help me understand, how to pivot an Hive table.

I have an Hive table like this :

```<code>ColumnA    ColumnB    Column C    Date        Price
A1          B1        C1          20171001    100
A1          B2        C2          20171001    50
A2          B2        C2          20171002    75
A3          B1        C2          20171002    10
</code>```

I want to pivot the above table like this:

```<code>ColumnA    ColumnB    Column C    20171001    20171002    Total
A1         B1         C1          100                     100
A1         B2         C2          50                      50
A2         B2         C1                       75         75
A3         B1         C2                       10         10
</code>```

答:
Try This.

```<code>select
        ColumnA,
        ColumnB,
        ColumnC,
        MAX ( CASE
                WHEN Date_ = '20171001'
                THEN Price
        END ) price_20171001,
        MAX ( CASE
                WHEN Date_ = '20171002'
                THEN Price
        END )      price_20171002 ,
        Max(Price) Total
FROM
        Yourtable
GROUP BY
        ColumnA,
        ColumnB,
        ColumnC
ORDER BY
        ColumnA;
</code>```

Note : Since Date is an Invalid column , I have used Date_.

Title: How to transpose a Hive table

Body:
Could anyone help me understand, how to pivot an Hive table.

I have an Hive table like this :

ColumnA    ColumnB    Column C    Date        Price
A1          B1        C1          20171001    100
A1          B2        C2          20171001    50
A2          B2        C2          20171002    75
A3          B1        C2          20171002    10

I want to pivot the above table like this:

ColumnA    ColumnB    Column C    20171001    20171002    Total
A1         B1         C1          100                     100
A1         B2         C2          50                      50
A2         B2         C1                       75         75
A3         B1         C2                       10         10

Body:
Try This.

select
        ColumnA,
        ColumnB,
        ColumnC,
        MAX ( CASE
                WHEN Date_ = '20171001'
                THEN Price
        END ) price_20171001,
        MAX ( CASE
                WHEN Date_ = '20171002'
                THEN Price
        END )      price_20171002 ,
        Max(Price) Total
FROM
        Yourtable
GROUP BY
        ColumnA,
        ColumnB,
        ColumnC
ORDER BY
        ColumnA;

Note : Since Date is an Invalid column , I have used Date_.


问:
GPS disabling feature
I am developing a app.. When i start the app my GPS is enabled but on exit it should disable the GPS. how to do it? please help</p>

答:
I don't think its not possible.

Try something like this:

```<code>LocationManager.removeUpdates(LocationListener);
</code>```

I hope it is what you're looking for.

Title: GPS disabling feature

Body:
I don't think its not possible.

Try something like this:

LocationManager.removeUpdates(LocationListener);

I hope it is what you're looking for.


问:
Add WSDL URL from properties into pom
not sure if this question was already answered, but I've been looking in google and stackoverflow for a while and didn't find something for the requirement I need.

I have a pom.xml file in which I'm defining a property (which is a WSDL URL):

```<code><properties>
    <service.wsdl.url>https://myservice.com/testservice.asmx?wsdl</service.wsdl.url>
</properties>
</code>```

And then I have a plugin defined for web service components generation using wsimport:

```<code>        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <version>1.12</version>
            <executions>
                <execution>
                    <id>myservice</id>
                    <goals>
                        <goal>wsimport</goal>
                    </goals>
                    <configuration>
                        <wsdlUrls>
                            <wsdlUrl>${service.wsdl.url}</wsdlUrl>
                        </wsdlUrls>
                        <packageName>com.myservice.generated</packageName>
                        <sourceDestDir>src/main/java</sourceDestDir>
                        <args>
                            <arg>-B-XautoNameResolution</arg>
                        </args>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

The question I have is on how can I get the URL from a properties file. I have a properties file called "application.properties" in my src/main/resources folder in which I have a key/value pair:

service.wsdl.url = https://myservice.com/testservice.asmx?wsdl

I'd like to do something like:

```<code><properties>
    <service.wsdl.url>${service.wsdl.url}</service.wsdl.url>
</properties>
</code>```

I've checking some answers and posts but as mentioned I was not able to find something for my needs.

Any help will be appreciated.

Thanks in advance!

答:
You can probably make use of the properties-maven-plugin as:

```<code>  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
      <execution>
        <phase>initialize</phase>
        <goals>
          <goal>read-project-properties</goal>
        </goals>
        <configuration>
          <files>
            <file>src/main/resources/application.properties</file>
          </files>
        </configuration>
      </execution>
    </executions>
  </plugin>
</code>```

Title: Add WSDL URL from properties into pom

Body:
not sure if this question was already answered, but I've been looking in google and stackoverflow for a while and didn't find something for the requirement I need.

I have a pom.xml file in which I'm defining a property (which is a WSDL URL):

<properties>
    <service.wsdl.url>https://myservice.com/testservice.asmx?wsdl</service.wsdl.url>
</properties>

And then I have a plugin defined for web service components generation using wsimport:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <version>1.12</version>
            <executions>
                <execution>
                    <id>myservice</id>
                    <goals>
                        <goal>wsimport</goal>
                    </goals>
                    <configuration>
                        <wsdlUrls>
                            <wsdlUrl>${service.wsdl.url}</wsdlUrl>
                        </wsdlUrls>
                        <packageName>com.myservice.generated</packageName>
                        <sourceDestDir>src/main/java</sourceDestDir>
                        <args>
                            <arg>-B-XautoNameResolution</arg>
                        </args>
                    </configuration>
                </execution>
            </executions>
        </plugin>

The question I have is on how can I get the URL from a properties file. I have a properties file called "application.properties" in my src/main/resources folder in which I have a key/value pair:

service.wsdl.url = https://myservice.com/testservice.asmx?wsdl

I'd like to do something like:

<properties>
    <service.wsdl.url>${service.wsdl.url}</service.wsdl.url>
</properties>

I've checking some answers and posts but as mentioned I was not able to find something for my needs.

Any help will be appreciated.

Thanks in advance!

Body:
You can probably make use of the properties-maven-plugin as:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
      <execution>
        <phase>initialize</phase>
        <goals>
          <goal>read-project-properties</goal>
        </goals>
        <configuration>
          <files>
            <file>src/main/resources/application.properties</file>
          </files>
        </configuration>
      </execution>
    </executions>
  </plugin>


问:
Spring Boot microservice response issue with Angular 2 http call
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

```<code>@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}
</code>```

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

答:
The accepted answer is good since it provides a working solution but it also forces you to hardcode client's URL on the server side in every controller. You can set up a global CORS configuration instead. If your web configuration extends the WebMvcConfigurereAdapter class you can simply override the addCorsMappings method. The following example enables CORS for the whole application:

```<code>@Configuration
public class WebConfig extends WebMvcConfigurereAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
</code>```

Read more about CORS support in Spring here

Body:
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

Body:
The accepted answer is good since it provides a working solution but it also forces you to hardcode client's URL on the server side in every controller. You can set up a global CORS configuration instead. If your web configuration extends the WebMvcConfigurereAdapter class you can simply override the addCorsMappings method. The following example enables CORS for the whole application:

@Configuration
public class WebConfig extends WebMvcConfigurereAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Read more about CORS support in Spring here


问:
CSS "underline" text part
How can I "underline" text to get the same effect like you can see under "TEST"?

I tried to encapsulate TEST in a span and adding an absolute :after with position: absolute, but I think it's not the correct way and haven't been able to obtain the expected result.

Here's the HTML

    ALL THIS TEXT IS

    A TEST

```

答:
Something like this?

body{
  background: #333;
  font-family: arial;
}

.hero-text{
  color: #fff;
  text-align: center;
}

.bold.striked{
  position: relative;
  color: #fff;
  text-align: center;
  width: 300px;
  margin: 0 auto;
  z-index: 2;
}

.bold.striked::before{
  content: "";
  height: 15px;
  width: calc(100% + 50px);
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  background: #4882d5;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="white hero-text">
    <span class="thin">ALL THIS TEXT IS</span>
    <br>
    <span class="bold striked">A TEST</span>
</h1></code>```

Title: CSS "underline" text part

Body:
Something like this?

body{
  background: #333;
  font-family: arial;
}

.hero-text{
  color: #fff;
  text-align: center;
}

.bold.striked{
  position: relative;
  color: #fff;
  text-align: center;
  width: 300px;
  margin: 0 auto;
  z-index: 2;
}

.bold.striked::before{
  content: "";
  height: 15px;
  width: calc(100% + 50px);
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  background: #4882d5;
  z-index: -1;
}

<h1 class="white hero-text">
    <span class="thin">ALL THIS TEXT IS</span>
    <br>
    <span class="bold striked">A TEST</span>
</h1>


问:
How do i get the timestamps for a max(val) and min(val) in a window?
How do i get the timestamps for a MAX(val) and MINval) in a NAMED WINDOW or WINDOW?

Window:

```<code>[
t1- 100
t2- 200
t3- 250
t4- 900
]
</code>```

every time the window is released I want t1 with its min value and t4 with its max value.

I tried with subquery on my NAMED WINDOW, but it says aggregation in subqueries not allowed. Consider using INSERT INTO instead.

Can someone help me out?

Thanks

答: You can use maxby(val).timestamp

Body:
How do i get the timestamps for a MAX(val) and MINval) in a NAMED WINDOW or WINDOW?

Window:

[
t1- 100
t2- 200
t3- 250
t4- 900
]

every time the window is released I want t1 with its min value and t4 with its max value.

I tried with subquery on my NAMED WINDOW, but it says aggregation in subqueries not allowed. Consider using INSERT INTO instead.

Can someone help me out?

Thanks

Body: You can use maxby(val).timestamp


问:
Have an excel cell value list except when the value is null
I have an integer list "myList" that corresponds to empty excel lines and I would like to retrieve the values of all cells that are not empty thanks to LINQ
I already dit that to get all the value:

```<code> var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();
</code>```

and i tried that to get all the value without the empty cell:

```<code> var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString().Where(p => { x.Row != ctrl.myList.ElementAt(p); })).ToList();
</code>```

and that :

```<code>var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y => ctrl.myList.ForEach(p =>
            {
                int i = ctrl.myList.ElementAt(p);
                if (i != y.Row)
                {
                }
            }) != y.Row).Select(x => x.Value2.ToString()).ToList();
</code>```

but of course it doesn't compile, I have tried other things but it doesn't work either and I am short of ideas...
Thank you for your help.

all the code :

```<code> int nInLastRow = worksheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
 Excel.Range selectedRange = (Excel.Range)worksheet.get_Range("B2:B" + nInLastRow);
 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();
</code>```

答:
```<code>List<double> list = selection.Cast<Range>().Select(r => r.Value).OfType<double>().ToList();
</code>```

to get all numbers, but faster to get all values at once:

```<code>object o = selection.Value;
List<double> list = (o as object[,] ?? new[,] { { o } }).OfType<double>().ToList();
</code>```

Body:
I have an integer list "myList" that corresponds to empty excel lines and I would like to retrieve the values of all cells that are not empty thanks to LINQ
I already dit that to get all the value:

 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();

and i tried that to get all the value without the empty cell:

 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString().Where(p => { x.Row != ctrl.myList.ElementAt(p); })).ToList();

and that :

var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y => ctrl.myList.ForEach(p =>
            {
                int i = ctrl.myList.ElementAt(p);
                if (i != y.Row)
                {
                }
            }) != y.Row).Select(x => x.Value2.ToString()).ToList();

but of course it doesn't compile, I have tried other things but it doesn't work either and I am short of ideas...
Thank you for your help.

all the code :

 int nInLastRow = worksheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
 Excel.Range selectedRange = (Excel.Range)worksheet.get_Range("B2:B" + nInLastRow);
 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();

Body:
List<double> list = selection.Cast<Range>().Select(r => r.Value).OfType<double>().ToList();

to get all numbers, but faster to get all values at once:

object o = selection.Value;
List<double> list = (o as object[,] ?? new[,] { { o } }).OfType<double>().ToList();


问:
How to update Temp table by providing column name through variable
I have temp table generated by dynamic SQL query with different column name depends upon data. when I want to update temp table by given hard coded column name it works fine. but when I pass column name by variable it won't works

```<code>update #Temp
set @value = ''' + cast(@TempData as nvarchar(max)) +  '''
where id = @CUserID
</code>```

here  @value holds column name like [Dusky Legend] this query won't works but

```<code>update #Temp
set [Dusky Legend] = ''' + cast(@TempData as nvarchar(max)) +  '''
where id = @CUserID
</code>```

this works properly ,
my problem is I have only way to provide column name by variable
this is my complete code

```<code> Declare @MarketID AS NVARCHAR(MAX) = '1.136903880';
 Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';
 declare @TempData as numeric = 1111111111;
 declare @@values as NVARCHAR(MAX) ='';

 DECLARE @colsSelect AS NVARCHAR(MAX);
 DECLARE @colsLoop AS NVARCHAR(MAX);

 DECLARE @query AS NVARCHAR(MAX);

 SELECT @colsSelect = STUFF((SELECT distinct ',' +
                    '00' + ' as ' + QUOTENAME(name)
 from RunnersInfoes   AS t where marketID =@MarketID

                  FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                    , 1, 1, '');

                    SELECT @colsLoop = STUFF((SELECT distinct ',' +
                    QUOTENAME(name)
                    from RunnersInfoes   AS t where marketID =@MarketID

                    FOR XML PATH(''), TYPE
                   ).value('.', 'NVARCHAR(MAX)')
                    , 1, 1, '');

                    --print @colsLoop

 set @query=
 '
 ;with cte
 as
 (
 select
 id, ParentId,0 AS Level,Share ,AccountTypeName,FirstName
 from  dbo.View_UserProfile
 where View_UserProfile.id = ' + '''' + @UserID + '''' +'
 union all
select
t.id, t.ParentId,Level + 1 AS Level,t.Share,t.AccountTypeName ,t.FirstName
 from View_UserProfile t
 inner join cte on t.ParentId = cte.id)

SELECT ID,AccountTypeName as Type,FirstName as Name, ' + @colsSelect + '  into                   #Temp  from cte as t

--exec tempdb..sp_help #Temp

 Declare @CUserID AS NVARCHAR(MAX)

 DECLARE dynamic_cursor CURSOR FOR
 select ID from #Temp
 OPEN dynamic_cursor

 FETCH NEXT FROM dynamic_cursor   INTO @CUserID

 WHILE @@FETCH_STATUS = 0
BEGIN

 declare @pos as numeric = 0
 declare  @len as numeric = 0
 declare @value as varchar(255)

 WHILE CHARINDEX('','',  ''' + @colsLoop +''', @pos+1)>0
    BEGIN
   set @len = CHARINDEX('','', ''' + @colsLoop +''', @pos+1) - @pos
   set @value = SUBSTRING(''' + @colsLoop +''', @pos, @len)
   PRINT  @value

   update #Temp set [Dusky Legend] = ''' + cast(@TempData as nvarchar(max)) +   ''' where id = @CUserID

set @pos = CHARINDEX('','', ''' + @colsLoop +''', @pos+@len) +1
         END

          --print' + cast(@TempData as nvarchar(max)) +'

          --update #Temp set [Dusky Legend] =''' + cast(@TempData as  nvarchar(max)) +  ''' where id = @CUserID

           FETCH NEXT FROM dynamic_cursor INTO @CUserID

            END

           CLOSE dynamic_cursor
          DEALLOCATE dynamic_cursor

           select * from #Temp

             '
           execute  (@query)
</code>```

答:
You need dynamic SQL.

```<code>declare @value varchar(64) = '[Dusky Legend]'
declare @TempData varchar(max) = 'some value'
declare @CUSerID int = 14

declare @sql varchar(max)
set @sql = '
update #Temp
set ' + @value + ' = ' + cast(@TempData as nvarchar(max)) +  '
where id = ' + cast(@CUserID as varchar(256))

 print(@sql)
 --exec(@sql)
</code>```

Side note, you may need a global TempTable depending on how you are doing this.

Body:
I have temp table generated by dynamic SQL query with different column name depends upon data. when I want to update temp table by given hard coded column name it works fine. but when I pass column name by variable it won't works

update #Temp
set @value = ''' + cast(@TempData as nvarchar(max)) +  '''
where id = @CUserID

here  @value holds column name like [Dusky Legend] this query won't works but

update #Temp
set [Dusky Legend] = ''' + cast(@TempData as nvarchar(max)) +  '''
where id = @CUserID

this works properly ,
my problem is I have only way to provide column name by variable
this is my complete code

 Declare @MarketID AS NVARCHAR(MAX) = '1.136903880';
 Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';
 declare @TempData as numeric = 1111111111;
 declare @@values as NVARCHAR(MAX) ='';

 DECLARE @colsSelect AS NVARCHAR(MAX);
 DECLARE @colsLoop AS NVARCHAR(MAX);

 DECLARE @query AS NVARCHAR(MAX);

 SELECT @colsSelect = STUFF((SELECT distinct ',' +
                    '00' + ' as ' + QUOTENAME(name)
 from RunnersInfoes   AS t where marketID =@MarketID

                  FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                    , 1, 1, '');

                    SELECT @colsLoop = STUFF((SELECT distinct ',' +
                    QUOTENAME(name)
                    from RunnersInfoes   AS t where marketID =@MarketID

                    FOR XML PATH(''), TYPE
                   ).value('.', 'NVARCHAR(MAX)')
                    , 1, 1, '');

                    --print @colsLoop

 set @query=
 '
 ;with cte
 as
 (
 select
 id, ParentId,0 AS Level,Share ,AccountTypeName,FirstName
 from  dbo.View_UserProfile
 where View_UserProfile.id = ' + '''' + @UserID + '''' +'
 union all
select
t.id, t.ParentId,Level + 1 AS Level,t.Share,t.AccountTypeName ,t.FirstName
 from View_UserProfile t
 inner join cte on t.ParentId = cte.id)

SELECT ID,AccountTypeName as Type,FirstName as Name, ' + @colsSelect + '  into                   #Temp  from cte as t

--exec tempdb..sp_help #Temp

 Declare @CUserID AS NVARCHAR(MAX)

 DECLARE dynamic_cursor CURSOR FOR
 select ID from #Temp
 OPEN dynamic_cursor

 FETCH NEXT FROM dynamic_cursor   INTO @CUserID

 WHILE @@FETCH_STATUS = 0
BEGIN

 declare @pos as numeric = 0
 declare  @len as numeric = 0
 declare @value as varchar(255)

 WHILE CHARINDEX('','',  ''' + @colsLoop +''', @pos+1)>0
    BEGIN
   set @len = CHARINDEX('','', ''' + @colsLoop +''', @pos+1) - @pos
   set @value = SUBSTRING(''' + @colsLoop +''', @pos, @len)
   PRINT  @value

   update #Temp set [Dusky Legend] = ''' + cast(@TempData as nvarchar(max)) +   ''' where id = @CUserID

set @pos = CHARINDEX('','', ''' + @colsLoop +''', @pos+@len) +1
         END

          --print' + cast(@TempData as nvarchar(max)) +'

          --update #Temp set [Dusky Legend] =''' + cast(@TempData as  nvarchar(max)) +  ''' where id = @CUserID

           FETCH NEXT FROM dynamic_cursor INTO @CUserID

            END

           CLOSE dynamic_cursor
          DEALLOCATE dynamic_cursor

           select * from #Temp

             '
           execute  (@query)

Body:
You need dynamic SQL.

declare @value varchar(64) = '[Dusky Legend]'
declare @TempData varchar(max) = 'some value'
declare @CUSerID int = 14

declare @sql varchar(max)
set @sql = '
update #Temp
set ' + @value + ' = ' + cast(@TempData as nvarchar(max)) +  '
where id = ' + cast(@CUserID as varchar(256))

 print(@sql)
 --exec(@sql)

Side note, you may need a global TempTable depending on how you are doing this.


问:
MonoTouch's Soft Debugger don't connect to App on iPhone - why?
I'm quite new on MonoTouch, so please forgive me my question in doubt... ;-)

I need help with the soft-debugger, because it's not connecting to the App on the device. While with iPhone Simulator everything is working as expected, the following happens when I start debugging against my device:

The is uploaded and installed to the device.

MonoDevelop comes up with a window saying the following: "Waiting for debugger to connect on 127.0.0.1:10000..." Please start the application on the device"

When starting the app on the device, the device vibrates indicating that the debugger is not connected....

In the settings of my App on the iPhone I have set the IP-Adress to my Mac's IP.

My iPhone is connected via WIFI to my network. I can ping my Mac from my iPhone and vice versa.

In several screenshots where the debugger was obviously working I saw that the debugger came up with the Mac's IP address and not the 127.0.0.1....

Do I have to configure my IP-address somewhere in MonoDevelop?

BTW: I'm using the latest version of MonoDevelop - it's 2.4.1

I have tried anything.... re-installing MonoDevelop, cleaning up the project several times, setting up a new project.... nothing...

Please, please help....

答:
Alex,

many thanks for your replies! They were very helpful to me (especially point 5).

I have solved the problem by setting the Host IP in the ~/.config/MonoDevelop/MonoDevelopProperties.xml. That did it! :-)

Now I'm wondering where I do this setting in the MonoDevelop GUI... ;-)

Cheers,
Andreas


问:
Not able to highlight a number of words in a text on python

 I was wondering what is wrong here? It should be highlighting all the words in a list when a button is clicked. However, this is the error that comes up:

```<code>Exception in Tkinter callback <br>
Traceback (most recent call last):
  File "C:\Users\Reuben_2\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/Reuben_2/AppData/Local/Programs/Python/Python36/Writing is hard/MyHighlighter.py", line 54, in highlight_text
    pos = ArticleTextBox.search(names[2], pos, stopindex=END, count=lenght)
  File "C:\Users\Reuben_2\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3332, in search
    return str(self.tk.call(tuple(args)))
_tkinter.TclError: bad text index ""
</code>```

Here is my code:

```<code>  def highlight_text():
        article=ArticleTextBox.get(0.0,tk.END)
        my_sent=article
        names=(get_continuous_chunks(my_sent))
        lenght = StringVar()
        pos = '1.0'
        for w in range(0,nameslistlength):
            while True:
                pos = ArticleTextBox.search(names[w], pos, stopindex=END, count=lenght)
                if not pos:
                    break
                ArticleTextBox.tag_add('highlight', pos, '{}+{}c'.format(pos, lenght.get()))
                pos += '+1c'
</code>```

Thank you for your help. Please let me know if you have any questions + any tips on how to improve my stack overflow questions.

答:
The error comes at the start of the second iteration of the for loop.

The first iteration can only end when the while loop ends, and it can only end when pos is the empty string. Thus, when the second iteration of the for loop starts, pos is the empty string which you then try to use when calling search.

The solution is to reset pos to "1.0" at the start of the for loop, assuming that the purpose of the for loop is to search then entire widget for each word or phrase in names.

By the way, the pythonic way to iterate over a loop isn't to get the length and then iterate over the indexes. Instead, directly iterate over the list:

```<code>for name in names:
    pos = "1.0"
    while True:
        pos = ArticleTextBox.search(name, ...)
        ...
    ...
</code>```

Body:
 I was wondering what is wrong here? It should be highlighting all the words in a list when a button is clicked. However, this is the error that comes up:

Exception in Tkinter callback

Traceback (most recent call last):
  File "C:\Users\Reuben_2\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/Reuben_2/AppData/Local/Programs/Python/Python36/Writing is hard/MyHighlighter.py", line 54, in highlight_text
    pos = ArticleTextBox.search(names[2], pos, stopindex=END, count=lenght)
  File "C:\Users\Reuben_2\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3332, in search
    return str(self.tk.call(tuple(args)))
_tkinter.TclError: bad text index ""

Here is my code:

  def highlight_text():
        article=ArticleTextBox.get(0.0,tk.END)
        my_sent=article
        names=(get_continuous_chunks(my_sent))
        lenght = StringVar()
        pos = '1.0'
        for w in range(0,nameslistlength):
            while True:
                pos = ArticleTextBox.search(names[w], pos, stopindex=END, count=lenght)
                if not pos:
                    break
                ArticleTextBox.tag_add('highlight', pos, '{}+{}c'.format(pos, lenght.get()))
                pos += '+1c'

Thank you for your help. Please let me know if you have any questions + any tips on how to improve my stack overflow questions.

Body:
The error comes at the start of the second iteration of the for loop.

The first iteration can only end when the while loop ends, and it can only end when pos is the empty string. Thus, when the second iteration of the for loop starts, pos is the empty string which you then try to use when calling search.

The solution is to reset pos to "1.0" at the start of the for loop, assuming that the purpose of the for loop is to search then entire widget for each word or phrase in names.

By the way, the pythonic way to iterate over a loop isn't to get the length and then iterate over the indexes. Instead, directly iterate over the list:

for name in names:
    pos = "1.0"
    while True:
        pos = ArticleTextBox.search(name, ...)
        ...
    ...


问:
How can I repeat the last VIM macro?
I know how to repeat the last command in Vim. I use ..

But how can I repeat the last macro? It's a little non-comfortable to press @q everytime I want to repeat it.

I tried with . but it just repeats the last command from the macro.

Is there a shorter way of doing that?

答:
I find @@ a bit hard to type and as I don't use , much - and it's close enough to .:

```<code>:map , @@
</code>```

Title: How can I repeat the last VIM macro?

Body:
I find @@ a bit hard to type and as I don't use , much - and it's close enough to .:

:map , @@


问:
How to use JS to check if divs have svg tags inside of them?
I have this JS function that essentially cycles through some divs to see if there is a question mark side the div tags (which in my app means a question wasn't answered) and if it finds one, it displays a required message for that field and puts a red border around it to make it more noticeable.

```<code>  $( function() {
        //stuff to do on submit
        $('#add').submit(function() {
          const allFields = [ 'dob', 'tob', 'sex', 'weight'];

          allFields
            .forEach(nameOfField => {
              $(displayError(nameOfField)).hide();
              $(formField(nameOfField)).removeClass('error-border');
            });

          const listOfFieldsFailedValidation =
            allFields
              .filter(field => {

                //The two lines in question
                const fieldText = $('#' + field + '-display').text();
                return fieldText.indexOf('?') !== -1;

              });

          if (listOfFieldsFailedValidation.length <= 0)
            return true;

          $('html,body').animate({scrollTop:0}, 0);

          listOfFieldsFailedValidation
            .forEach(nameOfFieldFailedValidation => {
              $(displayError(nameOfFieldFailedValidation)).show();
              $(formField(nameOfFieldFailedValidation)).addClass('error-border');
            });

          return false;
        });

});
</code>```

I have since edited my app to use SVG question marks inside the divs, instead of plain text question marks.

So now I need to check if a SVG tags exist in the divs, rather than checking if the text includes a "?".  I'd like to simply edit the "two lines in question" (noted in the code) to keep everything within this overall function.  is that possible?

I tried replacing the two lines in question with the following but no luck:

```<code> const fieldText = $('#' + field + '-display');
 return fieldText.getElementsByTagName('svg').length > 0;
</code>```

Can anyone help me correctly check to see if SVG tags exist, instead of a plain text question mark, all while using this same overall function?

答:
Using the .find() method.

$(document).ready(function () {

   var svg = $("div").find("svg");

   console.log(svg.length) // Outputs 7

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
</div></code>```

Or use a CSS selector inside the jQuery selector.

$(document).ready(function () {

   // Or use a CSS selector
   var svg = $("div svg");

   console.log(svg.length) // Outputs 7

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
</div></code>```

Body:
I have this JS function that essentially cycles through some divs to see if there is a question mark side the div tags (which in my app means a question wasn't answered) and if it finds one, it displays a required message for that field and puts a red border around it to make it more noticeable.

  $( function() {
        //stuff to do on submit
        $('#add').submit(function() {
          const allFields = [ 'dob', 'tob', 'sex', 'weight'];

          allFields
            .forEach(nameOfField => {
              $(displayError(nameOfField)).hide();
              $(formField(nameOfField)).removeClass('error-border');
            });

          const listOfFieldsFailedValidation =
            allFields
              .filter(field => {

                //The two lines in question
                const fieldText = $('#' + field + '-display').text();
                return fieldText.indexOf('?') !== -1;

              });

          if (listOfFieldsFailedValidation.length <= 0)
            return true;

          $('html,body').animate({scrollTop:0}, 0);

          listOfFieldsFailedValidation
            .forEach(nameOfFieldFailedValidation => {
              $(displayError(nameOfFieldFailedValidation)).show();
              $(formField(nameOfFieldFailedValidation)).addClass('error-border');
            });

          return false;
        });

});

I have since edited my app to use SVG question marks inside the divs, instead of plain text question marks.

So now I need to check if a SVG tags exist in the divs, rather than checking if the text includes a "?".  I'd like to simply edit the "two lines in question" (noted in the code) to keep everything within this overall function.  is that possible?

I tried replacing the two lines in question with the following but no luck:

 const fieldText = $('#' + field + '-display');
 return fieldText.getElementsByTagName('svg').length > 0;

Can anyone help me correctly check to see if SVG tags exist, instead of a plain text question mark, all while using this same overall function?

Body:
Using the .find() method.

$(document).ready(function () {

   var svg = $("div").find("svg");

   console.log(svg.length) // Outputs 7

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
</div>

Or use a CSS selector inside the jQuery selector.

$(document).ready(function () {

   // Or use a CSS selector
   var svg = $("div svg");

   console.log(svg.length) // Outputs 7

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
  <svg></svg>
</div>


问:
Java - moving first letter of string to the end, and determining if word is the same when spelled backwards
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

```<code>public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}
</code>```

答:
This works:</p>

```<code>   import java.util.*;

public class HelloWorld{

     public static void main(String []args){
         Scanner scan = new Scanner(System.in);
        String s1 = scan.next();
        char s2 = s1.charAt(0);
        String s3 = s1.substring(1) + s2;
        s3 = new StringBuilder(s3).reverse().toString();
        if(s1.equals(s3))
            System.out.println("They are same");
        else
            System.out.println("They are not the same");

     }
}
</code>```

Body:
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}

Body:
This works:

   import java.util.*;

public class HelloWorld{

     public static void main(String []args){
         Scanner scan = new Scanner(System.in);
        String s1 = scan.next();
        char s2 = s1.charAt(0);
        String s3 = s1.substring(1) + s2;
        s3 = new StringBuilder(s3).reverse().toString();
        if(s1.equals(s3))
            System.out.println("They are same");
        else
            System.out.println("They are not the same");

     }
}