问:
Error in finding lowest common ancestor in tree
I am trying to find the lowest common ancestor of the two given values in the tree.

My approach is to traverse to the bottom left of the tree and check individual nodes weather they have both the nodes under them. The first node to give a match is the lowest common ancestor.

Can anyone tell me the error in this function.

```<code>/*
Node is defined as

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/

bool find(node *root,int val)  //to check if the value exist under the given node or not
{
    if(root==NULL)
        return false;
    if(root->data==val)
        return true;

    if((root->left&&find(root->left,val))||(root->right&&find(root->right,val)))
        return true;
    return false;
}

node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor
{
    if(root==NULL)
        return NULL;
    static node* ans=NULL;
    lca(root->left,v1,v2);  //traversing to the bottom of the tree
    lca(root->right,v1,v2);

    if((find(root->left,v1)&&find(root->right,v2))||(find(root->left,v2)&&find(root->right,v1)))   //checking the existence of both nodes under the tree
    {
        if(ans==NULL)
            ans=root;
    }

    return ans;  //returning the lca
}
</code>```

答:
Your recursive function should return only a node if the result was found. It should return NULL if the result node was not found. Break if the node was found, else continue. I would do it like this:

```<code>node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor
{
    if(root==NULL)
        return NULL;

    node* ans=NULL;

    // search the left child tree
    ans = lca(root->left,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // search the right child tree
    ans = lca(root->right,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // test this tree node
    if( (find(root->left,v1)&&find(root->right,v2)) ||
        (find(root->left,v2)&&find(root->right,v1)))
    {
        // If the condition is true, this node is the result
        return root;
    }

    return NULL; // Neither this node nor any subordinate node of this node is the result
}
</code>```

Body:
I am trying to find the lowest common ancestor of the two given values in the tree.

My approach is to traverse to the bottom left of the tree and check individual nodes weather they have both the nodes under them. The first node to give a match is the lowest common ancestor.

Can anyone tell me the error in this function.

/*
Node is defined as

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/

bool find(node *root,int val)  //to check if the value exist under the given node or not
{
    if(root==NULL)
        return false;
    if(root->data==val)
        return true;

    if((root->left&&find(root->left,val))||(root->right&&find(root->right,val)))
        return true;
    return false;
}

node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor
{
    if(root==NULL)
        return NULL;
    static node* ans=NULL;
    lca(root->left,v1,v2);  //traversing to the bottom of the tree
    lca(root->right,v1,v2);

    if((find(root->left,v1)&&find(root->right,v2))||(find(root->left,v2)&&find(root->right,v1)))   //checking the existence of both nodes under the tree
    {
        if(ans==NULL)
            ans=root;
    }

    return ans;  //returning the lca
}

Body:
Your recursive function should return only a node if the result was found. It should return NULL if the result node was not found. Break if the node was found, else continue. I would do it like this:

node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor
{
    if(root==NULL)
        return NULL;

    node* ans=NULL;

    // search the left child tree
    ans = lca(root->left,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // search the right child tree
    ans = lca(root->right,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // test this tree node
    if( (find(root->left,v1)&&find(root->right,v2)) ||
        (find(root->left,v2)&&find(root->right,v1)))
    {
        // If the condition is true, this node is the result
        return root;
    }

    return NULL; // Neither this node nor any subordinate node of this node is the result
}


来源: stackexchange

问:
There is no error in the code , but also it is not getting executed?
```<code>enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)
</code>```

答:
Why not simply compare account_key

```<code>enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    if enrollment['account_key'] == unique_engagement_students['account_key']:
        print (enrollment)
</code>```

Output:

```<code>{'name': 'Amruta', 'account_key': 4162}
</code>```

Now, if unique_engagement_students is also list of dictionary then:

```<code>enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students=[{'name':'Amruta','account_key':4162},
                            {'name':'ABC','account_key':123}]

for enrollment in enrollments:
    if enrollment in unique_engagement_students:
        print (enrollment)
</code>```

Output:

```<code>{'name': 'Amruta', 'account_key': 4162}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why not simply compare account_key

enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    if enrollment['account_key'] == unique_engagement_students['account_key']:
        print (enrollment)

Output:

{'name': 'Amruta', 'account_key': 4162}

Now, if unique_engagement_students is also list of dictionary then:

enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students=[{'name':'Amruta','account_key':4162},
                            {'name':'ABC','account_key':123}]

for enrollment in enrollments:
    if enrollment in unique_engagement_students:
        print (enrollment)

Output:

{'name': 'Amruta', 'account_key': 4162}


问:
Django - order by
I need to sort my objects to use it in my template. Now it is something like:

```<code>sites = Site.objects.all().order_by('-date', '-group')[:10]
</code>```

Result is for example:

today group2

today group2

yesterday group2

yesterday group1

three days ago group2

four days ago group2

I need:

today group2

yesterday group2

three days ago group2

four days ago group2

today group1

yesterday group1

I simply need 10 newest sites ordered by group.
I would like to use it in my template (two sites in group2 first and 8 with group 2 or 1 next). Thanks for any advice.

答:
I made it that way. It works as it should.

```<code>sites = Site.objects.order_by('-date').order_by('-group', '-date')[:10]
</code>```

It wasn't good idea. Below is proper way to achieve my goal:

My view:

```<code>sites = Site.objects.order_by('-date')[:10]
</code>```

My template:

```<code>{% for site in sites|dictsortreversed:"group_id" %}
</code>```

Title: Django - order by

Body:
I need to sort my objects to use it in my template. Now it is something like:

sites = Site.objects.all().order_by('-date', '-group')[:10]

Result is for example:

today group2

today group2

yesterday group2

yesterday group1

three days ago group2

four days ago group2

I need:

today group2

yesterday group2

three days ago group2

four days ago group2

today group1

yesterday group1

I simply need 10 newest sites ordered by group.
I would like to use it in my template (two sites in group2 first and 8 with group 2 or 1 next). Thanks for any advice.

Body:
I made it that way. It works as it should.

sites = Site.objects.order_by('-date').order_by('-group', '-date')[:10]

It wasn't good idea. Below is proper way to achieve my goal:

My view:

sites = Site.objects.order_by('-date')[:10]

My template:

{% for site in sites|dictsortreversed:"group_id" %}


问:
Can I call optional::emplace as a member initializer?
I'm trying to add a new constructor an existing class and wondering if I can somehow do an emplace initialization of an optional and then use that value in the initializer for another member value.

For example:

class sample {
    my_type sc;
    optional<opt_type> run;

    sample() :
        sc( gen_default() ) {
    }

    enum ctor_alt { ctor_alt };
    sample( ctor_alt ) :
        emplace( run, ctor_arg ), /* Possible somehow? */
        sc( run.field ) {
    }
```

My primary motivation is that I don't want to alter the type of my_type. There are many users of this variable and putting it in a wrapper would require changing a lot of code.

答:
Sure thing, just call the constructor of std::optional with std::in_place_t:

```<code>run{std::in_place, ctor_arg}
</code>```

std::in_place_t is a tag type to disambiguate when you want the type to construct the value in place instead of copying it.

If you want to use the value of the optional for another member variable, you need to make sure that that member variable comes after the optional, because member objects are initialized in the order that they appear.

Body:
I'm trying to add a new constructor an existing class and wondering if I can somehow do an emplace initialization of an optional and then use that value in the initializer for another member value.

For example:

class sample {
    my_type sc;
    optional<opt_type> run;

    sample() :
        sc( gen_default() ) {
    }

    enum ctor_alt { ctor_alt };
    sample( ctor_alt ) :
        emplace( run, ctor_arg ), /* Possible somehow? */
        sc( run.field ) {
    }

My primary motivation is that I don't want to alter the type of my_type. There are many users of this variable and putting it in a wrapper would require changing a lot of code.

Body:
Sure thing, just call the constructor of std::optional with std::in_place_t:

run{std::in_place, ctor_arg}

std::in_place_t is a tag type to disambiguate when you want the type to construct the value in place instead of copying it.

If you want to use the value of the optional for another member variable, you need to make sure that that member variable comes after the optional, because member objects are initialized in the order that they appear.


问:
Python: Check if Any List Item In String, If So Assign Found Item to Variable
I've the following list:

my_list = ['a', 'b', 'c']

I've the following list of strings:

my_strings = ['azz', 'bzz', 'czz']

I'm doing the following to determine if any items of my_list are in contained within a item in my_strings:

```<code>for my_string in my_strings:
    if any(x in my_string for x in my_list):
        # Do Stuff
</code>```

What's the best practice for retaining the x as found in my_list so that I might be able to then do the following:

```<code>#Do Stuff
new_var = my_string.split('x')[1]
</code>```

The desired result would be able to assign zz to new_var by determining that a from my list was in azz from my_strings

答:
You should not use any because you actually care about which one matches:

```<code>for my_string in my_strings:
    for x in my_list:
        if x in my_string:
            #Do Stuff
            my_string.split('x')[0]
            break
</code>```

Body:
I've the following list:

my_list = ['a', 'b', 'c']

I've the following list of strings:

my_strings = ['azz', 'bzz', 'czz']

I'm doing the following to determine if any items of my_list are in contained within a item in my_strings:

for my_string in my_strings:
    if any(x in my_string for x in my_list):
        # Do Stuff

What's the best practice for retaining the x as found in my_list so that I might be able to then do the following:

#Do Stuff
new_var = my_string.split('x')[1]

The desired result would be able to assign zz to new_var by determining that a from my list was in azz from my_strings

Body:
You should not use any because you actually care about which one matches:

for my_string in my_strings:
    for x in my_list:
        if x in my_string:
            #Do Stuff
            my_string.split('x')[0]
            break


问:
How to delete specific characters from a string in Ruby?
I have several strings that look like this:

```<code>"((String1))"
</code>```

They are all different lengths. How could I remove the parentheses from all these strings in a loop?

答:
Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

```<code>irb(main)> "((String1))"[/[^()]+/]
=> "String1"
</code>```

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

```<code>irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have several strings that look like this:

"((String1))"

They are all different lengths. How could I remove the parentheses from all these strings in a loop?

Body:
Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"


问:
Hide elements when width change
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

```<code><div class="menu">
    <div class="burger-menu">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <ul class="submenu">
        <li><a href="#about-me">O mnie</a></li>
        <li><a href="">Prace</a></li>
        <li><a href="">Certyfikty</a></li>
        <li><a href="">Cennik</a></li>
        <li><a href="">Kontakt</a></li>
    </ul>
</div>
</code>```

JQuery

```<code>//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};
</code>```

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

答:
Problem:-

Window width checking code not running every-time when you are resizing your window.

Solution:-

Use  jQuery resize()  like below:-

```<code>$(window).resize(function(){
  if($(window).width() > 766){
    $('.submenu').hide();
  }else{
    console.log('halo');
   //add $('.submenu').show(); to show menu
  }
});
</code>```

Note:- rest of the code is Ok.

Title: Hide elements when width change

Body:
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

O mnie

Prace

Certyfikty

Cennik

Kontakt

JQuery

//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

Body:
Problem:-

Window width checking code not running every-time when you are resizing your window.

Solution:-

Use  jQuery resize()  like below:-

$(window).resize(function(){
  if($(window).width() > 766){
    $('.submenu').hide();
  }else{
    console.log('halo');
   //add $('.submenu').show(); to show menu
  }
});

Note:- rest of the code is Ok.


问:
Transferring an object via REST
I've been trying to send an object from one application to another using rest.

Sender:

```<code>@Controller
public class Sender {
    @RequestMapping(value = "/comMessageApp-api/getMessages")
    public String restGetMessages() {
        String url = "http://localhost:8079/comMessageApp-api/responseMessages";
        HttpEntity<Dto2> entity = new HttpEntity<>(new Dto2());
        ResponseEntity<Dto2> response = restTemplate.exchange(url, HttpMethod.POST, entity, Dto2.class);
    }
}
</code>```

Receiver:

```<code>@RestController
public class Receiver {
    @RequestMapping(value = "/comMessageApp-api/responseMessages")
    public void restResponseMessages(HttpEntity<Dto2> request) {
        System.out.println(request.getBody());
    }
}
</code>```

DTO:

```<code>public class Dto2 {
    private String string = "Test string";

    public Dto2() {
    }

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
}
</code>```

Jackson is used serialization/deserialization.

Any ideas, why request.getBody() printed in the Receiver is null???
I tried to send the object inside HttpEntity and inside RequestEntity. No success in both cases. On the receiving side I always get null.

答:
Your sender (client) side is very close but your server side doesn't return a value so change the type to Void:

```<code>ResponseEntity<Void> response = restOps.exchange(url, HttpMethod.POST, entity, Void.class);
</code>```

Your receiver (server) side is not quite set up correctly either, you need to set the HTTP method to [edited] POST.  You'll also need to tell Spring to map the body of the request (your rest payload) onto the parameter;

```<code>@RequestMapping(value = "/comMessageApp-api/responseMessages", method=RequestMethod.POST)
public void recieveDto (@RequestBody final Dto dto) {
    System.out.println(dto.toString());
}
</code>```

[EDIT] Brainfart, the http method should be set to POST on receive annotation.

[Further suggestion]
403 errors may be due to Spring Security, if you have it switched on (check your POM if you're not sure) try this;

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
        .authorizeRequests().
            antMatchers("/**").permitAll();
    }
}
</code>```

You'll want to be tightening up security once you know it works.

Title: Transferring an object via REST

Body:
I've been trying to send an object from one application to another using rest.

Sender:

@Controller
public class Sender {
    @RequestMapping(value = "/comMessageApp-api/getMessages")
    public String restGetMessages() {
        String url = "http://localhost:8079/comMessageApp-api/responseMessages";
        HttpEntity<Dto2> entity = new HttpEntity<>(new Dto2());
        ResponseEntity<Dto2> response = restTemplate.exchange(url, HttpMethod.POST, entity, Dto2.class);
    }
}

Receiver:

@RestController
public class Receiver {
    @RequestMapping(value = "/comMessageApp-api/responseMessages")
    public void restResponseMessages(HttpEntity<Dto2> request) {
        System.out.println(request.getBody());
    }
}

DTO:

public class Dto2 {
    private String string = "Test string";

    public Dto2() {
    }

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
}

Jackson is used serialization/deserialization.

Any ideas, why request.getBody() printed in the Receiver is null???
I tried to send the object inside HttpEntity and inside RequestEntity. No success in both cases. On the receiving side I always get null.

Body:
Your sender (client) side is very close but your server side doesn't return a value so change the type to Void:

ResponseEntity<Void> response = restOps.exchange(url, HttpMethod.POST, entity, Void.class);

Your receiver (server) side is not quite set up correctly either, you need to set the HTTP method to [edited] POST.  You'll also need to tell Spring to map the body of the request (your rest payload) onto the parameter;

@RequestMapping(value = "/comMessageApp-api/responseMessages", method=RequestMethod.POST)
public void recieveDto (@RequestBody final Dto dto) {
    System.out.println(dto.toString());
}

[EDIT] Brainfart, the http method should be set to POST on receive annotation.

[Further suggestion]
403 errors may be due to Spring Security, if you have it switched on (check your POM if you're not sure) try this;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
        .authorizeRequests().
            antMatchers("/**").permitAll();
    }
}

You'll want to be tightening up security once you know it works.


答:
emplace is a member function, and you cannot execute a member function until you've constructed the object (unless you're the object's constructor). But if you want to construct an engaged optional<T> in-place, you can simply use the std::in_place constructor:

```<code>run( std::in_place, ctor_arg )
</code>```

However, member initializers are always executed in the order in which the members are declared, not the order in the member initializer list (your compiler ought to warn you if you initialize them out of order). So if you want to use an earlier initializer to initialize a later variable, you have to order them correctly in your declarations:

```<code>optional<opt_type> run;
my_type sc;
</code>```

Title: Can I call optional::emplace as a member initializer?

Body:
emplace is a member function, and you cannot execute a member function until you've constructed the object (unless you're the object's constructor). But if you want to construct an engaged optional<T> in-place, you can simply use the std::in_place constructor:

run( std::in_place, ctor_arg )

However, member initializers are always executed in the order in which the members are declared, not the order in the member initializer list (your compiler ought to warn you if you initialize them out of order). So if you want to use an earlier initializer to initialize a later variable, you have to order them correctly in your declarations:

optional<opt_type> run;
my_type sc;


问:
Deleteing an image in run time
I am trying to delete an image with the method:
(the file path is correct by 100%)

```<code>if(File.Exists(filePath))
   File.Delete(filePath);
</code>```

and I am getting the following exception :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\visual_programming\yad2\yad2\bin\Debug\images\1.jpg' because it is being used by another process.

答:
It's a common issue for the images that are binded directly to ImageSource of the Image control. You should create the ImageSource through BitmapImage and set BitmapImage.CacheOption property to BitmapCacheOption.OnLoad:

```<code>BitmapImage bi = new BitmapImage();

// Begin initialization.
bi.BeginInit();

// Set properties.
bi.CacheOption = BitmapCacheOption.OnLoad;
//
bi.EndInit();
</code>```

More Details about BitmapImage.CacheOption on MSDN

Title: Deleteing an image in run time

Body:
I am trying to delete an image with the method:
(the file path is correct by 100%)

if(File.Exists(filePath))
   File.Delete(filePath);

and I am getting the following exception :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\visual_programming\yad2\yad2\bin\Debug\images\1.jpg' because it is being used by another process.

Body:
It's a common issue for the images that are binded directly to ImageSource of the Image control. You should create the ImageSource through BitmapImage and set BitmapImage.CacheOption property to BitmapCacheOption.OnLoad:

BitmapImage bi = new BitmapImage();

// Begin initialization.
bi.BeginInit();

// Set properties.
bi.CacheOption = BitmapCacheOption.OnLoad;
//
bi.EndInit();

More Details about BitmapImage.CacheOption on MSDN

ContentLicense: CC BY-SA 2.5


问:
C# 7:How can I deconstruct an object into a single value using a tuple?
One of the nice new features of C# 7 is the possibility to define deconstructors for classes and assign the deconstructed values directly to a value tuple.

However, in the case that the object is deconstructed into a single value, I can't find a way to assign it to a tuple. Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here. The only way I found to access the deconstructor was to call the Deconstruct method directly, but this eliminates its benefit, as I could use any method for this end.

Does anyone know a better way to deconstruct an object into a single value?

Here is my test code:

```<code>class TestClass
{
    private string s;
    private int n;
    public TestClass(string s, int n) => (this.s, this.n) = (s, n);
    public void Deconstruct(out string s) => s = this.s;
    public void Deconstruct(out string s, out int n) => (s, n) = (this.s, this.n);
}

static void Main(string[] args)
{
    var testObject = new TestClass("abc", 3);

    var (s1) = testObject; // sytax error (comma expected)
    ValueTuple<string> t = testObject; // error: "no implicit conversion from TestClass to (string)"
    testObject.Deconstruct(out string s2); // this works
    var (s3, n) = testObject; // no problem

    Console.WriteLine($"{s1} {t.Item1} {s2} {s3} {n}");
    Console.ReadKey();
}
</code>```

答:
Deconstructions into a single element are not supported in C# 7.0.

It is unclear why you would need such a mechanism, as you can simply access a property or write a conversion operator to achieve the same thing.

Conceptually, a tuple of one element is just that one element (you don't need a tuple to hold it). So there is no tuple syntax (using parentheses notation) to facilitate that (not to mention it would be syntactically ambiguous). The same applies for deconstructions.

Here are the most relevant LDM notes I could find: 2017-03-15 (zero and one element tuples and deconstructions).

It is possible that such deconstruction could become allowed in some future recursive pattern scenarios, but that has not been finalized yet.

Body:
One of the nice new features of C# 7 is the possibility to define deconstructors for classes and assign the deconstructed values directly to a value tuple.

However, in the case that the object is deconstructed into a single value, I can't find a way to assign it to a tuple. Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here. The only way I found to access the deconstructor was to call the Deconstruct method directly, but this eliminates its benefit, as I could use any method for this end.

Does anyone know a better way to deconstruct an object into a single value?

Here is my test code:

class TestClass
{
    private string s;
    private int n;
    public TestClass(string s, int n) => (this.s, this.n) = (s, n);
    public void Deconstruct(out string s) => s = this.s;
    public void Deconstruct(out string s, out int n) => (s, n) = (this.s, this.n);
}

static void Main(string[] args)
{
    var testObject = new TestClass("abc", 3);

    var (s1) = testObject; // sytax error (comma expected)
    ValueTuple<string> t = testObject; // error: "no implicit conversion from TestClass to (string)"
    testObject.Deconstruct(out string s2); // this works
    var (s3, n) = testObject; // no problem

    Console.WriteLine($"{s1} {t.Item1} {s2} {s3} {n}");
    Console.ReadKey();
}


问:
UITableView goes under translucent Navigation Bar
I am trying to have a transparent navigation bar in IOS 7 app. There is a full screen image in my application. I am also having a UITableView over that image. When I use the code below, image fits the screen as I want but UITableView goes under navigation bar.

in viewDidLoad

i use

```<code>self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
</code>```

it is being ok when I change to self.navigationController.navigationBar.translucent = NO; but then I lose transparency at navigation bar.

答:
Constrain the table view to the bottom of the navigation bar. The table view will automatically be offset by 44, but then in code we can just do this:

```<code>tableView.contentInset = UIEdgeInsets(top: -44, left: 0, bottom: 0, right: 0)
</code>```

The bar is transparent and has no color, but the table view does not overlap it at all. Notice the word "Hook" gets cut off despite the navigation bar being transparent. This will only work of you constrain the table view top edge to be 0 from the navigation bar. NOT 0 from the top view.

Body:
I am trying to have a transparent navigation bar in IOS 7 app. There is a full screen image in my application. I am also having a UITableView over that image. When I use the code below, image fits the screen as I want but UITableView goes under navigation bar.

in viewDidLoad

i use

self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];

it is being ok when I change to self.navigationController.navigationBar.translucent = NO; but then I lose transparency at navigation bar.

Body:
Constrain the table view to the bottom of the navigation bar. The table view will automatically be offset by 44, but then in code we can just do this:

tableView.contentInset = UIEdgeInsets(top: -44, left: 0, bottom: 0, right: 0)

The bar is transparent and has no color, but the table view does not overlap it at all. Notice the word "Hook" gets cut off despite the navigation bar being transparent. This will only work of you constrain the table view top edge to be 0 from the navigation bar. NOT 0 from the top view.


问:
Setting msExchMailboxGuid for AD
I'm trying to create an Exchange 2010 mailbox using php. I've read a thread that mentions msExchMailboxGuid is required to create the mailbox. I'm using adLDAP as a wrapper around the ldap functionality.

I'm generating a guid fine, I just can't figure out how to send it so AD likes it. I am sending it the same way the format should be to search using a guid as a hex string, which I can do without a problem.

When attempting to set that attribute, I get a Constraint violation for that field, which from searching seems to be a length issue.

Here's my guid:

66caeefb-dfc0-4f30-8d83-6b4d4d6198cf

Here it is in UTF-8 hex:

\fb\ee\ca\66\c0\df\30\4f\8d\83\6b\4d\4d\61\98\cf

I've tried it as unencoded, with slashes, without slashes, with slashes escaped, plain string guid, plain string guid without dashes... How can I send it so it will be accepted?

If I don't include msExchMailboxGuid, the AD account gets created successfully but no mailbox exists.

答:
Active Directory is expecting msExchMailboxGuid to be a binary value when creating/modifying users. You were on the right track with the hex value. Take the hex without slashes and pass it to hex2bin:

```<code>$mailboxGuid = hex2bin('fbeeca66c0df304f8d836b4d4d6198cf');
</code>```

However, you'll probably run into more issues than just the GUID. If you're willing to use a separate library, it's possible to create Exchange Mailboxes (Exchange 2010 - 2016) using the LdapTools library:

https://github.com/ldaptools/ldaptools/blob/master/docs/en/cookbook/Creating-Exchange-Mailboxes.md

I would suggest the newer AdLdap2 library, but I don't think it supports Exchange stuff anymore natively in the library.

Title: Setting msExchMailboxGuid for AD

Body:
Active Directory is expecting msExchMailboxGuid to be a binary value when creating/modifying users. You were on the right track with the hex value. Take the hex without slashes and pass it to hex2bin:

$mailboxGuid = hex2bin('fbeeca66c0df304f8d836b4d4d6198cf');

However, you'll probably run into more issues than just the GUID. If you're willing to use a separate library, it's possible to create Exchange Mailboxes (Exchange 2010 - 2016) using the LdapTools library:

https://github.com/ldaptools/ldaptools/blob/master/docs/en/cookbook/Creating-Exchange-Mailboxes.md

I would suggest the newer AdLdap2 library, but I don't think it supports Exchange stuff anymore natively in the library.


答:
You could use CSS media queries, but since you want jQuery... On window resize, you need to check the width of the window. With your code, it's only running once.</p>

```<code>$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

 $(window).resize(function(){
     if($(window).width() > 766){
        $('.submenu').hide();
     }else {
         console.log('halo');
     };
 }
</code>```

Title: Hide elements when width change

Body:
You could use CSS media queries, but since you want jQuery... On window resize, you need to check the width of the window. With your code, it's only running once.

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

 $(window).resize(function(){
     if($(window).width() > 766){
        $('.submenu').hide();
     }else {
         console.log('halo');
     };
 }


问:
copying text in tableview (swift)
I have a tableview controller, and the text in the cells are in the "basic" style.  I just typed in the text I wanted with the labels it gave me with the basic styles... How can i let the user now, be able to hold down on the text and be able to copy the text to the clipboard?

I was able to find answers to this problem for objective-c, but not for swift.  I thought it was probably in the inspector, the answer for my problem. But I can't find anything in the inspector that will allow me to do that, unless i just skipped it without noticing it.

I have tested on a real device and simulator

答:
Better way to copy data from label is using default methods of UITableView:

```<code>-(void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath;
</code>```

and their equivalents in swift:

```<code>override func tableView(_ tableView: UITableView, canPerformAction action:
Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    if (action.description == "copy:") {
        return true
    } else {
        return false
    }
}

override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
    if (action.description == "copy:") {
        //...
    }
}

override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
    return true
}
</code>```

Title: copying text in tableview (swift)

Body:
Better way to copy data from label is using default methods of UITableView:

-(void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath;

and their equivalents in swift:

override func tableView(_ tableView: UITableView, canPerformAction action:
Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    if (action.description == "copy:") {
        return true
    } else {
        return false
    }
}

override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
    if (action.description == "copy:") {
        //...
    }
}

override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
    return true
}


问:
Resuming Home Screen
I navigate to the subsequent activities in my project and from one activity i want to come at the home screen...Please suggest the exact code for it.

Thanks

答:
The trick is to launch an Intent with action set to ACTION_MAIN and a category of CATEGORY_HOME.

Something along the lines of:

```<code>Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
</code>```

Title: Resuming Home Screen

Body:
The trick is to launch an Intent with action set to ACTION_MAIN and a category of CATEGORY_HOME.

Something along the lines of:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);


问:
Why a statement written after iterating over an empty list does not work python
To my knowledge, the following code will not work:

```<code>empty_list = []
if empty_list:
    print("It's an empty list, duh...")
</code>```

However, I came across the following situation:

```<code>arr = []
for r in arr:
    print(r)
    print("Why?")
</code>```

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?

答:
The for loop iterates over all the objects in the iterable (in this case arr).

Since there are no objects in arr so the for loop will not have an object to refer to and it will reach the end of the array before entering the loop, thus finishing the loop.

Body:
To my knowledge, the following code will not work:

empty_list = []
if empty_list:
    print("It's an empty list, duh...")

However, I came across the following situation:

arr = []
for r in arr:
    print(r)
    print("Why?")

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?


答:
You are misunderstanding the use of for, it goes through all the elements of the array, and what you tell it to do, if the array is empty, it doesn't executes anything, and the variable r is not used, look:

```<code>arr = []
for r in arr:
    print(r)
    print("Why?")
</code>```

Doesn't print anything, instead

```<code>arr = [2]
for r in arr:
    print(r)
    print("Why?")
</code>```

prints:

2

why?

why? because, it has an element to go through

Title: Why a statement written after iterating over an empty list does not work python

Body:
You are misunderstanding the use of for, it goes through all the elements of the array, and what you tell it to do, if the array is empty, it doesn't executes anything, and the variable r is not used, look:

arr = []
for r in arr:
    print(r)
    print("Why?")

Doesn't print anything, instead

arr = [2]
for r in arr:
    print(r)
    print("Why?")

prints:

2

why?

why? because, it has an element to go through


问:
Starting Go server on App Engine localhost throws error
Can anyone tell me why this is happening:

```<code>$ dev_appserver.py nmg_server
INFO     2017-07-08 17:15:37,369 application_configuration.py:461] No version specified. Generated version id: 20170708t171537
WARNING  2017-07-08 17:15:37,369 application_configuration.py:166] The Managed VMs runtime is deprecated, please consider migrating your application to use the Flexible runtime. See https://cloud.google.com/appengine/docs/flexible/python/migrating for more details.
INFO     2017-07-08 17:15:37,472 devappserver2.py:116] Skipping SDK update check.
INFO     2017-07-08 17:15:37,513 api_server.py:312] Starting API server at: http://localhost:54096
INFO     2017-07-08 17:15:37,517 api_server.py:938] Applying all pending transactions and saving the datastore
INFO     2017-07-08 17:15:37,517 api_server.py:941] Saving search indexes
Traceback (most recent call last):
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 103, in <module>
    _run_file(__file__, globals())
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 97, in _run_file
    execfile(_PATHS.script_file(script_name), globals_)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 381, in <module>
    main()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 369, in main
    dev_server.start(options)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 196, in start
    options.api_host, apiserver.port, wsgi_request_info_, options.grpc_apis)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/dispatcher.py", line 223, in start
    _module.start()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/module.py", line 1647, in start
    self._add_instance()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/module.py", line 1799, in _add_instance
    expect_ready_request=True)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/go_runtime.py", line 189, in new_instance
    self._go_application.maybe_build()):
TypeError: maybe_build() takes exactly 2 arguments (1 given)
</code>```

I'm trying to run my server for testing on localhost and it keeps exiting with this error

答:
This appears to be a bug in Cloud SDK which is affecting dev_appserver.py when using with App Engine Managed VMs. It does not seem to be affecting App Engine Standard or App Engine Flex environments.

Until Google releases a new Cloud SDK with the fix, you can modify the CLOUD_SDK_INSTALL_DIR//platform/google_appengine/google/appengine/tools/devappserver2/go_managedvm.py file locally as shown below (added both the patchable unified diff as well as before/after just for convenience).

Also consider moving to App Engine Flex since Managed VMs are deprecated and will not be supported after October 27, 2017.

Warning: The Managed VMs beta environment (applications deployed with
  vm:true) is deprecated and will be decommissioned. This page is for
  users who are already using the flexible environment with vm:true in
  their app.yaml and want to upgrade to the latest release. If you are
  updating your application from the standard environment, see the
  Migrating Services from the Standard Environment to the Flexible
  Environment instead.

Diff in patchable format

```<code>--- /Users/tuxdude/google-cloud-sdk-orig/platform/google_appengine/google/appengine/tools/devappserver2go_managedvm.py     2017-07-08 11:11:11.000000000 -0700
+++ /Users/tuxdude/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/go_managedvm.py      2017-07-08 11:11:11.000000000 -0700
@@ -152,15 +152,9 @@
     logging.debug('Build succeeded:\n%s\n%s', stdout, stderr)
     self._go_executable = exe_name

-  def maybe_build(self, maybe_modified_since_last_build):
+  def maybe_build(self):
     """Builds an executable for the application if necessary.

-    Args:
-      maybe_modified_since_last_build: True if any files in the application root
-          or the GOPATH have changed since the last call to maybe_build, False
-          otherwise. This argument is used to decide whether a build is Required
-          or not.
-
     Returns:
       True if compilation was successfully performed (will raise
         an exception if compilation was attempted but failed).
@@ -173,9 +167,6 @@
       self._work_dir = tempfile.mkdtemp('appengine-go-bin')
       atexit.register(_rmtree, self._work_dir)

-    if self._go_executable and not maybe_modified_since_last_build:
-      return False
-
     if self._go_executable:
       logging.debug('Rebuilding Go application due to source modification')
     else:
</code>```

Before:

```<code>  def maybe_build(self, maybe_modified_since_last_build):
    """Builds an executable for the application if necessary.

    Args:
      maybe_modified_since_last_build: True if any files in the application root
          or the GOPATH have changed since the last call to maybe_build, False
          otherwise. This argument is used to decide whether a build is Required
          or not.

    Returns:
      True if compilation was successfully performed (will raise
        an exception if compilation was attempted but failed).
      False if compilation was not attempted.

    Raises:
      BuildError: if building the executable fails for any reason.
    """
    if not self._work_dir:
      self._work_dir = tempfile.mkdtemp('appengine-go-bin')
      atexit.register(_rmtree, self._work_dir)

    if self._go_executable and not maybe_modified_since_last_build:
      return False

    if self._go_executable:
      logging.debug('Rebuilding Go application due to source modification')
    else:
      logging.debug('Building Go application')
    self._build()
    return True
</code>```

After:

```<code>  def maybe_build(self):
    """Builds an executable for the application if necessary.

    Returns:
      True if compilation was successfully performed (will raise
        an exception if compilation was attempted but failed).
      False if compilation was not attempted.

    Raises:
      BuildError: if building the executable fails for any reason.
    """
    if not self._work_dir:
      self._work_dir = tempfile.mkdtemp('appengine-go-bin')
      atexit.register(_rmtree, self._work_dir)

    if self._go_executable:
      logging.debug('Rebuilding Go application due to source modification')
    else:
      logging.debug('Building Go application')
    self._build()
    return True
</code>```

Body:
Can anyone tell me why this is happening:

$ dev_appserver.py nmg_server
INFO     2017-07-08 17:15:37,369 application_configuration.py:461] No version specified. Generated version id: 20170708t171537
WARNING  2017-07-08 17:15:37,369 application_configuration.py:166] The Managed VMs runtime is deprecated, please consider migrating your application to use the Flexible runtime. See https://cloud.google.com/appengine/docs/flexible/python/migrating for more details.
INFO     2017-07-08 17:15:37,472 devappserver2.py:116] Skipping SDK update check.
INFO     2017-07-08 17:15:37,513 api_server.py:312] Starting API server at: http://localhost:54096
INFO     2017-07-08 17:15:37,517 api_server.py:938] Applying all pending transactions and saving the datastore
INFO     2017-07-08 17:15:37,517 api_server.py:941] Saving search indexes
Traceback (most recent call last):
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 103, in <module>
    _run_file(__file__, globals())
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 97, in _run_file
    execfile(_PATHS.script_file(script_name), globals_)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 381, in <module>
    main()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 369, in main
    dev_server.start(options)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 196, in start
    options.api_host, apiserver.port, wsgi_request_info_, options.grpc_apis)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/dispatcher.py", line 223, in start
    _module.start()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/module.py", line 1647, in start
    self._add_instance()
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/module.py", line 1799, in _add_instance
    expect_ready_request=True)
  File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/go_runtime.py", line 189, in new_instance
    self._go_application.maybe_build()):
TypeError: maybe_build() takes exactly 2 arguments (1 given)

I'm trying to run my server for testing on localhost and it keeps exiting with this error

Body:
This appears to be a bug in Cloud SDK which is affecting dev_appserver.py when using with App Engine Managed VMs. It does not seem to be affecting App Engine Standard or App Engine Flex environments.

Until Google releases a new Cloud SDK with the fix, you can modify the CLOUD_SDK_INSTALL_DIR//platform/google_appengine/google/appengine/tools/devappserver2/go_managedvm.py file locally as shown below (added both the patchable unified diff as well as before/after just for convenience).

Also consider moving to App Engine Flex since Managed VMs are deprecated and will not be supported after October 27, 2017.

Warning: The Managed VMs beta environment (applications deployed with
  vm:true) is deprecated and will be decommissioned. This page is for
  users who are already using the flexible environment with vm:true in
  their app.yaml and want to upgrade to the latest release. If you are
  updating your application from the standard environment, see the
  Migrating Services from the Standard Environment to the Flexible
  Environment instead.

Diff in patchable format

--- /Users/tuxdude/google-cloud-sdk-orig/platform/google_appengine/google/appengine/tools/devappserver2go_managedvm.py     2017-07-08 11:11:11.000000000 -0700
+++ /Users/tuxdude/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/go_managedvm.py      2017-07-08 11:11:11.000000000 -0700
@@ -152,15 +152,9 @@
     logging.debug('Build succeeded:\n%s\n%s', stdout, stderr)
     self._go_executable = exe_name

-  def maybe_build(self, maybe_modified_since_last_build):
+  def maybe_build(self):
     """Builds an executable for the application if necessary.

-    Args:
-      maybe_modified_since_last_build: True if any files in the application root
-          or the GOPATH have changed since the last call to maybe_build, False
-          otherwise. This argument is used to decide whether a build is Required
-          or not.
-
     Returns:
       True if compilation was successfully performed (will raise
         an exception if compilation was attempted but failed).
@@ -173,9 +167,6 @@
       self._work_dir = tempfile.mkdtemp('appengine-go-bin')
       atexit.register(_rmtree, self._work_dir)

-    if self._go_executable and not maybe_modified_since_last_build:
-      return False
-
     if self._go_executable:
       logging.debug('Rebuilding Go application due to source modification')
     else:

Before:

  def maybe_build(self, maybe_modified_since_last_build):
    """Builds an executable for the application if necessary.

    Args:
      maybe_modified_since_last_build: True if any files in the application root
          or the GOPATH have changed since the last call to maybe_build, False
          otherwise. This argument is used to decide whether a build is Required
          or not.

    Returns:
      True if compilation was successfully performed (will raise
        an exception if compilation was attempted but failed).
      False if compilation was not attempted.

    Raises:
      BuildError: if building the executable fails for any reason.
    """
    if not self._work_dir:
      self._work_dir = tempfile.mkdtemp('appengine-go-bin')
      atexit.register(_rmtree, self._work_dir)

    if self._go_executable and not maybe_modified_since_last_build:
      return False

    if self._go_executable:
      logging.debug('Rebuilding Go application due to source modification')
    else:
      logging.debug('Building Go application')
    self._build()
    return True

After:

  def maybe_build(self):
    """Builds an executable for the application if necessary.

    Returns:
      True if compilation was successfully performed (will raise
        an exception if compilation was attempted but failed).
      False if compilation was not attempted.

    Raises:
      BuildError: if building the executable fails for any reason.
    """
    if not self._work_dir:
      self._work_dir = tempfile.mkdtemp('appengine-go-bin')
      atexit.register(_rmtree, self._work_dir)

    if self._go_executable:
      logging.debug('Rebuilding Go application due to source modification')
    else:
      logging.debug('Building Go application')
    self._build()
    return True


问:
Which type of path to store in MySQL database?
When I come to build a simple site using PHP and MySQL, what is the best method for storing paths of files and images?

Inserting paths to Mysql as (system path C:/----)

Inserting paths to Mysql as (HTTP path http://----)

答:
Neither, the best is to store just the filename and leave your application to determine where to locate this file. You can determine it accordingly to your database table. For example, let's say we have an user table which have an avatar field. You can store just the filename (foo.jpg), and then determine the path in your application (c:\xampp\htdocs\project1\img\users\foo.jpg). Or even better, you can leave this field and store nothing about the image, then you can check if an image exists with the id of the user, like 1.jpg, 2.jpg etc.

But, if you really want to store absolute paths, start storing from your project folder. For example, lets say you have c:\xampp\htdocs\my_project\module1 Then, start from /module1

If you need to store a external URL you can save the entire like http://www.foo.com/test


问:
Where to add method for Rails controller for processing API response?
I'm using RubyGems API Wrapper to fetch gems matching a name. I submit the search query to the API, then want to filter through the response to choose the gem that matches the query precisely (the first gem is not always the best match). I've set up my controller like so:

```<code>class GemsController < ApplicationController

    def show
        gems = Gems.search(params[:name]) # From RubyGems Wrapper
        @gem = exact_name_match?(gems, params[:name]) # My own method
        if @gem
            render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok
        else
            render json: { errors: ["Gem not found"] }, status: :not_found
        end
    end
end
</code>```

I'm trying to keep the controller as skinny as possible so I wrote a method exact_name_match? but I don't know where to put it. I've read about service objects, but those seems a bit too complex for this situation.

Note: I don't have databases or models as I'm just using the API.

答:
I find the term service object sounds like more than it is. It really is just a plain ol' Ruby object. You could create a class (in a file like app/services/gem_finder.rb since app/* is auto-loaded) to encapsulate the behavior you're looking for with something like this:

```<code>class GemFinder
    def initialize(name)
        @name = name
    end

    def exact_name_match
        gems.find { |gem| @name == gem['name'] }
    end

    private

    def gems
        @gems ||= Gems.search(@name)
    end
end
</code>```

This could be used in your controller like so:

```<code>class GemsController < ApplicationController

    def show
        gem_finder = GemFinder.new(params[:name])
        if @gem = gem_finder.exact_name_match
            render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok
        else
            render json: { errors: ["Gem not found"] }, status: :not_found
        end
    end
end
</code>```

This is beneficial in that it isolates the controller from the API wrapper. If you need to use this behavior elsewhere, all of the logic for gem searching is contained in here. If there are updates to the wrapper itself, you'll only need to change the code inside this class.

Body:
I'm using RubyGems API Wrapper to fetch gems matching a name. I submit the search query to the API, then want to filter through the response to choose the gem that matches the query precisely (the first gem is not always the best match). I've set up my controller like so:

class GemsController < ApplicationController

    def show
        gems = Gems.search(params[:name]) # From RubyGems Wrapper
        @gem = exact_name_match?(gems, params[:name]) # My own method
        if @gem
            render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok
        else
            render json: { errors: ["Gem not found"] }, status: :not_found
        end
    end
end

I'm trying to keep the controller as skinny as possible so I wrote a method exact_name_match? but I don't know where to put it. I've read about service objects, but those seems a bit too complex for this situation.

Note: I don't have databases or models as I'm just using the API.

Body:
I find the term service object sounds like more than it is. It really is just a plain ol' Ruby object. You could create a class (in a file like app/services/gem_finder.rb since app/* is auto-loaded) to encapsulate the behavior you're looking for with something like this:

class GemFinder
    def initialize(name)
        @name = name
    end

    def exact_name_match
        gems.find { |gem| @name == gem['name'] }
    end

    private

    def gems
        @gems ||= Gems.search(@name)
    end
end

This could be used in your controller like so:

class GemsController < ApplicationController

    def show
        gem_finder = GemFinder.new(params[:name])
        if @gem = gem_finder.exact_name_match
            render json: { name: @gem["name"], info: @gem["info"], dependencies: @gem["dependencies"] }, status: :ok
        else
            render json: { errors: ["Gem not found"] }, status: :not_found
        end
    end
end

This is beneficial in that it isolates the controller from the API wrapper. If you need to use this behavior elsewhere, all of the logic for gem searching is contained in here. If there are updates to the wrapper itself, you'll only need to change the code inside this class.


问:
Methods to create deep copy of objects without the help of Marshal
I have 3 simple classes CashRegister, Bill and Position. A CashRegister is composed of Bill objects and a Bill object is composed of Position objects. They're implemented as followed

```<code>class CashRegister
  def initialize
    @bills = []
  end

  def clone
    #?
  end
end

class Bill
  def initialize(nr)
    @nr = nr
    @positions = []
  end

  def clone
    #?
  end
end

class Position
  def initialize(product, price)
    @product = product
    @price = price
  end

  def clone
    #?
  end
end
</code>```

How do I create methods that can deep copy the objects of these classes. The use of Marshal.load(Marshal.dump(an_obj)) is not allowed.

Edit: So far I've got this:

```<code>    class CashRegister
      def initialize
        @bills = []
      end

      def clone
        @bills.map { |bill| bill.clone}
      end
    end

    class Bill
      def initialize(nr)
        @nr = nr
        @positions = []
      end

      def clone
        cloned = super
        cloned.positions = @positions.map{ |pos| pos.clone}
        cloned
      end
    end

    class Position

      attr_reader :preis
      # this method is given
      def produkt
        @produkt.clone()
      end

      def initialize(product, price)
        @product = product
        @price = price
      end

      def clone
        cloned = super
        cloned.product
        cloned
      end
    end
</code>```

The clone method in class Position seems to be ok (no compile error). But there is an error in the one in class Bill, it says "undefined method 'positions=', so the problem must be in the line cloned.positions = @positions.map{ |pos| pos.clone}. But I don't understand, can't we call cloned.positions like that?

答:
It's just the instance variables you have to worry about.

```<code>class Position
  attr_accessor :product, :price
  def initialize(product, price)
    @product = product
    @price = price
  end
end

p1 = Position.new("lima beans", 2.31)
  #=> #<Position:0x000000027587b0 @product="lima beans", @price=2.31>
p2 = Position.new(p1.product, p1.price)
  #=> #<Position:0x0000000273dd48 @product="lima beans", @price=2.31>
</code>```

We can confirm that p2 is a deep copy of p1.

```<code>p1.product = "lettuce"
p1.price   = 1.49

p1 #=> #<Position:0x0000000271f870 @product="lettuce", @price=1.49>
p2 #=> #<Position:0x000000026e9e00 @product="lima beans", @price=2.31>

p2.product = "spinach"
p2.price = 2.10

p1 #=> #<Position:0x0000000271f870 @product="lettuce", @price=1.49>
p2 #=> #<Position:0x000000026e9e00 @product="spinach", @price=2.1>
</code>```

It's more complex if, for example, the class were defined as follows (where products is an array).

```<code>p1 = Position.new ["carrots", "onions"]
  #=> #<Position:0x000000025b8928 @products=["carrots", "onions"]>
p2 = Position.new p1.products
  #=> #<Position:0x000000025b0048 @products=["carrots", "onions"]>

p1.products << "beets"

p1 #=> #<Position:0x000000025b8928 @products=["carrots", "onions", "beets"]>
p2 #=> #<Position:0x000000025b0048 @products=["carrots", "onions", "beets"]>
</code>```

p2 is not what we want. We would need to write

```<code>p1 = Position.new ["carrots", "onions"]
  #=> #<Position:0x00000002450900 @products=["carrots", "onions"]>
p2 = Position.new p1.products.dup
  #=> #<Position:0x0000000243aa88 @products=["carrots", "onions"]>
</code>```

(note the .dup) so that

```<code>p1.products << "beets"
  #=> ["carrots", "onions", "beets"]

p1 #=> #<Position:0x00000002450900 @products=["carrots", "onions", "beets"]>
p2 #=> #<Position:0x0000000243aa88 @products=["carrots", "onions"]>
</code>```

More generally, we need to make deep copies of the instance variables.

Body:
I have 3 simple classes CashRegister, Bill and Position. A CashRegister is composed of Bill objects and a Bill object is composed of Position objects. They're implemented as followed

class CashRegister
  def initialize
    @bills = []
  end

  def clone
    #?
  end
end

class Bill
  def initialize(nr)
    @nr = nr
    @positions = []
  end

  def clone
    #?
  end
end

class Position
  def initialize(product, price)
    @product = product
    @price = price
  end

  def clone
    #?
  end
end

How do I create methods that can deep copy the objects of these classes. The use of Marshal.load(Marshal.dump(an_obj)) is not allowed.

Edit: So far I've got this:

    class CashRegister
      def initialize
        @bills = []
      end

      def clone
        @bills.map { |bill| bill.clone}
      end
    end

    class Bill
      def initialize(nr)
        @nr = nr
        @positions = []
      end

      def clone
        cloned = super
        cloned.positions = @positions.map{ |pos| pos.clone}
        cloned
      end
    end

    class Position

      attr_reader :preis
      # this method is given
      def produkt
        @produkt.clone()
      end

      def initialize(product, price)
        @product = product
        @price = price
      end

      def clone
        cloned = super
        cloned.product
        cloned
      end
    end

The clone method in class Position seems to be ok (no compile error). But there is an error in the one in class Bill, it says "undefined method 'positions=', so the problem must be in the line cloned.positions = @positions.map{ |pos| pos.clone}. But I don't understand, can't we call cloned.positions like that?

Body:
It's just the instance variables you have to worry about.

class Position
  attr_accessor :product, :price
  def initialize(product, price)
    @product = product
    @price = price
  end
end

p1 = Position.new("lima beans", 2.31)
  #=> #<Position:0x000000027587b0 @product="lima beans", @price=2.31>
p2 = Position.new(p1.product, p1.price)
  #=> #<Position:0x0000000273dd48 @product="lima beans", @price=2.31>

We can confirm that p2 is a deep copy of p1.

p1.product = "lettuce"
p1.price   = 1.49

p1 #=> #<Position:0x0000000271f870 @product="lettuce", @price=1.49>
p2 #=> #<Position:0x000000026e9e00 @product="lima beans", @price=2.31>

p2.product = "spinach"
p2.price = 2.10

p1 #=> #<Position:0x0000000271f870 @product="lettuce", @price=1.49>
p2 #=> #<Position:0x000000026e9e00 @product="spinach", @price=2.1>

It's more complex if, for example, the class were defined as follows (where products is an array).

p1 = Position.new ["carrots", "onions"]
  #=> #<Position:0x000000025b8928 @products=["carrots", "onions"]>
p2 = Position.new p1.products
  #=> #<Position:0x000000025b0048 @products=["carrots", "onions"]>

p1.products << "beets"

p1 #=> #<Position:0x000000025b8928 @products=["carrots", "onions", "beets"]>
p2 #=> #<Position:0x000000025b0048 @products=["carrots", "onions", "beets"]>

p2 is not what we want. We would need to write

p1 = Position.new ["carrots", "onions"]
  #=> #<Position:0x00000002450900 @products=["carrots", "onions"]>
p2 = Position.new p1.products.dup
  #=> #<Position:0x0000000243aa88 @products=["carrots", "onions"]>

(note the .dup) so that

p1.products << "beets"
  #=> ["carrots", "onions", "beets"]

p1 #=> #<Position:0x00000002450900 @products=["carrots", "onions", "beets"]>
p2 #=> #<Position:0x0000000243aa88 @products=["carrots", "onions"]>

More generally, we need to make deep copies of the instance variables.


问:
Regex Full match
I'm trying to understand regular expressions:

I need to only match on text_01 and text_02 and filter out the tags.

```<code><span>text_01<b>text_02</b>
</code>```

I've tried to do it like:

```<code>(?<=<span>)(([^>]+)<b>)(.+?)(?=</b>)
</code>```

But it captures 3 groups and and the Full Match includes a tag.

```<code>text_01<b>text_02
</code>```

Could you give me advice on how I need to build a regex whose Full match contains only text and no tags?

答:
By using a non-capturing group you are able to exclude the middle  tag as a capture group, but you will never be able to get a full match without the tag included. It's not possible, a regular expression cannot skip a part while capturing. A match must be consecutive.

```<code>(?<=<span>)(.+?)(?:<b>)(.+?)(?=<\/b>)
</code>```

Full match        text_01text_02

Group 1.          text_01

Group 2.      text_02

Title: Regex Full match

Body:
I'm trying to understand regular expressions:

I need to only match on text_01 and text_02 and filter out the tags.

text_01text_02

I've tried to do it like:

(?<=)(([^>]+))(.+?)(?=)

But it captures 3 groups and and the Full Match includes a tag.

text_01text_02

Could you give me advice on how I need to build a regex whose Full match contains only text and no tags?

Body:
By using a non-capturing group you are able to exclude the middle <b> tag as a capture group, but you will never be able to get a full match without the tag included. It's not possible, a regular expression cannot skip a part while capturing. A match must be consecutive.

(?<=<span>)(.+?)(?:<b>)(.+?)(?=<\/b>)

Full match        text_01<b>text_02

Group 1.          text_01

Group 2.      text_02


问:
Big Query Analytic Functions Improve Query Performance
Pretty new to big query and hitting timeouts on a 100M point dataset.  I'm trying to find the points at which we reach a consistent series of values around 0 (stops) and points at which we consistently get above 0 (starts).

I saved the subquery that's being joined that determines the start file times to it's own dataset, but that didn't help. (seconds increments through multiple "files."

The part causing the problem is the initial aggregation of previous pts and next pts.

```<code>WITH test AS
 (SELECT 'A' as ACM, CAST('2017-01-01' AS DATE) as file_date, CAST('10:10:10' AS TIME) as file_time , 0.0 as value, 0.1 as seconds
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.4 )
SELECT
  acm,
  file_date,
  start_file_time,
  file_times,
  agg_sec as start_stop
FROM (
  SELECT
    acm,
    file_date,
    start_file_time,
    file_times,
    ARRAY_AGG(kind) OVER w AS agg_kind,
    ARRAY_AGG(seconds)  OVER w AS agg_sec
  FROM (
    SELECT
      acm,
      file_date,
      start_file_time,
      ARRAY(SELECT DISTINCT x FROM UNNEST(file_times) as x) AS file_times,
      seconds,
      CASE
      WHEN (ABS(prev_val) < 50 and ABS(next_val) >= 50 and next_avg >= 50 and prev_avg < 50 ) THEN 'start'
      WHEN (ABS(next_val) < 50 and ABS(prev_val) >= 50 and prev_avg >= 50 and next_avg < 50 ) THEN 'stop'
      END as kind,
      prev_val, next_val, prev_avg, next_avg
    FROM (
      SELECT
        s.acm as acm,
        s.file_date as file_date,
        s.start_file_time as start_file_time,
        seconds,
        value,
        ARRAY_AGG(s.file_time) OVER (PARTITION BY s.acm, s.file_date, s.start_file_time) as file_times,
        AVG(ABS(value)) OVER prev as prev_avg,
        NTH_VALUE(value, 2) OVER prev as prev_val,
        AVG(ABS(value)) OVER next as next_avg,
        NTH_VALUE(value, 2) OVER next as next_val
      FROM test v
      JOIN (
        SELECT
          acm,
          file_date,
          file_time,
          TIME_SUB(file_time, INTERVAL CAST(FLOOR(MIN(seconds)) AS INT64) SECOND) as start_file_time
        FROM test
        GROUP BY acm, file_date, file_time
      ) s ON s.acm = v.acm AND s.file_date = v.file_date AND s.file_time = v.file_time
      WINDOW prev AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS 2 PRECEDING), next AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
      )
    WHERE value = 0)
  WHERE kind IN ('start', 'stop')
  WINDOW w AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS 1 PRECEDING))
WHERE ARRAY_LENGTH(agg_kind) = 2 AND agg_kind[ORDINAL(1)] = 'start' AND agg_kind[ORDINAL(2)] = 'stop'
;
</code>```

答:
Hopefully this query gives you the results you are looking for and is capable of processing your dataset successfully:

```<code>SELECT
  * EXCEPT(file_data),
  ARRAY(SELECT STRUCT(seconds, kind) FROM UNNEST(file_data) WHERE kind IS NOT NULL) file_data
FROM(
  SELECT
    ACM,
    file_date,
    start_file_time,
    ARRAY(SELECT DISTINCT file_time FROM UNNEST(file_data)) file_times,
    ARRAY(SELECT STRUCT(seconds, IF(value = 0, (CASE WHEN ABS(NTH_VALUE(value, 2) OVER(prev)) < 50 AND ABS(NTH_VALUE(value, 2) OVER(next)) >= 50 AND AVG(ABS(value)) OVER(next) >= 50 and AVG(ABS(value)) OVER(prev) < 50 THEN 'start'
                                                    WHEN ABS(NTH_VALUE(value, 2) OVER(next)) < 50 AND ABS(NTH_VALUE(value, 2) OVER(prev)) >= 50 AND AVG(ABS(value)) OVER(prev) >= 50 and AVG(ABS(value)) OVER(next) < 50 THEN 'stop' END), NULL) as kind)
          FROM UNNEST(file_data)  WINDOW prev AS (ORDER BY seconds ROWS 2 PRECEDING), next as(ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)) file_data
  FROM(
    SELECT
      ACM,
      file_date,
      TIME_SUB(file_time, INTERVAL CAST(FLOOR(seconds) AS INT64) SECOND) AS start_file_time,
      ARRAY_AGG(STRUCT(file_time, value, seconds)) file_data
    FROM test
    GROUP BY ACM, file_date, start_file_time
   )
 )
</code>```

Its results is exactly what you described as "start" and "stop" in your test data.

A few notes to make:

I avoided the expensive JOIN operation.

Made use of ARRAYs and STRUCTs as much as possible which increases not only efficiency on storage but also increases query performance due processing of only desired data, i.e, no need to handle duplicated data.

Just 2 WINDOW clauses each used inside of correspondent ARRAY structure which boosts performance. Notice this is possible because I aggregated everything in ARRAYs of STRUCTs so there's no need for more complex windowing clauses as data is already "sorted out".

There's no data duplication in this query.

Notice the results are in a slight different structure now, I'd recommend using this new one as it's more effective on data storage and further processing.

Let me know if this works for you.

Body:
Pretty new to big query and hitting timeouts on a 100M point dataset.  I'm trying to find the points at which we reach a consistent series of values around 0 (stops) and points at which we consistently get above 0 (starts).

I saved the subquery that's being joined that determines the start file times to it's own dataset, but that didn't help. (seconds increments through multiple "files."

The part causing the problem is the initial aggregation of previous pts and next pts.

WITH test AS
 (SELECT 'A' as ACM, CAST('2017-01-01' AS DATE) as file_date, CAST('10:10:10' AS TIME) as file_time , 0.0 as value, 0.1 as seconds
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.4 )
SELECT
  acm,
  file_date,
  start_file_time,
  file_times,
  agg_sec as start_stop
FROM (
  SELECT
    acm,
    file_date,
    start_file_time,
    file_times,
    ARRAY_AGG(kind) OVER w AS agg_kind,
    ARRAY_AGG(seconds)  OVER w AS agg_sec
  FROM (
    SELECT
      acm,
      file_date,
      start_file_time,
      ARRAY(SELECT DISTINCT x FROM UNNEST(file_times) as x) AS file_times,
      seconds,
      CASE
      WHEN (ABS(prev_val) < 50 and ABS(next_val) >= 50 and next_avg >= 50 and prev_avg < 50 ) THEN 'start'
      WHEN (ABS(next_val) < 50 and ABS(prev_val) >= 50 and prev_avg >= 50 and next_avg < 50 ) THEN 'stop'
      END as kind,
      prev_val, next_val, prev_avg, next_avg
    FROM (
      SELECT
        s.acm as acm,
        s.file_date as file_date,
        s.start_file_time as start_file_time,
        seconds,
        value,
        ARRAY_AGG(s.file_time) OVER (PARTITION BY s.acm, s.file_date, s.start_file_time) as file_times,
        AVG(ABS(value)) OVER prev as prev_avg,
        NTH_VALUE(value, 2) OVER prev as prev_val,
        AVG(ABS(value)) OVER next as next_avg,
        NTH_VALUE(value, 2) OVER next as next_val
      FROM test v
      JOIN (
        SELECT
          acm,
          file_date,
          file_time,
          TIME_SUB(file_time, INTERVAL CAST(FLOOR(MIN(seconds)) AS INT64) SECOND) as start_file_time
        FROM test
        GROUP BY acm, file_date, file_time
      ) s ON s.acm = v.acm AND s.file_date = v.file_date AND s.file_time = v.file_time
      WINDOW prev AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS 2 PRECEDING), next AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
      )
    WHERE value = 0)
  WHERE kind IN ('start', 'stop')
  WINDOW w AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS 1 PRECEDING))
WHERE ARRAY_LENGTH(agg_kind) = 2 AND agg_kind[ORDINAL(1)] = 'start' AND agg_kind[ORDINAL(2)] = 'stop'
;

Body:
Hopefully this query gives you the results you are looking for and is capable of processing your dataset successfully:

SELECT
  * EXCEPT(file_data),
  ARRAY(SELECT STRUCT(seconds, kind) FROM UNNEST(file_data) WHERE kind IS NOT NULL) file_data
FROM(
  SELECT
    ACM,
    file_date,
    start_file_time,
    ARRAY(SELECT DISTINCT file_time FROM UNNEST(file_data)) file_times,
    ARRAY(SELECT STRUCT(seconds, IF(value = 0, (CASE WHEN ABS(NTH_VALUE(value, 2) OVER(prev)) < 50 AND ABS(NTH_VALUE(value, 2) OVER(next)) >= 50 AND AVG(ABS(value)) OVER(next) >= 50 and AVG(ABS(value)) OVER(prev) < 50 THEN 'start'
                                                    WHEN ABS(NTH_VALUE(value, 2) OVER(next)) < 50 AND ABS(NTH_VALUE(value, 2) OVER(prev)) >= 50 AND AVG(ABS(value)) OVER(prev) >= 50 and AVG(ABS(value)) OVER(next) < 50 THEN 'stop' END), NULL) as kind)
          FROM UNNEST(file_data)  WINDOW prev AS (ORDER BY seconds ROWS 2 PRECEDING), next as(ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)) file_data
  FROM(
    SELECT
      ACM,
      file_date,
      TIME_SUB(file_time, INTERVAL CAST(FLOOR(seconds) AS INT64) SECOND) AS start_file_time,
      ARRAY_AGG(STRUCT(file_time, value, seconds)) file_data
    FROM test
    GROUP BY ACM, file_date, start_file_time
   )
 )

Its results is exactly what you described as "start" and "stop" in your test data.

A few notes to make:

I avoided the expensive JOIN operation.

Made use of ARRAYs and STRUCTs as much as possible which increases not only efficiency on storage but also increases query performance due processing of only desired data, i.e, no need to handle duplicated data.

Just 2 WINDOW clauses each used inside of correspondent ARRAY structure which boosts performance. Notice this is possible because I aggregated everything in ARRAYs of STRUCTs so there's no need for more complex windowing clauses as data is already "sorted out".

There's no data duplication in this query.

Notice the results are in a slight different structure now, I'd recommend using this new one as it's more effective on data storage and further processing.

Let me know if this works for you.


问:
different results of IN Condition
Don't quite understand IN statement. First variant works fine:

```<code>select manufacturers.id
from manufacturers
where manufacturers.id in (select manufacturerId
                           from pcs group by manufacturerId
                           having count(manufacturerId) > 1)
</code>```

But when I make subquery a procedure:

```<code>CREATE PROCEDURE [dbo].Get_manufacturers @productType varchar(50)
as
begin
declare @query varchar(500)
set @query='select manufacturerId from ' +  QuoteName(@productType) + '
               group by manufacturerId having count(manufacturerId) > 1'
declare @t table (manufacturerId int)
insert into @t exec(@query)
select manufacturerId from @t;
end

select manufacturers.id
from manufacturers
where manufacturers.id in (Get_manufacturers 'pcs')
</code>```

I get an error: Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pcs'

Get_manufacturers 'pcs' works properly. Where am I wrong?

答:
Don't quite understand IN statement

...

Get_manufacturers 'pcs' works properly - it returns a table

You misunderstand both stored procedures and IN condition.

From IN (Transact-SQL):

```<code>test_expression [ NOT ] IN
    ( subquery | expression [ ,...n ]
    )
</code>```

What the stored procedure returns is not a subquery, neither it's an expression.
Here is a link to understand what subquery is Using a Subquery in a T-SQL Statement

A subquery is a SELECT statement that is nested within another T-SQL
statement

So stored procedure is not a subquery, it's just not a SELECT statement.
But even when you say that stored procedures returns a table it's wrong: you can JOIN a table to another table but you cannot join the result of stored procedure.
And even if you "see" the result set returned by a procedure as a "table" it's not a table.

Title: different results of IN Condition

Body:
Don't quite understand IN statement. First variant works fine:

select manufacturers.id
from manufacturers
where manufacturers.id in (select manufacturerId
                           from pcs group by manufacturerId
                           having count(manufacturerId) > 1)

But when I make subquery a procedure:

CREATE PROCEDURE [dbo].Get_manufacturers @productType varchar(50)
as
begin
declare @query varchar(500)
set @query='select manufacturerId from ' +  QuoteName(@productType) + '
               group by manufacturerId having count(manufacturerId) > 1'
declare @t table (manufacturerId int)
insert into @t exec(@query)
select manufacturerId from @t;
end

select manufacturers.id
from manufacturers
where manufacturers.id in (Get_manufacturers 'pcs')

I get an error: Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pcs'

Get_manufacturers 'pcs' works properly. Where am I wrong?

Body:
Don't quite understand IN statement

...

Get_manufacturers 'pcs' works properly - it returns a table

You misunderstand both stored procedures and IN condition.

From IN (Transact-SQL):

test_expression [ NOT ] IN
    ( subquery | expression [ ,...n ]
    )

What the stored procedure returns is not a subquery, neither it's an expression.
Here is a link to understand what subquery is Using a Subquery in a T-SQL Statement

A subquery is a SELECT statement that is nested within another T-SQL
statement

So stored procedure is not a subquery, it's just not a SELECT statement.
But even when you say that stored procedures returns a table it's wrong: you can JOIN a table to another table but you cannot join the result of stored procedure.
And even if you "see" the result set returned by a procedure as a "table" it's not a table.


问:
Jenkins android build failing with the message: FATAL: The Gradle wrapper has not been found in these directories
When I try building android project, build fails with the following msg:

```<code>Started by user admin
Building in workspace /Users/Shared/Jenkins/Home/workspace/stable-dev
[Gradle] - Launching build.

FATAL: The Gradle wrapper has not been found in these directories:
/Users/admin/Downloads/android_stable_dev,
/Users/Shared/Jenkins/Home/workspace/stable-dev

Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE
</code>```

Configurations I used:

Use Gradle Wrapper

build File: /Users/admin/Downloads/android_stable_dev/build.gradle

I tried filling /Users/admin/Downloads/android_stable_dev/gradlew, /Users/admin/Downloads/android_stable_dev/gradle/wrapper/, /Users/admin/Downloads/android_stable_dev/gradle/ etc. in the Wrapper location field in the configuration. Still didn't work (All those files are there).

I'm using jenkins-2.47.pkg

答:
You only have to provide the location of parent folder of the gradlew and build.gradle and not the files. So in your case

```<code>Root Build script: /Users/admin/Downloads/android_stable_dev
Wrapper Location: /Users/admin/Downloads/android_stable_dev
</code>```

It is mentioned in the help (click ? next to Wrapper Location and Root Build script options) but I too found this out after carefully reading it multiple times

Body:
When I try building android project, build fails with the following msg:

Started by user admin
Building in workspace /Users/Shared/Jenkins/Home/workspace/stable-dev
[Gradle] - Launching build.

FATAL: The Gradle wrapper has not been found in these directories:
/Users/admin/Downloads/android_stable_dev,
/Users/Shared/Jenkins/Home/workspace/stable-dev

Build step 'Invoke Gradle script' marked build as failure
Finished: FAILURE

Configurations I used:

Use Gradle Wrapper

build File: /Users/admin/Downloads/android_stable_dev/build.gradle

I tried filling /Users/admin/Downloads/android_stable_dev/gradlew, /Users/admin/Downloads/android_stable_dev/gradle/wrapper/, /Users/admin/Downloads/android_stable_dev/gradle/ etc. in the Wrapper location field in the configuration. Still didn't work (All those files are there).

I'm using jenkins-2.47.pkg

Body:
You only have to provide the location of parent folder of the gradlew and build.gradle and not the files. So in your case

Root Build script: /Users/admin/Downloads/android_stable_dev
Wrapper Location: /Users/admin/Downloads/android_stable_dev

It is mentioned in the help (click ? next to Wrapper Location and Root Build script options) but I too found this out after carefully reading it multiple times


问:
Neo4j Start Error: /var/run/neo4j/neo4j.pid: No such file or directory
After upgrading from Neo4j 3.0 to 3.1 (and subsequently 3.2), I get the following error after running sudo neo4j start:

```<code>/usr/share/neo4j/bin/neo4j: line 411: /var/run/neo4j/neo4j.pid: No such file or directory
</code>```

Nonetheless, Neo4j is actually running after running this command.. However, I cannot then stop Neo4j afterwards with sudo neo4j stop, as there is no PID.

How can I fix this?

Notes:

I upgraded using sudo apt upgrade

It is possible to get around this issue by doing a sudo mkdir /var/run/neo4j beforehand, but was hoping there might be a more effective solution.

答:
When using the installation package you should not start/stop with the neo4j script, but use the installed service. Depending on your Ubuntu version that is

```<code>sudo service neo4j {start|stop|restart}
</code>```

or

```<code>sudo systemctl {start|stop|restart} neo4j
</code>```

Check http://neo4j.com/docs/operations-manual/current/installation/linux/debian/ and http://neo4j.com/docs/operations-manual/current/installation/linux/systemd/ for more information.

Hope this helps,
Tom

P.S. Note that starting/stopping without using the service may have started Neo4j with the wrong user (root instead of neo4j) and files may therefore have the wrong ownership now !

Body:
After upgrading from Neo4j 3.0 to 3.1 (and subsequently 3.2), I get the following error after running sudo neo4j start:

/usr/share/neo4j/bin/neo4j: line 411: /var/run/neo4j/neo4j.pid: No such file or directory

Nonetheless, Neo4j is actually running after running this command.. However, I cannot then stop Neo4j afterwards with sudo neo4j stop, as there is no PID.

How can I fix this?

Notes:

I upgraded using sudo apt upgrade

It is possible to get around this issue by doing a sudo mkdir /var/run/neo4j beforehand, but was hoping there might be a more effective solution.

Body:
When using the installation package you should not start/stop with the neo4j script, but use the installed service. Depending on your Ubuntu version that is

sudo service neo4j {start|stop|restart}

or

sudo systemctl {start|stop|restart} neo4j

Check http://neo4j.com/docs/operations-manual/current/installation/linux/debian/ and http://neo4j.com/docs/operations-manual/current/installation/linux/systemd/ for more information.

Hope this helps,
Tom

P.S. Note that starting/stopping without using the service may have started Neo4j with the wrong user (root instead of neo4j) and files may therefore have the wrong ownership now !


问:
Java Data Structure
I'm looking for a data structure that will act like a Queue so that I can hava First In First Out behaviour, but ideally I would also be able to see if an element exists in that Queue in constant time as you can do with a HashMap, rather than the linear time that you get with a LinkedList.

I thought a LinkedHashMap might do the job, but although I could make an iterator and just take and then remove the first element of the iteration to produce a sort of poll() method, I'm wondering if there is a better way.

Many thanks in advance

答: I don't know if there is something out there but you could easily create a compound object that consists of a Queue and a HashSet. All modifying operations need to occur on both collections at the same time to keep them in sync. You can then use the set for lookup which should be very fast.

Title: Java Data Structure


答:
Parsing HTML with regular expressions can get very complicated. In general it is not advised practice and better to use a parser for this (some library in whatever language you are using).

But for cases where you are sure the text content does not have < nor >, and these < and > are not nested, you could use this one:

[^<>]*(?=<[^<>]*>)

This only matches text that is followed by a pair of < and >.

If it is enough to test that text is followed by <, it can be simply:

[^<>]*(?=<)

Title: Regex Full match