问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
The compiler is inferring that in the case of the comparison operators, the null is being implicitly typed as int?.

```<code>Console.WriteLine(null == null); // true
Console.WriteLine(null != null); // false
Console.WriteLine(null < null);  // false*
Console.WriteLine(null <= null); // false*
Console.WriteLine(null > null);  // false*
Console.WriteLine(null >= null); // false*
</code>```

Visual Studio offers a warning:

*Comparing with null of type 'int?' always produces 'false'

This can be verified with the following code:

```<code>static void PrintTypes(LambdaExpression expr)
{
    Console.WriteLine(expr);
    ConstantExpression cexpr = expr.Body as ConstantExpression;
    if (cexpr != null)
    {
        Console.WriteLine("\t{0}", cexpr.Type);
        return;
    }
    BinaryExpression bexpr = expr.Body as BinaryExpression;
    if (bexpr != null)
    {
        Console.WriteLine("\t{0}", bexpr.Left.Type);
        Console.WriteLine("\t{0}", bexpr.Right.Type);
        return;
    }
    return;
}
PrintTypes((Expression<Func<bool>>)(() => null == null)); // constant folded directly to bool
PrintTypes((Expression<Func<bool>>)(() => null != null)); // constant folded directly to bool
PrintTypes((Expression<Func<bool>>)(() => null < null));
PrintTypes((Expression<Func<bool>>)(() => null <= null));
PrintTypes((Expression<Func<bool>>)(() => null > null));
PrintTypes((Expression<Func<bool>>)(() => null >= null));
</code>```

Outputs:

```<code>() => True
        System.Boolean
() => False
        System.Boolean
() => (null < null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null <= null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null > null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null >= null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
</code>```

Why?

This seems logical to me.  First of all, here's relevant sections of the C# 4.0 Spec.

The null literal §2.4.4.6:

The  null-literal can be implicitly converted to a reference type or nullable type.

Binary numeric promotions §7.3.6.2:

Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:

• If either operand is of type decimal, the other operand is converted to type decimal, or a binding-time error occurs if the other operand is of type float or double.

  •   Otherwise, if either operand is of type double, the other operand is converted to type double.

  •   Otherwise, if either operand is of type float, the other operand is converted to type float.

  •   Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a binding-time error occurs if the other operand is of type sbyte, short, int, or long.

  •   Otherwise, if either operand is of type long, the other operand is converted to type long.

  •   Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long.

  •   Otherwise, if either operand is of type uint, the other operand is converted to type uint.

  •   Otherwise, both operands are converted to type int.

Lifted operators §7.3.7:

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:

• For the relational operators

  <  >  <=  >=

  a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

The null-literal alone doesn't really have a type.  It is inferred by what it is assigned to.  No assignment takes place here however.  Only considering built-in types with language support (ones with keywords), object or any nullable would be a good candidate.  However object isn't comparable so it gets ruled out.  That leaves nullable types good candidates.  But which type?  Since neither left nor right operands has a specified type, they are converted to a (nullable) int by default.  Since both nullable values are null, it returns false.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

Body:
The compiler is inferring that in the case of the comparison operators, the null is being implicitly typed as int?.

Console.WriteLine(null == null); // true
Console.WriteLine(null != null); // false
Console.WriteLine(null < null);  // false*
Console.WriteLine(null <= null); // false*
Console.WriteLine(null > null);  // false*
Console.WriteLine(null >= null); // false*

Visual Studio offers a warning:

*Comparing with null of type 'int?' always produces 'false'

This can be verified with the following code:

static void PrintTypes(LambdaExpression expr)
{
    Console.WriteLine(expr);
    ConstantExpression cexpr = expr.Body as ConstantExpression;
    if (cexpr != null)
    {
        Console.WriteLine("\t{0}", cexpr.Type);
        return;
    }
    BinaryExpression bexpr = expr.Body as BinaryExpression;
    if (bexpr != null)
    {
        Console.WriteLine("\t{0}", bexpr.Left.Type);
        Console.WriteLine("\t{0}", bexpr.Right.Type);
        return;
    }
    return;
}
PrintTypes((Expression<Func<bool>>)(() => null == null)); // constant folded directly to bool
PrintTypes((Expression<Func<bool>>)(() => null != null)); // constant folded directly to bool
PrintTypes((Expression<Func<bool>>)(() => null < null));
PrintTypes((Expression<Func<bool>>)(() => null <= null));
PrintTypes((Expression<Func<bool>>)(() => null > null));
PrintTypes((Expression<Func<bool>>)(() => null >= null));

Outputs:

() => True
        System.Boolean
() => False
        System.Boolean
() => (null < null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null <= null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null > null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]
() => (null >= null)
        System.Nullable`1[System.Int32]
        System.Nullable`1[System.Int32]

Why?

This seems logical to me.  First of all, here's relevant sections of the C# 4.0 Spec.

The null literal §2.4.4.6:

The  null-literal can be implicitly converted to a reference type or nullable type.

Binary numeric promotions §7.3.6.2:

Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:

• If either operand is of type decimal, the other operand is converted to type decimal, or a binding-time error occurs if the other operand is of type float or double.

  •   Otherwise, if either operand is of type double, the other operand is converted to type double.

  •   Otherwise, if either operand is of type float, the other operand is converted to type float.

  •   Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a binding-time error occurs if the other operand is of type sbyte, short, int, or long.

  •   Otherwise, if either operand is of type long, the other operand is converted to type long.

  •   Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long.

  •   Otherwise, if either operand is of type uint, the other operand is converted to type uint.

  •   Otherwise, both operands are converted to type int.

Lifted operators §7.3.7:

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:

• For the relational operators

  <  >  <=  >=

  a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

The null-literal alone doesn't really have a type.  It is inferred by what it is assigned to.  No assignment takes place here however.  Only considering built-in types with language support (ones with keywords), object or any nullable would be a good candidate.  However object isn't comparable so it gets ruled out.  That leaves nullable types good candidates.  But which type?  Since neither left nor right operands has a specified type, they are converted to a (nullable) int by default.  Since both nullable values are null, it returns false.


来源: stackexchange

问:
python binary search tree size
im trying to implement a binary search tree and im having trouble with my size() method, which counts the number of nodes in the tree.

```<code>class BSTNode:
def __init__(self, item):

    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None
</code>```

this is what my size funtion looks like:

```<code>def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += 1 + self._leftchild.size()
        if self._rightchild != None:
            size += 1 + self._rightchild.size()
    return size
</code>```

it overcounts the number of nodes that are actually in the tree and i dont know why, maybe because its recursive but im not  sure.

答:
Replace

```<code>size += 1 + self._leftchild.size()
</code>```

With

```<code>size += self._leftchild.size()
</code>```

That extra 1 is the reason for overcounting. And similarly for right child.

ContentLicense: CC BY-SA 3.0

Title: python binary search tree size

Body:
im trying to implement a binary search tree and im having trouble with my size() method, which counts the number of nodes in the tree.

class BSTNode:
def __init__(self, item):

    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None

this is what my size funtion looks like:

def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += 1 + self._leftchild.size()
        if self._rightchild != None:
            size += 1 + self._rightchild.size()
    return size

it overcounts the number of nodes that are actually in the tree and i dont know why, maybe because its recursive but im not  sure.

Body:
Replace

size += 1 + self._leftchild.size()

With

size += self._leftchild.size()

That extra 1 is the reason for overcounting. And similarly for right child.


问:
jQuery toggle text and image not working
I am creating a dropdown accordion menu with jQuery.
I have worked on a few versions before and my script can work well before I add the image toggle.

But after I have added the image toggle script, the whole toggle is not functioning well.

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).text() == "Show") {
        $(this).text("Hide");
      } else {
        $(this).text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}</code>```

    Show

    XXXXXXXXXX Content XXXXXXXXXX

```
</div>
</div>
</p>

<p>So what I want to do is that: Originally the content will be hidden, with a title "Show" with arrow down icon is shown. If I click on the title, the hidden content will be shown and the title will change to "Hide" and with arrow up icon. </p>

<p>Originally I can achieve the toggle with those text, however, after I have tried to add the image toggle script, it is not working.</p>

```$(this).find('i').toggleClass('arrow-down arrow-up');
```

Anyone can share with me your solution/opinion here? Thank you so much for your time of reading my question!

答:
```<code>$(this).closet("div")
</code>```

Should be:

```<code>$(this).closest("div")
</code>```

Body:
I am creating a dropdown accordion menu with jQuery.
I have worked on a few versions before and my script can work well before I add the image toggle.

But after I have added the image toggle script, the whole toggle is not functioning well.

$(function() {
  $('.showmore').click(
    function() {
      $(this).closest("div").next(".dropdown").toggle();
      $(this).find('i').toggleClass('arrow-down arrow-up');
      if ($(this).text() == "Show") {
        $(this).text("Hide");
      } else {
        $(this).text("Show");
      }
      $(this).closest("div").next(".dropdown").toggleClass('selected');
    }
  )
})

.title {
  background-color: #CCCCCC;
}

.sprite {
  background-image: url(https://image.ibb.co/bHTF8R/pinkarrow.png);
  background-repeat: no-repeat;
  display: block;
}

.arrow-down {
  width: 9px;
  height: 6px;
  background-position: -9px 0;
}

.arrow-up {
  width: 9px;
  height: 6px;
  background-position: 0 0;
}

.arrow-down,
.arrow-up {
  display: inline-block;
  padding-left: 5px;
}

.dropdown {
  display: none;
}

.selected {
  border: 4px solid #CCCCCC;
}

    Show

    XXXXXXXXXX Content XXXXXXXXXX

So what I want to do is that: Originally the content will be hidden, with a title "Show" with arrow down icon is shown. If I click on the title, the hidden content will be shown and the title will change to "Hide" and with arrow up icon.

Originally I can achieve the toggle with those text, however, after I have tried to add the image toggle script, it is not working.

$(this).find('i').toggleClass('arrow-down arrow-up');

Anyone can share with me your solution/opinion here? Thank you so much for your time of reading my question!

Body:
$(this).closet("div")

Should be:

$(this).closest("div")


问:
Browse file in AngularJS + TypeScript on button click
I have user.component.html and user.component.ts
All examples I found were in html this way <input type="file" />
I don't want to use this style. I have in my html file:

```<code><button type="button" class="btn" (click)="openPicture()" Browse </button>
</code>```

Below is the function on ts file:

```<code>  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}
</code>```

I have found an example on stackoverflow with angular/material but I dont have this module. Is there any other alternative way, without installing any extra package to solve this?

答:
You could try good old hidden input in label:

```<code><label class="btn">
    Browse <input type="file" style="display: none;" (change)="handleChange($event)">
</label>
</code>```

handleChange implementation would have to consume event:

```<code>handleChange(event) {
    // consume event.target.files[0] which has File type
}
</code>```

rest about File can be found on MDN

Body:
I have user.component.html and user.component.ts
All examples I found were in html this way <input type="file" />
I don't want to use this style. I have in my html file:

<button type="button" class="btn" (click)="openPicture()" Browse </button>

Below is the function on ts file:

  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}

I have found an example on stackoverflow with angular/material but I dont have this module. Is there any other alternative way, without installing any extra package to solve this?

Body:
You could try good old hidden input in label:

<label class="btn">
    Browse <input type="file" style="display: none;" (change)="handleChange($event)">
</label>

handleChange implementation would have to consume event:

handleChange(event) {
    // consume event.target.files[0] which has File type
}

rest about File can be found on MDN


问:
JQuery to add divs to list of images
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

```<code><div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
</code>```

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

答:
Assuming those images are in a container with the ID container, you could do this:

Example: http://jsfiddle.net/c2nQH/

```<code>var imgs = $('#container > img');

imgs.each(function(i) {
          // If we're on a multiple of 3...
    if (i % 3 == 0) {
              // ...take a slice of it and the next two, and wrap them.
        imgs.slice(i, i + 3).wrapAll('<div></div>');
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: JQuery to add divs to list of images

Body:
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

Body:
Assuming those images are in a container with the ID container, you could do this:

Example: http://jsfiddle.net/c2nQH/

var imgs = $('#container > img');

imgs.each(function(i) {
          // If we're on a multiple of 3...
    if (i % 3 == 0) {
              // ...take a slice of it and the next two, and wrap them.
        imgs.slice(i, i + 3).wrapAll('<div></div>');
    }
});


问:
How to disable mouseout events triggered by child elements?
Let me describe the problem in details:

I want to show an absolute positioned div when hovering over an element. That's really simple with jQuery and works just fine. But when the mouse goes over one of the child elements, it triggers the mouseout event of the containing div. How do I keep javascript from triggering the mouseout event of the containing element when hovering a child element.

What's the best and shortest way to do that with jQuery?

Here is a simplified example to illustrate what I mean:

Html:

```<code><a>Hover Me</a>
<div>
  <input>Test</input>
  <select>
    <option>Option 1</option>
    <option>Option 2</option>
  </select>
</div>
</code>```

Javascript/jQuery:

```<code>$('a').hover( function() { $(this).next().show() }
              function() { $(this).next().hide() } );
</code>```

答: I resolved this problem by adding pointer-events: none; on my child elements css

OwnerDisplayName: Sander

Body:
Let me describe the problem in details:

I want to show an absolute positioned div when hovering over an element. That's really simple with jQuery and works just fine. But when the mouse goes over one of the child elements, it triggers the mouseout event of the containing div. How do I keep javascript from triggering the mouseout event of the containing element when hovering a child element.

What's the best and shortest way to do that with jQuery?

Here is a simplified example to illustrate what I mean:

Html:

Hover Me

  <input>Test</input>
  <select>
    <option>Option 1</option>
    <option>Option 2</option>
  </select>

Javascript/jQuery:

$('a').hover( function() { $(this).next().show() }
              function() { $(this).next().hide() } );

LastEditorDisplayName: Sander


问:
How to recover Fabric Account from App ID
Unfortunately, everyone in  this team is new to this legacy project and no one knows credential for the fabric account login, if I know the app id how can I recover the login </p>

答:
Thanks Sam! This is only possible through Fabric support on a case by case basis. They will require some security steps to make sure you control the app.

Do you have control of the web domain that the registered emails were at? Email the bundle ID or package name to support@fabric.io and we'll work with you to see what we can do.

Todd - Fabric team


问:
C++ STL Concurrent update to values in fixed size map - Is it safe?
I have a C++ STL map

std::map < std::thread_id, int > some_map which has a fixed size of num_threads and all locations are initialised to 0 in the beginning.

```<code>some_map[id1] = 0;
some_map[id2] = 0;
...
</code>```

Question: Is it safe if each thread modifies the container as

some_map[std::this_thread::get_id()] = rand() in each of the thread?

答:
As mentioned here, STL containers are almost uniformly const thread-safe, such that calling any const-qualified member functions will not result in a data race.  Since std::map::operator[] is not a const-qualified, thread-safety is not guaranteed.

Even if you ensure that you will not be calling thread-unsafe functions (i.e. insert, erase), unless you understand the underlying implementation for std::map, which can depend on the library (GCC, Clang, etc.), be wary of calling std::map::operator[] from multiple threads on a shared object.

If you need the map-like behavior, consider using a container that is specifically designed to be thread safe (e.g. Intel's TBB concurrent_hash_map).

Body:
I have a C++ STL map

std::map < std::thread_id, int > some_map which has a fixed size of num_threads and all locations are initialised to 0 in the beginning.

some_map[id1] = 0;
some_map[id2] = 0;
...

Question: Is it safe if each thread modifies the container as

some_map[std::this_thread::get_id()] = rand() in each of the thread?


答:
Because of browser security features, you're actually required to use the input tag to access the filesystem. What you can do, though, is hide the input element and access it from the rest of your code and markup.

Take a look at this related answer to get an idea of what you can do. Otherwise, here's a simple example of how it could work:

```<code><input type="file" style="display: none" #file/>
<button type="button" class="btn" (click)="file.click()" Browse </button
</code>```

Title: Browse file in AngularJS + TypeScript on button click

Body:
Because of browser security features, you're actually required to use the input tag to access the filesystem. What you can do, though, is hide the input element and access it from the rest of your code and markup.

Take a look at this related answer to get an idea of what you can do. Otherwise, here's a simple example of how it could work:

<input type="file" style="display: none" #file/>
<button type="button" class="btn" (click)="file.click()" Browse </button


问:
CSS Selector to match input not contained in a div with specific class?
I have this situation

```<code><div class="hidden">
  <input name="bar-foo" value="test">
</div>
<div class="hidden">
  <input name="bar-foo-baz" value="test2">
</div>
<div class="nothidden">
  <input name="bar-foo" value="test3"> <!-- should be selected -->
</div>
<div class="nothidden">
  <input name="foo-bar-baz" value="test4"> <!-- should be selected -->
</div>
</code>```

I need to match inputs containing word foo and bar, not contained in a div which class is 'hidden'.

```<code>input[name*="foo"][name*="bar"]
</code>```

matches all the four inputs.

```<code>:not(.hidden) input[name*="foo"][name*="bar"]
</code>```

in my opinion, should match inputs not contained in something with class '.hidden', but it doesn't. How do I achieve this result?

Here is it a jsfiddle
https://jsfiddle.net/8dLbz5ws/1/

答:
This worked for me.

https://jsfiddle.net/1dd2a3sw/

```<code>div:not(.hidden) input[name*="foo"][name*="bar"] {
  color:red;
}
</code>```

Body:
I have this situation

  <input name="bar-foo" value="test">

  <input name="bar-foo-baz" value="test2">

  <input name="bar-foo" value="test3">

  <input name="foo-bar-baz" value="test4">

I need to match inputs containing word foo and bar, not contained in a div which class is 'hidden'.

input[name*="foo"][name*="bar"]

matches all the four inputs.

:not(.hidden) input[name*="foo"][name*="bar"]

in my opinion, should match inputs not contained in something with class '.hidden', but it doesn't. How do I achieve this result?

Here is it a jsfiddle
https://jsfiddle.net/8dLbz5ws/1/

Body:
This worked for me.

https://jsfiddle.net/1dd2a3sw/

div:not(.hidden) input[name*="foo"][name*="bar"] {
  color:red;
}


问:
Error print user.default swift 3
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

```<code>func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}
</code>```

Second view:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }
</code>```

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance

答:
Here is my solution

For your line of code:

```<code>Constants.lbd.set(id_usuario, forKey: "id_usuario")
</code>```

User this:

```<code>   UserDefaults.standard.set(id_usuario,forKey:"id_usuario") // Use Integer to store this value
</code>```

For your line of code in Second VC:

```<code> let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
</code>```

User this:

```<code>  let id_usuario =   UserDefaults.standard.integer(forKey:"id_usuario") // Use Integer to store this value
</code>```

This will solve your problem

Title: Error print user.default swift 3

Body:
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}

Second view:

override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance

Body:
Here is my solution

For your line of code:

Constants.lbd.set(id_usuario, forKey: "id_usuario")

User this:

   UserDefaults.standard.set(id_usuario,forKey:"id_usuario") // Use Integer to store this value

For your line of code in Second VC:

 let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int

User this:

  let id_usuario =   UserDefaults.standard.integer(forKey:"id_usuario") // Use Integer to store this value

This will solve your problem


问:
GET friendships/show with rtweet
I tried to find a way to use the rtweet package to perform a request to GET friendships/show from the Twitter REST API, in order to analyse the relationship between two users. However, I could not make it work (I did find lookup_friendships(), but it does not do what I want). Is it possible to do that with rtweet, and if so, how?

答: You might be able to use the get_friends() or get_followers() functions.

Title: GET friendships/show with rtweet


问:
An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.3'
I get an error while I install new package in Visual studio I have this error

```<code> An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.2'
</code>```

I had update it from Newtonsoft.Json.10.0.2 to Newtonsoft.Json.10.0.3 But I have the same error

答: I try to upgrade my nuget and it work with Me</p>

Body:
I get an error while I install new package in Visual studio I have this error

 An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.2'

I had update it from Newtonsoft.Json.10.0.2 to Newtonsoft.Json.10.0.3 But I have the same error


问:
Angular material tab scroll contents are not working
I am working with angularjs material design but I got stuck at one point that md-scroll for up and down is not working. However, for left and right side it is working fine. Tabs have a table view where scroll up and down is supposed to work but they are not responding. Whenever I am scrolling it up or down is it going on left direction.

This is the CSS I have used for scrolling left and right.

```<code>md-tabs-content-wrapper, [md-swipe-left], [md-swipe-right] {
  touch-action: none;
  touch-action: pan-y;
}
</code>```

答:
Maybe you set styles for the wrong tag?

For example, I see touch-action: none style on <md-tab-content> tag on my project. And if I just set touch-action: auto !important; it works. It doesn't work without !important because of the style is set through the style attribute.

Body:
I am working with angularjs material design but I got stuck at one point that md-scroll for up and down is not working. However, for left and right side it is working fine. Tabs have a table view where scroll up and down is supposed to work but they are not responding. Whenever I am scrolling it up or down is it going on left direction.

This is the CSS I have used for scrolling left and right.

md-tabs-content-wrapper, [md-swipe-left], [md-swipe-right] {
  touch-action: none;
  touch-action: pan-y;
}


答:
Your second selector :not(.hidden) input[name*="foo"][name*="bar"] matches all the inputs because they are all contained in some element that doesn't have the hidden class (for example the body or another parent div).

You can fix the problem by being more specific:

```<code>:not(.hidden) > input[name*="foo"][name*="bar"]
</code>```

This will filter out those with .hidden direct parents.

EDIT

Some commenters would like to know how to select all the inputs in question that are not contained in any .hidden element (not necessarily a direct parent). This is a tougher problem. The following:

```<code>input[name*="foo"][name*="bar"]:not(.hidden input)
</code>```

does not seem to work, I think because :not only permits relatively simple selectors inside. The only way I can think of is to update all the chosen inputs and then un-update them when within any .hidden elements:

```<code>input[name*="foo"][name*="bar"] { color: red; }
.hidden input[name*="foo"][name*="bar"] { color: black; }
</code>```

This will only work if the default settings (ie color: black) is uniform I'm afraid.

Title: CSS Selector to match input not contained in a div with specific class?

Body:
Your second selector :not(.hidden) input[name*="foo"][name*="bar"] matches all the inputs because they are all contained in some element that doesn't have the hidden class (for example the body or another parent div).

You can fix the problem by being more specific:

:not(.hidden) > input[name*="foo"][name*="bar"]

This will filter out those with .hidden direct parents.

EDIT

Some commenters would like to know how to select all the inputs in question that are not contained in any .hidden element (not necessarily a direct parent). This is a tougher problem. The following:

input[name*="foo"][name*="bar"]:not(.hidden input)

does not seem to work, I think because :not only permits relatively simple selectors inside. The only way I can think of is to update all the chosen inputs and then un-update them when within any .hidden elements:

input[name*="foo"][name*="bar"] { color: red; }
.hidden input[name*="foo"][name*="bar"] { color: black; }

This will only work if the default settings (ie color: black) is uniform I'm afraid.


问:
Dataflow writing to Datastore: "Message: datastore transaction or write too big."
I'm just starting with Dataflow / Apache Beam.
I wrote a Dataflow pipeline in Python to import a big catalog of products (> 50K products, stored inside a JSON file) into Datastore.
The pipeline runs fine on my local machine (DirectRunner) but fails on the DataflowRunner with the following error message:

```<code>RPCError: datastore call commit [while running 'write to datastore/Write Mutation to Datastore'] failed: Error code: INVALID_ARGUMENT. Message: datastore transaction or write too big.
</code>```

My guess would be that Datastore can't handle the write rate of the pipeline, but I'm not sure on how I can throttle down the writing in the Dataflow pipeline.

I'm using the WriteToDatastore transform to write to DataStore:

```<code>from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
</code>```

My pipeline looks like this:

```<code>with beam.Pipeline(options=pipeline_options) as p:
(p  # pylint: disable=expression-not-assigned
 | 'read from json' >> ReadFromText(known_args.input, coder=JsonCoder())
 | 'create entity' >> beam.Map(
     EntityWrapper(known_args.namespace, known_args.kind,
                   known_args.ancestor).make_entity)
 | 'write to datastore' >> WriteToDatastore(known_args.dataset))
</code>```

Thanks in advance for your help.

答:
Doesn't look like a write rate issue. That error message means a mutation was above system limits. Causes can include:

Exceeding 500 entities in a single transaction

Exceeding 10MiB in a single transaction

Exceeding 1MiB in a single entity

Exceeding 2MiB total composite index size for an entity

You can read more about Cloud Datastore system limits in our Limits documentation.

Body:
I'm just starting with Dataflow / Apache Beam.
I wrote a Dataflow pipeline in Python to import a big catalog of products (> 50K products, stored inside a JSON file) into Datastore.
The pipeline runs fine on my local machine (DirectRunner) but fails on the DataflowRunner with the following error message:

RPCError: datastore call commit [while running 'write to datastore/Write Mutation to Datastore'] failed: Error code: INVALID_ARGUMENT. Message: datastore transaction or write too big.

My guess would be that Datastore can't handle the write rate of the pipeline, but I'm not sure on how I can throttle down the writing in the Dataflow pipeline.

I'm using the WriteToDatastore transform to write to DataStore:

from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore

My pipeline looks like this:

with beam.Pipeline(options=pipeline_options) as p:
(p  # pylint: disable=expression-not-assigned
 | 'read from json' >> ReadFromText(known_args.input, coder=JsonCoder())
 | 'create entity' >> beam.Map(
     EntityWrapper(known_args.namespace, known_args.kind,
                   known_args.ancestor).make_entity)
 | 'write to datastore' >> WriteToDatastore(known_args.dataset))

Thanks in advance for your help.


问:
Visual studio forms designer and derived usercontrols
I have visual studio 2015 and code in C#. I use the windows forms designer and have:

class BaseControl
with a tablelayout and some base controls + a (public) and in designer placed panel A to be filled by subcontrols

class SpecificControl : BaseControl
if i open it in designer, i see (of course) all controls of the BaseControl. But i cannot place anything inside the panel A - even if A is public.

I see a small black rectangle in upper left corner of the panel (like blocked) and if a move e.g. a textbox onto the panel i see the circle with the line that shows me it is not allowed.

of course i can add my textbox by code cause panel A is public.

How can i make this working?

答:
Set Modifiers property of Panel A on BaseControl to protected

May also need to build project before it correctly picks this up.

Though I would say be careful using visual form inheritance in c#;  it can often cause more issues than it solves.


问:
Load Wordpress admin CSS into thickbox (or anywhere)?
I have a plugin that uses the built-in WordPress ThickBox and I want to load the regular wordpress administration dashboard CSS into this ThickBox.  It does not happen automatically, since I am loading an iFrame within the ThickBox.  Can i wp_enqueue_style() something that will automagically load this for me?  </p>

答:
You need to add a GET param to the URL when loading the thickbox.  When this GET param is present you can set an admin body class, in which you can hide all the other non-essential admin elements.

Example:

```<code>if(isset($_GET['tb'])){
  add_action("admin_body_class", "set_iframe_class");
}
</code>```

Body:
You need to add a GET param to the URL when loading the thickbox.  When this GET param is present you can set an admin body class, in which you can hide all the other non-essential admin elements.

Example:

if(isset($_GET['tb'])){
  add_action("admin_body_class", "set_iframe_class");
}


问:
Python 2.7 - I'm getting the wrong order of values after converting CSV to JSON
I want to convert CSV to JSON file by taking data from stdin and outputting it to stdout. The input data's format has a format (each line) like this:
    111117_055958,b8:27:eb:da:ef:6d,0,b8:27:eb:8f:ba:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593,3697,-2.700629,X

My Python code is:

```<code>#!/usr/bin/env python
import csv, json , sys

fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",)
reader = csv.DictReader(sys.stdin, fieldnames)

for row in reader:
    print(json.dumps(row, sys.stdout))
    sys.stdout.write('\n')
</code>```

And my output looks like this:

```<code>{"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"}
</code>```

So names and values of parameters are OK. But the order of parameters is different compared to the input string and order in the fieldnames value. Can you tell me what I am doing wrong?

I use Python 2.7.12 on Synology.

答:
A workaround to this problem would be to use a normal csv.reader() and to then construct an OrderedDict() with each row. This can then be passed to json.dumps() to maintain the order:

```<code>from collections import OrderedDict
import csv, json, sys

fieldnames = ("Time", "MAC_ETH", "IP_ETH", "MAC_WiFi", "IP_WiFi", "Up_time", "Winsen", "ADC_2", "ADC_3", "VOC", "Temp", "Humidity", "Internet", "Lampa_UV", "CPU_temp", "Amph_P1", "Amph_P2", "PT100", "Brak",)

for row in csv.reader(sys.stdin):
    rowd = OrderedDict(zip(fieldnames, row))
    print(json.dumps(rowd, sys.stdout))
    sys.stdout.write('\n')
</code>```

This would give you output as:

```<code>{"Time": "111117_055958", "MAC_ETH": "b8:27:eb:da:ef:6d", "IP_ETH": "0", "MAC_WiFi": "b8:27:eb:8f:ba:38", "IP_WiFi": "192.168.1.10", "Up_time": "171110_163200", "Winsen": "19", "ADC_2": "0", "ADC_3": "0", "VOC": "562", "Temp": "18.7", "Humidity": "50.1", "Internet": "ON", "Lampa_UV": "OFF", "CPU_temp": "44.0", "Amph_P1": "6593", "Amph_P2": "3697", "PT100": "-2.700629", "Brak": "X"}
</code>```

Body:
I want to convert CSV to JSON file by taking data from stdin and outputting it to stdout. The input data's format has a format (each line) like this:
    111117_055958,b8:27:eb:da:ef:6d,0,b8:27:eb:8f:ba:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593,3697,-2.700629,X

My Python code is:

#!/usr/bin/env python
import csv, json , sys

fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",)
reader = csv.DictReader(sys.stdin, fieldnames)

for row in reader:
    print(json.dumps(row, sys.stdout))
    sys.stdout.write('\n')

And my output looks like this:

{"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"}

So names and values of parameters are OK. But the order of parameters is different compared to the input string and order in the fieldnames value. Can you tell me what I am doing wrong?

I use Python 2.7.12 on Synology.

Body:
A workaround to this problem would be to use a normal csv.reader() and to then construct an OrderedDict() with each row. This can then be passed to json.dumps() to maintain the order:

from collections import OrderedDict
import csv, json, sys

fieldnames = ("Time", "MAC_ETH", "IP_ETH", "MAC_WiFi", "IP_WiFi", "Up_time", "Winsen", "ADC_2", "ADC_3", "VOC", "Temp", "Humidity", "Internet", "Lampa_UV", "CPU_temp", "Amph_P1", "Amph_P2", "PT100", "Brak",)

for row in csv.reader(sys.stdin):
    rowd = OrderedDict(zip(fieldnames, row))
    print(json.dumps(rowd, sys.stdout))
    sys.stdout.write('\n')

This would give you output as:

{"Time": "111117_055958", "MAC_ETH": "b8:27:eb:da:ef:6d", "IP_ETH": "0", "MAC_WiFi": "b8:27:eb:8f:ba:38", "IP_WiFi": "192.168.1.10", "Up_time": "171110_163200", "Winsen": "19", "ADC_2": "0", "ADC_3": "0", "VOC": "562", "Temp": "18.7", "Humidity": "50.1", "Internet": "ON", "Lampa_UV": "OFF", "CPU_temp": "44.0", "Amph_P1": "6593", "Amph_P2": "3697", "PT100": "-2.700629", "Brak": "X"}


问:
Spring - Resteasy - Cors Double Access-Control-Allow-Origin header in response
I setup a web application with Spring 3 and Resteasy; since my resources require authentication I am not allowed to use * as Access-Control-Allow-Origin.
So I configured

```<code>org.jboss.resteasy.plugins.interceptors.CorsFilter
</code>```

with the right origin domain.
This works with a desktop client (Paw for Mac Os and others), but not with the browser (Chrome); the problem is that the response contains a double value for Access-Control-Allow-Origin, that is the one I configured and '*'.

CorsFilter is not to blame because, even if you configure more than one origin, it always puts just one value for the header, the one which the request asked for.

I simply have no idea on who's putting that extra (and wrong) header, any idea on where I could look for?
Please note that the double header occurs on GET requests but not on OPTIONS requests.

答:
For those struggling like me who don't use the Application starter but only Spring + Reasteasy.

Just add in web.xml:

```<code><context-param>
    <param-name>resteasy.providers</param-name>
    <param-value>package.to.your.cors.CORSFilter</param-value>
</context-param>
</code>```

And create the Java Class CORSFilter like

```<code>package package.to.your.cors;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext requestContext,
                       final ContainerResponseContext cres) throws IOException {
        cres.getHeaders().add("Access-Control-Allow-Origin", "*");
        cres.getHeaders().add("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        cres.getHeaders().add("Access-Control-Allow-Headers", "X-Auth-Token, Content-Type");
        cres.getHeaders().add("Access-Control-Max-Age", "4800");
    }

}
</code>```

It works like a charm.

PS: inspired by s_bighead answer but I could not comment his answer to add my details.

Body:
I setup a web application with Spring 3 and Resteasy; since my resources require authentication I am not allowed to use * as Access-Control-Allow-Origin.
So I configured

org.jboss.resteasy.plugins.interceptors.CorsFilter

with the right origin domain.
This works with a desktop client (Paw for Mac Os and others), but not with the browser (Chrome); the problem is that the response contains a double value for Access-Control-Allow-Origin, that is the one I configured and '*'.

CorsFilter is not to blame because, even if you configure more than one origin, it always puts just one value for the header, the one which the request asked for.

I simply have no idea on who's putting that extra (and wrong) header, any idea on where I could look for?
Please note that the double header occurs on GET requests but not on OPTIONS requests.

Body:
For those struggling like me who don't use the Application starter but only Spring + Reasteasy.

Just add in web.xml:

<context-param>
    <param-name>resteasy.providers</param-name>
    <param-value>package.to.your.cors.CORSFilter</param-value>
</context-param>

And create the Java Class CORSFilter like

package package.to.your.cors;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext requestContext,
                       final ContainerResponseContext cres) throws IOException {
        cres.getHeaders().add("Access-Control-Allow-Origin", "*");
        cres.getHeaders().add("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        cres.getHeaders().add("Access-Control-Allow-Headers", "X-Auth-Token, Content-Type");
        cres.getHeaders().add("Access-Control-Max-Age", "4800");
    }

}

It works like a charm.

PS: inspired by s_bighead answer but I could not comment his answer to add my details.


问:
How to provide code for tkinter toplevel before data can be accessed
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

```<code>def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()
</code>```

答:
Well, from the example you've provided (after I fixed the indentation) I get an "Invalid Syntax" error because you are trying to compare en1.get() to a variable 2e2c2v which you haven't declared.

Update this line . . .

```<code>if en1.get() == 2e2c2v:
</code>```

. . . To . . .

```<code>if en1.get() == "2e2c2v":
</code>```

After I did this it worked for me as expected.

Body:
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()

Body:
Well, from the example you've provided (after I fixed the indentation) I get an "Invalid Syntax" error because you are trying to compare en1.get() to a variable 2e2c2v which you haven't declared.

Update this line . . .

if en1.get() == 2e2c2v:

. . . To . . .

if en1.get() == "2e2c2v":

After I did this it worked for me as expected.


问:
Adding dll's to the project and making functions work
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

```<code>#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__
</code>```

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?

答:
There is a windows call that loads a DLL into your image.  You can either add it to the compile setup in Visual Studio, or load it dynamically.

The easiest thing is probably to do it at compile time; google "Visual Studio llinking options".

Body:
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?


答:
change like this:

```<code>div:not(.hidden) input[name*="foo"][name*="bar"] {
    background-color: yellow;
}
</code>```

div:not(.hidden) input[name*="foo"][name*="bar"] {
 background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hidden">
  <input name="bar-foo" value="test">
</div>
<div class="hidden">
  <input name="bar-foo-baz" value="test2">
</div>
<div class="nothidden">
  <input name="bar-foo" value="test3"> <!-- should be selected -->
</div>
<div class="nothidden">
  <input name="foo-bar-baz" value="test4"> <!-- should be selected -->
</div></code>```

Body:
change like this:

div:not(.hidden) input[name*="foo"][name*="bar"] {
    background-color: yellow;
}

div:not(.hidden) input[name*="foo"][name*="bar"] {
 background-color: yellow;
}

<div class="hidden">
  <input name="bar-foo" value="test">
</div>
<div class="hidden">
  <input name="bar-foo-baz" value="test2">
</div>
<div class="nothidden">
  <input name="bar-foo" value="test3"> <!-- should be selected -->
</div>
<div class="nothidden">
  <input name="foo-bar-baz" value="test4"> <!-- should be selected -->
</div>


答:
Try targetting only the direct children of your classes that are not hidden, like this: </p>

```:not(.hidden) > input[name*="foo"][name*="bar"] { color:blue; }```

Body:
I have this situation

  <input name="bar-foo" value="test">

  <input name="bar-foo-baz" value="test2">

  <input name="bar-foo" value="test3">

  <input name="foo-bar-baz" value="test4">

I need to match inputs containing word foo and bar, not contained in a div which class is 'hidden'.

input[name*="foo"][name*="bar"]

matches all the four inputs.

:not(.hidden) input[name*="foo"][name*="bar"]

in my opinion, should match inputs not contained in something with class '.hidden', but it doesn't. How do I achieve this result?

Here is it a jsfiddle
https://jsfiddle.net/8dLbz5ws/1/

Body:
Try targetting only the direct children of your classes that are not hidden, like this:

:not(.hidden) > input[name*="foo"][name*="bar"] { color:blue; }


问:
Printing out symbols into tuple
I need to write a code using a function, that counts all symbols into dictionary (including whitespace, commas etc) and another function to print all elements that accoured atleast once into tuple (i.e giving "Hello world" output=('h', 'e', 'l', 'o', ' ', 'w', 'r', 'd') This is my code so far:</p>

```<code>def frequency(word):
  dict = {}
  for el in word:
     el = el.lower()
     if el in dict and not "":
         dict[el] += 1
     elif el not in dict and not "":
         dict[el] = 1
  for k,v in dict.items():
    print(k + ":" + str(v))

def different_symbols(word):
  dict={}
  for el in dict:
      if el not in dict:
          dict[el] = el
      elif el in dict:
         print(el)

frequency("Hello world!")
different_symbols("Hello world!")
</code>```

答:
Measure frequency using Counter.most_common() and unique characters with set(). If you specifically want dict and tuple type results:

```<code>from collections import Counter

def frequency(word):
    letters = Counter(word).most_common()
    letters_dict = {k: v for k, v in letters}
    return letters_dict

def different_symbols(word):
    return tuple(set(word))

print(frequency("Hello World!"))
# {'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

print(different_symbols("Hello World!"))
# ('d', ' ', 'r', 'l', 'H', 'e', 'o', 'w') order is completely random
</code>```

Title: Printing out symbols into tuple

Body:
I need to write a code using a function, that counts all symbols into dictionary (including whitespace, commas etc) and another function to print all elements that accoured atleast once into tuple (i.e giving "Hello world" output=('h', 'e', 'l', 'o', ' ', 'w', 'r', 'd') This is my code so far:

def frequency(word):
  dict = {}
  for el in word:
     el = el.lower()
     if el in dict and not "":
         dict[el] += 1
     elif el not in dict and not "":
         dict[el] = 1
  for k,v in dict.items():
    print(k + ":" + str(v))

def different_symbols(word):
  dict={}
  for el in dict:
      if el not in dict:
          dict[el] = el
      elif el in dict:
         print(el)

frequency("Hello world!")
different_symbols("Hello world!")

Body:
Measure frequency using Counter.most_common() and unique characters with set(). If you specifically want dict and tuple type results:

from collections import Counter

def frequency(word):
    letters = Counter(word).most_common()
    letters_dict = {k: v for k, v in letters}
    return letters_dict

def different_symbols(word):
    return tuple(set(word))

print(frequency("Hello World!"))
# {'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

print(different_symbols("Hello World!"))
# ('d', ' ', 'r', 'l', 'H', 'e', 'o', 'w') order is completely random


问:
Android Studio Desugar: Transform Classes with Desugar for Debug fails
My Android Studio project recently stopped building properly. I do not know what caused this issue.
Here is what I tried

I tried to build my project with different Android Studio versions, i.e. stable and different Canary channel versions, no change

I changed SDK versions around. My project built properly with SDK 26, but now it does not, also not with SDK 27

I swapped build tools and Gradle versions around, my project built properly with Gradle plugin 3.1.0-alpha2 and build tools version 26.0.2. I tried many

I used the "Clean Project", "Invalidate Caches"... functions in Android Studio uncountable times

I deleted my build folders

I switched Proguard on and off

I tried fixing possible library issues, but all of it did not help

I think I actually changed everything back to the settings I used successfully before and my other projects with similar settings just build fine.

Full error code:

```<code>Error:java.lang.RuntimeException: com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:org.gradle.process.internal.ExecException: Process 'command '...\jre\bin\java.exe'' finished with non-zero exit value 1
</code>```

Problem description

I have no clue what could (have) cause(d) this issue and I am clueless about what to try next, which is the reason why I am asking you for help. I hope anyone has any other help than what I could find.

I tagged Firebase because I think that the library might be the crucial point of my problem, now the problem is that it will never explain the sudden stop. I use FirebaseUI in my application and tried the old working dependencies, but also upgrading Firebase and then using this guide to match the outdated UI library. I also removed FirebaseUI, but this did neither make a successful build.

答: I fixed it (and another Kotlin related issue, by just completely wiping everything Android and Gradle related from my computer and then installing everything from scratch. Whole process was a torture, so I am still keen for a quick solution. I do not want to spend hours on this again :)</p>

Body:
My Android Studio project recently stopped building properly. I do not know what caused this issue.
Here is what I tried

I tried to build my project with different Android Studio versions, i.e. stable and different Canary channel versions, no change

I changed SDK versions around. My project built properly with SDK 26, but now it does not, also not with SDK 27

I swapped build tools and Gradle versions around, my project built properly with Gradle plugin 3.1.0-alpha2 and build tools version 26.0.2. I tried many

I used the "Clean Project", "Invalidate Caches"... functions in Android Studio uncountable times

I deleted my build folders

I switched Proguard on and off

I tried fixing possible library issues, but all of it did not help

I think I actually changed everything back to the settings I used successfully before and my other projects with similar settings just build fine.

Full error code:

Error:java.lang.RuntimeException: com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:org.gradle.process.internal.ExecException: Process 'command '...\jre\bin\java.exe'' finished with non-zero exit value 1

Problem description

I have no clue what could (have) cause(d) this issue and I am clueless about what to try next, which is the reason why I am asking you for help. I hope anyone has any other help than what I could find.

I tagged Firebase because I think that the library might be the crucial point of my problem, now the problem is that it will never explain the sudden stop. I use FirebaseUI in my application and tried the old working dependencies, but also upgrading Firebase and then using this guide to match the outdated UI library. I also removed FirebaseUI, but this did neither make a successful build.


问:
PCA() got an unexpected keyword argument 'k'
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)
```

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

答:
Are you sure you have not also imported PCA from scikit-learn, after you imported it from PySpark in your application script?

spark.version
# u'2.2.0'

from pyspark.ml.feature import PCA
from sklearn.decomposition import PCA

# PySpark syntax with scikit-learn PCA function
pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
# Error:
TypeError: __init__() got an unexpected keyword argument 'k'
```

Reversing the order of imports will not produce the error (not shown).

Body:
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

Body:
Are you sure you have not also imported PCA from scikit-learn, after you imported it from PySpark in your application script?

spark.version
# u'2.2.0'

from pyspark.ml.feature import PCA
from sklearn.decomposition import PCA

# PySpark syntax with scikit-learn PCA function
pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
# Error:
TypeError: __init__() got an unexpected keyword argument 'k'

Reversing the order of imports will not produce the error (not shown).


问:
R studio using time-series plot
I have CVS file with three columns

```<code>EX : name | number | boolean
     joan   4        true   etc...
</code>```

I want to convert CSV file to time-series plot, and tried those commands in R:

```<code>library(ggplot2)
data <- read.csv(".../.../.../outpots/names.csv")
ggplot(data, aes(name, number)) + geom_line()
</code>```

but I see graph without the plot inside

thanks

答:
The name field is a factor rather than a numeric field but we can use it on a line plot anyways by adding group=1 to the aes() specification.  This would also work if name were a character field.

```<code>library(ggplot2)
DF <- data.frame(name = letters, number = 1:26)  # test input

ggplot(DF, aes(name, number, group = 1)) + geom_line()
</code>```

giving:

Title: R studio using time-series plot

Body:
I have CVS file with three columns

EX : name | number | boolean
     joan   4        true   etc...

I want to convert CSV file to time-series plot, and tried those commands in R:

library(ggplot2)
data <- read.csv(".../.../.../outpots/names.csv")
ggplot(data, aes(name, number)) + geom_line()

but I see graph without the plot inside

thanks

Body:
The name field is a factor rather than a numeric field but we can use it on a line plot anyways by adding group=1 to the aes() specification.  This would also work if name were a character field.

library(ggplot2)
DF <- data.frame(name = letters, number = 1:26)  # test input

ggplot(DF, aes(name, number, group = 1)) + geom_line()

giving:


问:
Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps?
I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible.

Any suggestions?

答:
I use Netbeans Profiler:

alt text http://www.netbeans.org/images/v6/1/features/profiler-java-cut.png

Its free, has task based profiling, a heap walker, allows the insertion of profiling points, tracks memory usage and threading, but best of all it allows you to profile remote JVM's.  You can even attach to ones which are already running.

Oh, and it works really well if you've a maven build for your project too.

OwnerDisplayName: Andrew Harmel-Law


问:
Naming conventions for replacement APIs / classes
Do you have a naming convention for APIs or Classes that are being phased in to replace an older version that performed the same function / filled the same role?

E.g. Windows does this by adding "Ex" to the end of the function:

```<code>ShellExecute // old
ShellExecuteEx // new
</code>```

What do you prefer, and what are you reasonings?

Appending 2, V2, New, NowInStereo?

Doing a one-time rename of the old API from Something to SomethingOld and using Something for the new stuff?  This option worries me when it comes to version control, but it also seems the least likely to be burdened with a V3 or ReallyNew problem in the future.

Making up a completely different name that may describe the function less accurately, but at least is different.

答: Much of the time you can get away with changing the package name, rather than the class name itself.</p>

OwnerDisplayName: Josh

Body:
Do you have a naming convention for APIs or Classes that are being phased in to replace an older version that performed the same function / filled the same role?

E.g. Windows does this by adding "Ex" to the end of the function:

ShellExecute // old
ShellExecuteEx // new

What do you prefer, and what are you reasonings?

Appending 2, V2, New, NowInStereo?

Doing a one-time rename of the old API from Something to SomethingOld and using Something for the new stuff?  This option worries me when it comes to version control, but it also seems the least likely to be burdened with a V3 or ReallyNew problem in the future.

Making up a completely different name that may describe the function less accurately, but at least is different.

OwnerDisplayName: jamesh


问:
Visual Basic for Microsoft Access Training
I am currently trying to learn how to create, run, and manage a Database for a company that deals with Chemicals.

My question is simple. Is there a website or a very good read that can help me understand and learn VBA or Visual Basic?

答: I suggest better go for some better database technology. Use SQL server 2008; and since even with VBA you need to learn from scratch, why not learn SQL. The technology is far better and manageable than access and VBA</p>


问:
Keycloak: getting back from user profile page
In my application I have a link that redirects to the user's account page on the Keycloak server.
In this page the user can update his personal information.

The problem is that after entering his account page the user has no way to get back to the application.

There's a way to let the user get back without editing the page theme?

答:
I found the answer by looking at the freemaker template.

In my case I had to:

Set the application URL in the Base URL option in the Keycloak client settings.

Append the parameter ?referrer=<Client ID> on the URL that links to the user profile page.

ie http://127.0.0.1:8080/auth/realms/<realm>/account?referrer=<Client ID>

With these two settings the link to go back to the application will be visible.

ContentLicense: CC BY-SA 4.0


问:
Need help to write Sql update query?
I need to update parent table with value from child  one

this my explanation

```<code>update table1 set column1 = (select name from table2 where profile = true)
where column2 in (select id from table2 where profile = true)
</code>```

basically i need to copy name from child and set is as column1 in table1 where ids are the same in parent and child table and profile in table2 = true

答:
For SQL Server, the Update table is virtually also in the FROM clause
SQL Server uses bit for booleans (no true/false), so I suspect you are using something else

```<code>update table1
set column1 = table2.name
from table2
where table1.column2 = table2.id and table2.profile = 1
</code>```

MySQL form ( and Oracle too )

```<code>update table1 a join table2 b on a.column2 = b.id
set column1 = table2.name
where b.profile  # 'true = true' is silly
# b.profile = true   === just   b.profile
</code>```

Title: Need help to write Sql update query?

Body:
I need to update parent table with value from child  one

this my explanation

update table1 set column1 = (select name from table2 where profile = true)
where column2 in (select id from table2 where profile = true)

basically i need to copy name from child and set is as column1 in table1 where ids are the same in parent and child table and profile in table2 = true

Body:
For SQL Server, the Update table is virtually also in the FROM clause
SQL Server uses bit for booleans (no true/false), so I suspect you are using something else

update table1
set column1 = table2.name
from table2
where table1.column2 = table2.id and table2.profile = 1

MySQL form ( and Oracle too )

update table1 a join table2 b on a.column2 = b.id
set column1 = table2.name
where b.profile  # 'true = true' is silly
# b.profile = true   === just   b.profile


问:
How to scroll to an element with a specific class inside a modal using jquery?
I want to scroll to an element with a specific class inside a modal using jquery
however i'm using theis code after opening the modal

```<code><!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" id="demo-view">
  Launch demo modal
</button>

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel vehicula erat. Phasellus vestibulum leo eu mi tempor blandit. Suspendisse eget iaculis lectus. Donec vitae tempus enim, quis tristique magna. Donec lobortis, sem ac pretium viverra, leo nisl consequat arcu, sit amet ullamcorper nunc turpis ac erat. In rutrum auctor ligula, quis mattis enim lacinia eu. Aliquam at magna a erat laoreet iaculis quis a justo. Donec porttitor vulputate massa, nec suscipit nisi mollis sed.</p>
                <p>Praesent sit amet porttitor magna, auctor feugiat tellus. Sed venenatis tortor turpis, vel vestibulum eros pulvinar et. Pellentesque hendrerit diam quis dui euismod tincidunt. Sed sit amet mauris ipsum. Integer in magna tellus. In tincidunt mi quis nunc gravida sollicitudin. Aliquam ac dui eget erat consequat volutpat in eu magna.</p>
                <p>Sed feugiat bibendum leo consequat convallis. Donec facilisis, turpis a scelerisque venenatis, felis diam dictum tortor, vitae imperdiet tortor ligula eu lectus. Donec iaculis semper elementum. Nullam dapibus porttitor magna quis convallis. Morbi porttitor quam non magna ullamcorper rhoncus. Phasellus sit amet nunc at turpis pharetra luctus a a massa. Praesent luctus massa in odio faucibus eleifend.</p>
                <p>In eget lobortis leo, ut luctus odio. Mauris pharetra erat ac tellus hendrerit semper. Cras faucibus ipsum id ante hendrerit rutrum. Donec vitae ullamcorper arcu. Aliquam pellentesque faucibus placerat. Aliquam erat volutpat. In tincidunt metus sit amet ligula sagittis vehicula. Pellentesque velit quam, hendrerit a erat ac, fermentum tincidunt enim. Cras suscipit justo nec consectetur lacinia.</p>
<div>
<p>Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.</p>
</div>
<div class="unreaded">
<p>Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.</p>
</div>
<div class="unreaded">
<p>Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.</p>
</div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</code>```

javascript

```<code>$(document).on('click', ".#demo-view", function (e) {
$('#myModal').modal('show');
$('html, body').animate({
    scrollTop: $('.unreaded:visible:first').offset().top
}, 1000);
}
</code>```

Without modal it's work well. can someone help me to fix that ?
https://jsfiddle.net/ZcLSE/1904/
Thanks

答:
Updated fiddle

Your solution is not working because your content is in modal window and is not yet shown when you trigger animation. You should call scroll for modal window body on "shown" callback (when content is already generated);
Plus:

```<code>$('.unreaded:visible:first')
</code>```

This is definitely undefined thing :)

Body:
I want to scroll to an element with a specific class inside a modal using jquery
however i'm using theis code after opening the modal

<button class="btn btn-primary btn-lg" id="demo-view">
  Launch demo modal
</button>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel vehicula erat. Phasellus vestibulum leo eu mi tempor blandit. Suspendisse eget iaculis lectus. Donec vitae tempus enim, quis tristique magna. Donec lobortis, sem ac pretium viverra, leo nisl consequat arcu, sit amet ullamcorper nunc turpis ac erat. In rutrum auctor ligula, quis mattis enim lacinia eu. Aliquam at magna a erat laoreet iaculis quis a justo. Donec porttitor vulputate massa, nec suscipit nisi mollis sed.

Praesent sit amet porttitor magna, auctor feugiat tellus. Sed venenatis tortor turpis, vel vestibulum eros pulvinar et. Pellentesque hendrerit diam quis dui euismod tincidunt. Sed sit amet mauris ipsum. Integer in magna tellus. In tincidunt mi quis nunc gravida sollicitudin. Aliquam ac dui eget erat consequat volutpat in eu magna.

Sed feugiat bibendum leo consequat convallis. Donec facilisis, turpis a scelerisque venenatis, felis diam dictum tortor, vitae imperdiet tortor ligula eu lectus. Donec iaculis semper elementum. Nullam dapibus porttitor magna quis convallis. Morbi porttitor quam non magna ullamcorper rhoncus. Phasellus sit amet nunc at turpis pharetra luctus a a massa. Praesent luctus massa in odio faucibus eleifend.

In eget lobortis leo, ut luctus odio. Mauris pharetra erat ac tellus hendrerit semper. Cras faucibus ipsum id ante hendrerit rutrum. Donec vitae ullamcorper arcu. Aliquam pellentesque faucibus placerat. Aliquam erat volutpat. In tincidunt metus sit amet ligula sagittis vehicula. Pellentesque velit quam, hendrerit a erat ac, fermentum tincidunt enim. Cras suscipit justo nec consectetur lacinia.

Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.

Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.

Cras pellene urna a leo egestas, at ullamcorper augue suscipit. Nulla id lacinia magna, non iaculis est. Praesent a placerat augue, eget eleifend purus. Aenean dignissim, orci et rutrum facilisis, tellus massa porta nulla, quis hendrerit dui ipsum vitae urna. In mattis lectus dolor, id venenatis lectus pellentesque at. Suspendisse posuere metus vel bibendum dignissim. Fusce interdum magna id libero scelerisque suscipit. Duis orci augue, rhoncus eget pharetra ac, viverra nec magna. In accumsan nulla ac suscipit pellentesque. Nulla iaculis luctus tellus, at ultricies urna hendrerit a. Aenean vehicula sodales varius. Duis sodales hendrerit odio non sagittis.

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

javascript

$(document).on('click', ".#demo-view", function (e) {
$('#myModal').modal('show');
$('html, body').animate({
    scrollTop: $('.unreaded:visible:first').offset().top
}, 1000);
}

Without modal it's work well. can someone help me to fix that ?
https://jsfiddle.net/ZcLSE/1904/
Thanks

Body:
Updated fiddle

Your solution is not working because your content is in modal window and is not yet shown when you trigger animation. You should call scroll for modal window body on "shown" callback (when content is already generated);
Plus:

$('.unreaded:visible:first')

This is definitely undefined thing :)


问:
How can I merge these regex into one?
(Before I start: I'm doing this in python)

So basically I need my single regex to match all quotation marks immediately before and after my html QUOT tags: If a quotation mark exists in those spaces, I need it to match.

Example:

```<code><QUOT.START> Hello, this doesn't match! <\QUOT.END>

"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "
</code>```

I have 4 different regexes for this purpose:

```<code>1.   \"+(?=<QUOT\.START>)

2.   (?<=<QUOT\.START>)\"+

3.   \"+(?=<\\QUOT\.END>)

4.   (?<=<\\QUOT\.END>)\"+
</code>```

Can I merge these 4 into basically one?

答:
If you're able to use the newer regex module (which supports infinite lookbehind) you can somewhat condense your expression to

```<code>(?<=<\\?QUOT\.(?:START|END)>[\t ]*)" # matches quotes after <quot.start> or <quot.end>
                                     # plus whitespaces, eventually
|
"(?=[\t ]*<\\?QUOT\.(?:START|END)>)  # before <quot.start> or <quot.end>,
                                     # plus whitespaces eventually
</code>```

Without verbose mode:

```<code>(?<=<\\?QUOT\.(?:START|END)>[\t ]*)"|"(?=[\t ]*<\\?QUOT\.(?:START|END)>)
</code>```

Generally speaking this is:

```<code>(?<=<tag><whitespaces, eventually>)quote|quote(?=<whitespaces, eventually><tag>)
</code>```

In Python:

```<code>import regex as re

string = """
<QUOT.START> Hello, this doesn't match! <\QUOT.END>
"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "
"""

rx = re.compile(r'''(?<=<\\?QUOT\.(?:START|END)>[\t ]*)"|"(?=[\t ]*<\\?QUOT\.(?:START|END)>)''')

for m in rx.finditer(string):
    print(m.group(0))
    print(m.span())
</code>```

This brings up four quotes and their positions.

Title: How can I merge these regex into one?

Body:
(Before I start: I'm doing this in python)

So basically I need my single regex to match all quotation marks immediately before and after my html QUOT tags: If a quotation mark exists in those spaces, I need it to match.

Example:

<QUOT.START> Hello, this doesn't match! <\QUOT.END>

"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "

I have 4 different regexes for this purpose:

1.   \"+(?=<QUOT\.START>)

2.   (?<=<QUOT\.START>)\"+

3.   \"+(?=<\\QUOT\.END>)

4.   (?<=<\\QUOT\.END>)\"+

Can I merge these 4 into basically one?

Body:
If you're able to use the newer regex module (which supports infinite lookbehind) you can somewhat condense your expression to

(?<=<\\?QUOT\.(?:START|END)>[\t ]*)" # matches quotes after <quot.start> or <quot.end>
                                     # plus whitespaces, eventually
|
"(?=[\t ]*<\\?QUOT\.(?:START|END)>)  # before <quot.start> or <quot.end>,
                                     # plus whitespaces eventually

Without verbose mode:

(?<=<\\?QUOT\.(?:START|END)>[\t ]*)"|"(?=[\t ]*<\\?QUOT\.(?:START|END)>)

Generally speaking this is:

(?<=<tag><whitespaces, eventually>)quote|quote(?=<whitespaces, eventually><tag>)

In Python:

import regex as re

string = """
<QUOT.START> Hello, this doesn't match! <\QUOT.END>
"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "
"""

rx = re.compile(r'''(?<=<\\?QUOT\.(?:START|END)>[\t ]*)"|"(?=[\t ]*<\\?QUOT\.(?:START|END)>)''')

for m in rx.finditer(string):
    print(m.group(0))
    print(m.span())

This brings up four quotes and their positions.


问:
Java coursework questions
I'm an undergraduate student and I'm looking for help with troubleshooting the code I'm writing for my coursework.

```<code>import weather.WeatherData;
import Weather.data.classes.WeatherReading;
import Weather.data.classes.WeatherStation;

/**
 * QUESTION 01
 *
 * If you decide to answer question 01 then the main method below should be used as the entry point for your application
 * You may use as many other classes as you feel necessary as long as all code is supplied
 *
 * Remember to add -Xmx1024m to the VM arguments using menu run --> run configurations in eclipse
 */
public class Answer01 {
    public static void main(String[] args) {
        System.out.println("Question 01");
        /*
         * Add your code below
         */
        WeatherStation x = new WeatherStation("site", "a", 1.1, 1.0);
        WeatherReading y = new WeatherReading(1,2,3,4,5,6);
        String line[] = WeatherData.getData();
        ArrayList<WeatherStation>weatherSize = new ArrayList<>();
        for(int i = 1; i < line.length; i++){
        String [] split = line[i].split(",");
        WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));
        weatherSize.add(z);
        }

        System.out.println(weatherSize.size() + " test");

    }
}
</code>```

The problem I'm having here is that weatherSize.size() is printing out 0 instead of the correct answer which is 136.

The code draws data from a JAR file called weather.WeatherData and I created two classes which have getters and setters and toString() methods, called WeatherStation and WeatherReading.

The jar file is library item called WeatherData.jar and it records weather data recorded at different locations in the uk.

String[] weatherData = WeatherData.getData();

Returns an array of string and the first element at index 0 contains header information.

Element 0: SiteId,SiteName,Latitude,Longitude,Year,Month,Date,Hour,WindSpeed,Temperature
Element 1:
3002,BALTASOUND (3002),60.7490,-0.8540,2015,01,01,0,21,8.70

When I run my code for Answer01 it simply says: 0 test

```<code>    package Weather.data.classes;

    public class WeatherStation {
    public String siteId;
    public String siteName;
    public double latitude;
    public double longitude;

    public WeatherStation(String siteId, String siteName, double latitude, double longitute){
        super();
        this.siteId = siteId;
        this.siteName = siteName;
        this.latitude = latitude;
        this.longitude = longitude;
        }
    }
</code>```

And WeatherReading:

```<code>package Weather.data.classes;

public class WeatherReading {
    public int year;
    public int month;
    public int date;
    public int hour;
    public int windSpeed;
    public int temperature;

    public WeatherReading(int year, int month, int date, int hour, int windSpeed, int temperature){
        this.year = year;
        this.month = month;
        this.date = date;
        this.hour = hour;
        this.windSpeed = windSpeed;
        this.temperature = temperature;
    }
}
</code>```

答:
My suggestion would be to check the length of the line array which is read from the file

```<code>String line[] = WeatherData.getData();
System.out.println("Number of lines : " + line.length);
</code>```

This way you will know if the file is being read correctly.
Can you also check this line

```<code> WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));
</code>```

I think it should be

```<code>WeatherStation z = new WeatherStation(split[0], split[1], Double.parseDouble(split[2]), Double.parseDouble(split[3]));
</code>```

Title: Java coursework questions

Body:
I'm an undergraduate student and I'm looking for help with troubleshooting the code I'm writing for my coursework.

import weather.WeatherData;
import Weather.data.classes.WeatherReading;
import Weather.data.classes.WeatherStation;

/**
 * QUESTION 01
 *
 * If you decide to answer question 01 then the main method below should be used as the entry point for your application
 * You may use as many other classes as you feel necessary as long as all code is supplied
 *
 * Remember to add -Xmx1024m to the VM arguments using menu run --> run configurations in eclipse
 */
public class Answer01 {
    public static void main(String[] args) {
        System.out.println("Question 01");
        /*
         * Add your code below
         */
        WeatherStation x = new WeatherStation("site", "a", 1.1, 1.0);
        WeatherReading y = new WeatherReading(1,2,3,4,5,6);
        String line[] = WeatherData.getData();
        ArrayList<WeatherStation>weatherSize = new ArrayList<>();
        for(int i = 1; i < line.length; i++){
        String [] split = line[i].split(",");
        WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));
        weatherSize.add(z);
        }

        System.out.println(weatherSize.size() + " test");

    }
}

The problem I'm having here is that weatherSize.size() is printing out 0 instead of the correct answer which is 136.

The code draws data from a JAR file called weather.WeatherData and I created two classes which have getters and setters and toString() methods, called WeatherStation and WeatherReading.

The jar file is library item called WeatherData.jar and it records weather data recorded at different locations in the uk.

String[] weatherData = WeatherData.getData();

Returns an array of string and the first element at index 0 contains header information.

Element 0: SiteId,SiteName,Latitude,Longitude,Year,Month,Date,Hour,WindSpeed,Temperature
Element 1:
3002,BALTASOUND (3002),60.7490,-0.8540,2015,01,01,0,21,8.70

When I run my code for Answer01 it simply says: 0 test

    package Weather.data.classes;

    public class WeatherStation {
    public String siteId;
    public String siteName;
    public double latitude;
    public double longitude;

    public WeatherStation(String siteId, String siteName, double latitude, double longitute){
        super();
        this.siteId = siteId;
        this.siteName = siteName;
        this.latitude = latitude;
        this.longitude = longitude;
        }
    }

And WeatherReading:

package Weather.data.classes;

public class WeatherReading {
    public int year;
    public int month;
    public int date;
    public int hour;
    public int windSpeed;
    public int temperature;

    public WeatherReading(int year, int month, int date, int hour, int windSpeed, int temperature){
        this.year = year;
        this.month = month;
        this.date = date;
        this.hour = hour;
        this.windSpeed = windSpeed;
        this.temperature = temperature;
    }
}

Body:
My suggestion would be to check the length of the line array which is read from the file

String line[] = WeatherData.getData();
System.out.println("Number of lines : " + line.length);

This way you will know if the file is being read correctly.
Can you also check this line

 WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));

I think it should be

WeatherStation z = new WeatherStation(split[0], split[1], Double.parseDouble(split[2]), Double.parseDouble(split[3]));