问:
exscript ssh on python
Im having problem with the exscript, i want to ssh to my cisco switches, but im having some trouble

I wrote 2 scripts,

with this one I dont have any problem, I can change the default gateway just by running the script and entering the user and password:

```<code>from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()
enter code here`conn = SSH2()
conn.connect('192.168.86.12')
conn.login(account)
conn.execute('conf t')
conn.execute('no ip default-gateway')
conn.execute('ip default-gateway 192.168.68.10')

print "Response was:", repr(conn.response)
conn.send('exit\r')
conn.close()
</code>```

But the problem comes here. I want to make it automatic, I dont want to enter the user and password by hand.
So I wrote this script,

```<code>from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

#account = read_login()
conn = SSH2()
conn.connect('192.168.86.12')
conn.login('user','password')
conn.execute('conf t')
conn.execute('no ip default-gateway')
conn.execute('ip default-gateway 192.168.68.10')

print "Response was:", repr(conn.response)
conn.send('exit\r')
conn.close()
</code>```

But it gives me this error output..

```<code>Traceback (most recent call last):
File "nn.py", line 7, in <module>
conn.login('user','password')
File "/usr/local/lib/python2.7/dist-packages/Exscript-DEVELOPMENT-py2.7.egg/Exscript/protocols/Protocol.py", line 591, in login
with self._get_account(account) as account:
File "/usr/local/lib/python2.7/dist-packages/Exscript-DEVELOPMENT-py2.7.egg/Exscript/protocols/Protocol.py", line 567, in _get_account
account.__enter__()
AttributeError: 'str' object has no attribute '__enter__'
</code>```

ps: I have tried also with paramiko, but it doesnt allow me to run multiple commands.

答:
I am new in this stuff and getting lot of hard time in my job,hope you guys help in this.

While login in multi nodes insert a certain commands to reconfirm the status of links and this should be document in a "txt" file or "log" file for confirmation
I reached till below

```<code>from Exscript.protocols import SSH2
from Exscript.util.file import get_hosts_from_file
from Exscript import Account

accounts = [Account('myuser', 'mypassword')]
conn = SSH2()
hosts = get_hosts_from_file('myhosts.txt')

def do_something(job, host, conn):
    conn.execute('sh int description | i PE')

start(hosts, accounts, do_something)
conn.send('exit\r')
conn.close()
</code>```

Title: exscript ssh on python

Body:
Im having problem with the exscript, i want to ssh to my cisco switches, but im having some trouble

I wrote 2 scripts,

with this one I dont have any problem, I can change the default gateway just by running the script and entering the user and password:

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()
enter code here`conn = SSH2()
conn.connect('192.168.86.12')
conn.login(account)
conn.execute('conf t')
conn.execute('no ip default-gateway')
conn.execute('ip default-gateway 192.168.68.10')

print "Response was:", repr(conn.response)
conn.send('exit\r')
conn.close()

But the problem comes here. I want to make it automatic, I dont want to enter the user and password by hand.
So I wrote this script,

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

#account = read_login()
conn = SSH2()
conn.connect('192.168.86.12')
conn.login('user','password')
conn.execute('conf t')
conn.execute('no ip default-gateway')
conn.execute('ip default-gateway 192.168.68.10')

print "Response was:", repr(conn.response)
conn.send('exit\r')
conn.close()

But it gives me this error output..

Traceback (most recent call last):
File "nn.py", line 7, in <module>
conn.login('user','password')
File "/usr/local/lib/python2.7/dist-packages/Exscript-DEVELOPMENT-py2.7.egg/Exscript/protocols/Protocol.py", line 591, in login
with self._get_account(account) as account:
File "/usr/local/lib/python2.7/dist-packages/Exscript-DEVELOPMENT-py2.7.egg/Exscript/protocols/Protocol.py", line 567, in _get_account
account.__enter__()
AttributeError: 'str' object has no attribute '__enter__'

ps: I have tried also with paramiko, but it doesnt allow me to run multiple commands.

Body:
I am new in this stuff and getting lot of hard time in my job,hope you guys help in this.

While login in multi nodes insert a certain commands to reconfirm the status of links and this should be document in a "txt" file or "log" file for confirmation
I reached till below

from Exscript.protocols import SSH2
from Exscript.util.file import get_hosts_from_file
from Exscript import Account

accounts = [Account('myuser', 'mypassword')]
conn = SSH2()
hosts = get_hosts_from_file('myhosts.txt')

def do_something(job, host, conn):
    conn.execute('sh int description | i PE')

start(hosts, accounts, do_something)
conn.send('exit\r')
conn.close()


来源: stackexchange

问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答:
```<code>str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))
</code>```

That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

ContentLicense: CC BY-SA 4.0

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

Body:
str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))

That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

ContentLicense: CC BY-SA 2.5


问:
How can I test if an object inherits or is a member of a generic class?
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

```<code>class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true
</code>```

答:
I don't think a language feature exists for you to do this, because it's not useful to just know that an object is a subclass of, or C itself, without knowing the generic type parameters.

I mean, what are you gonna do after knowing that, yes, someObj is indeed of type C<Something>, but not what Something is? You can't do anything with someObject. You can't cast it so you can't access any members of it.

Swift's generics is very very strict, unlike Java, who just throws generic types out of the window at runtime...

If you insist that you want to do this, your only option is to use the hack you mentioned.

Or, if you just want to check whether a is C itself, not any of its subclasses, you can use this (just for fun):

```<code>func f(a: Any) -> Bool {
    let regex = try! NSRegularExpression(pattern: "C<.+>")
    let typeString = String(describing: type(of: a))
    let range = NSRange(location: 0, length: typeString.characters.count)
    let matchRange = regex.rangeOfFirstMatch(in: typeString, range: range)
    return range.toRange() == matchRange.toRange()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true

Body:
I don't think a language feature exists for you to do this, because it's not useful to just know that an object is a subclass of, or C itself, without knowing the generic type parameters.

I mean, what are you gonna do after knowing that, yes, someObj is indeed of type C<Something>, but not what Something is? You can't do anything with someObject. You can't cast it so you can't access any members of it.

Swift's generics is very very strict, unlike Java, who just throws generic types out of the window at runtime...

If you insist that you want to do this, your only option is to use the hack you mentioned.

Or, if you just want to check whether a is C itself, not any of its subclasses, you can use this (just for fun):

func f(a: Any) -> Bool {
    let regex = try! NSRegularExpression(pattern: "C<.+>")
    let typeString = String(describing: type(of: a))
    let range = NSRange(location: 0, length: typeString.characters.count)
    let matchRange = regex.rangeOfFirstMatch(in: typeString, range: range)
    return range.toRange() == matchRange.toRange()
}


问:
Call Kotlin inline function from Java
Exceptions.kt:

```<code>@Suppress("NOTHING_TO_INLINE")
inline fun generateStyleNotCorrectException(key: String, value: String) =
        AOPException(key + " = " + value)
</code>```

In kotlin:

```<code>fun inKotlin(key: String, value: String) {
    throw generateStyleNotCorrectException(key, value) }
</code>```

It works  in kotlin and the function is inlined.

But when used in Java code, It just cannot be inlined,
 and still a normal static method call (seen from the decompiled contents).

Something like this:

```<code>public static final void inJava(String key, String value) throws AOPException {
    throw ExceptionsKt.generateStyleNotCorrectException(key, value);
// when decompiled, it has the same contents as before , not the inlined contents.
}
</code>```

答:
The inlining that's done by the Kotlin compiler is not supported for Java files, since the Java compiler is unaware of this transformation (see this answer about why reified generics do not work from Java at all).

As for other use cases of inlining (most commonly when passing in a lambda as a parameter), as you've already discovered, the bytecode includes a public static method so that the inline function can be still called from Java. In this case, however, no inlining occurs.

Title: Call Kotlin inline function from Java

Body:
Exceptions.kt:

@Suppress("NOTHING_TO_INLINE")
inline fun generateStyleNotCorrectException(key: String, value: String) =
        AOPException(key + " = " + value)

In kotlin:

fun inKotlin(key: String, value: String) {
    throw generateStyleNotCorrectException(key, value) }

It works  in kotlin and the function is inlined.

But when used in Java code, It just cannot be inlined,
 and still a normal static method call (seen from the decompiled contents).

Something like this:

public static final void inJava(String key, String value) throws AOPException {
    throw ExceptionsKt.generateStyleNotCorrectException(key, value);
// when decompiled, it has the same contents as before , not the inlined contents.
}


问:
CSS KeyFrame effects
I want my elements to fade in then 2 lines comming out of the circle, one to the left and one to the right.

But All I can't get is: Everytime I try to make the lines show up, it shrinks the whole thing, I want to fix the circle in the middle then make the lines (container) start to "grow".

Already set it to absolute but didn't make it :\

Code Running: Codepen.io

答:
You could do that using pseudo selector :before and :after to create smooth CSS3 animation instead of adding different class for each elements,

.container{
 width:200px;
 height:auto;
 text-align:center;
 position:relative;
 top:10px;
}
.container > span{
 display:block;
 position:relative;
}
.container:before{
 content:'';
 position:absolute;
 width:10px;
 height:10px;
 background:blue;
 z-index:9;
 top:-10px;
 border-radius:50%;
 animation:opt 2s ease forwards;
 opacity:0;
}
.container:after{
 content:'';
 position:absolute;
 width:10px;
 height:10px;
 background:blue;
 z-index:9;
 bottom:-12px;
 border-radius:50%;
 animation:opt 2s ease forwards;
 opacity:0;
}
@keyframes opt{
 from{
  opacity:0;
 }
 to{
  opacity:1;
 }
}
.container > span:before{
 content:'';
 position:absolute;
 width:0px;
 height:2px;
 background:#111;
 z-index:7;
 bottom:-10px;
 right:50%;
 transform:translate(0,-50%);
 transition:1s ease;
 animation:wdth 2s ease forwards 1s;
}
.container > span:after{
 content:'';
 position:absolute;
 width:0px;
 height:2px;
 background:#111;
 z-index:7;
 top:-5px;
 left:50%;
 transition:1s ease;
 animation:wdth 2s ease forwards 1s;
}
@keyframes wdth{
 from{
  width:0px;
 }
 to{
  width:50px;
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <span>Ghaleon Games</span>
</div></code>```

Title: CSS KeyFrame effects

Body:
You could do that using pseudo selector :before and :after to create smooth CSS3 animation instead of adding different class for each elements,

.container{
 width:200px;
 height:auto;
 text-align:center;
 position:relative;
 top:10px;
}
.container > span{
 display:block;
 position:relative;
}
.container:before{
 content:'';
 position:absolute;
 width:10px;
 height:10px;
 background:blue;
 z-index:9;
 top:-10px;
 border-radius:50%;
 animation:opt 2s ease forwards;
 opacity:0;
}
.container:after{
 content:'';
 position:absolute;
 width:10px;
 height:10px;
 background:blue;
 z-index:9;
 bottom:-12px;
 border-radius:50%;
 animation:opt 2s ease forwards;
 opacity:0;
}
@keyframes opt{
 from{
  opacity:0;
 }
 to{
  opacity:1;
 }
}
.container > span:before{
 content:'';
 position:absolute;
 width:0px;
 height:2px;
 background:#111;
 z-index:7;
 bottom:-10px;
 right:50%;
 transform:translate(0,-50%);
 transition:1s ease;
 animation:wdth 2s ease forwards 1s;
}
.container > span:after{
 content:'';
 position:absolute;
 width:0px;
 height:2px;
 background:#111;
 z-index:7;
 top:-5px;
 left:50%;
 transition:1s ease;
 animation:wdth 2s ease forwards 1s;
}
@keyframes wdth{
 from{
  width:0px;
 }
 to{
  width:50px;
 }
}

<div class="container">
 <span>Ghaleon Games</span>
</div>


问:
asynchronous .js file loading syntax
I noticed that there seems to be a couple of slightly different syntaxes for loading js files asynchronously, and I was wondering if there's any difference between the two, or if they both pretty much function the same. I'm guessing they work the same, but just wanted to make sure one method isn't better than the other for some reason. :)

Method One

```<code>(function() {
    var d=document,
    h=d.getElementsByTagName('head')[0],
    s=d.createElement('script');
    s.type='text/javascript';
    s.src='/js/myfile.js';
    h.appendChild(s);
})(); /* note ending parenthesis and curly brace */
</code>```

Method Two (Saw this in Facebook's code)

```<code>(function() {
    var d=document,
    h=d.getElementsByTagName('head')[0],
    s=d.createElement('script');
    s.type='text/javascript';
    s.async=true;
    s.src='/js/myfile.js';
    h.appendChild(s);
}()); /* note ending parenthesis and curly brace */
</code>```

答:
I played around with this and created a library for this that includes support for firing a callback when the script eventually loads.

```<code>Sigma.async_script_load('http://example.com/underscore-min.js', '_', function() {
  _([1,2,3,2,3,1]).uniq();
});
</code>```

https://github.com/ssoroka/sigma

Title: asynchronous .js file loading syntax

Body:
I noticed that there seems to be a couple of slightly different syntaxes for loading js files asynchronously, and I was wondering if there's any difference between the two, or if they both pretty much function the same. I'm guessing they work the same, but just wanted to make sure one method isn't better than the other for some reason. :)

Method One

(function() {
    var d=document,
    h=d.getElementsByTagName('head')[0],
    s=d.createElement('script');
    s.type='text/javascript';
    s.src='/js/myfile.js';
    h.appendChild(s);
})(); /* note ending parenthesis and curly brace */

Method Two (Saw this in Facebook's code)

(function() {
    var d=document,
    h=d.getElementsByTagName('head')[0],
    s=d.createElement('script');
    s.type='text/javascript';
    s.async=true;
    s.src='/js/myfile.js';
    h.appendChild(s);
}()); /* note ending parenthesis and curly brace */

Body:
I played around with this and created a library for this that includes support for firing a callback when the script eventually loads.

Sigma.async_script_load('http://example.com/underscore-min.js', '_', function() {
  _([1,2,3,2,3,1]).uniq();
});

https://github.com/ssoroka/sigma


问:
How to create bottom navigation bar similar to instagram
I am an android newbie trying to create a bottom navigation bar for my new android app similar to one there in Instagram. Like this  where clicking on the search icon adds a search bar in action bar.
I am building an app for reminding the user about his medical appointments which has three navigation tabs at the bottom. I have created till this  after this I am stuck. Should I use three activities to display the content of corresponding tabs or fragments and how can I achieve that.

I need a recyclerview to display appointments. How can I display the search bar only when the search icon at bottom is clicked.
 Have searched a lot on achieving this but could not find anything useful.

Any suggestions for code or library which achieves the same would be great help thanks.

答:
If you want a library for BottomBar here's one.
You have to control Visibility of your SearchBar on the click of that bottom bar item. If you are trying to implement your own searchBar then check out this links link1 link2</p>


问:
Printing elements in arrays only once and each on a new line
I'm trying to print all the elements in an array in a new line.

however when I'm trying to print, it comes up like this: (example)

```<code>array = [1,2,3,4];
for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
}
</code>```

prints:

```<code>1,

1,2,

1,2,3,

1,2,3,4,
</code>```

How do I fix it?

答:
this answers your specific question:</p>

```<code> int[] array = {1,2,3,4};
               for (int i = 0; i < array.length; i++) {
               System.out.print(array[i]);
               System.out.print(" ");

               }
</code>```

Body:
I'm trying to print all the elements in an array in a new line.

however when I'm trying to print, it comes up like this: (example)

array = [1,2,3,4];
for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
}

prints:

1,

1,2,

1,2,3,

1,2,3,4,

How do I fix it?

Body:
this answers your specific question:

 int[] array = {1,2,3,4};
               for (int i = 0; i < array.length; i++) {
               System.out.print(array[i]);
               System.out.print(" ");

               }


问:
SQL multiples select and group by using "first 1"
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

```<code>---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------
</code>```

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

答:
First one by what order, specifically?

```<code>WITH TYPES AS
(
  SELECT TYPE, COUNT(*) AS 'COUNT' FROM EXAMPLE GROUP BY TYPE
)
SELECT
  TYPE,
  (SELECT TOP 1 PROD_NAME FROM EXAMPLE e WHERE e.TYPE = t.TYPE ORDER BY COD ASC) AS 'FIRST',
  COUNT
FROM TYPES t
</code>```

This results in the following:

```<code>TYPE | FIRST    | COUNT
-----|----------|------
03   | MASTER 0 | 4
05   | TAPE 01  | 3
</code>```

This what you're after?

Body:
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

Body:
First one by what order, specifically?

WITH TYPES AS
(
  SELECT TYPE, COUNT(*) AS 'COUNT' FROM EXAMPLE GROUP BY TYPE
)
SELECT
  TYPE,
  (SELECT TOP 1 PROD_NAME FROM EXAMPLE e WHERE e.TYPE = t.TYPE ORDER BY COD ASC) AS 'FIRST',
  COUNT
FROM TYPES t

This results in the following:

TYPE | FIRST    | COUNT
-----|----------|------
03   | MASTER 0 | 4
05   | TAPE 01  | 3

This what you're after?


问:
jQuery selector intermittent working, why?
I simply want to manipulate the elements within the #content div, but $('#content') doesn't seem to work, and yet in other places it does! My relevant code is very simple:

HTML

```<code><body>
  <input type='button' value='Save design' id='save'  />
  <div id="content" style="height: 200px; width:600px;border: 1px solid black;" class='whatev'></div>
</body>
</code>```

Script

```<code>$(document).ready(function(){
   $('#save').click(function(e){
     alert( document.getElementById('content').id); // this works!
     alert($("#content").length); // this works! it outputs "1"
     alert($("#content").id); // this does NOT work - undefined, why?
     //end save function
   });

    $('#content').click(function(e){
       // do stuff // ALL of this works!
    });
});
</code>```

That is it. If you notice, it does work in some places (the entire click function bound to it is perfectly fine), but where it doesn't work, it strangely does still exist because length = 1. I tried using context as well to search the div, just in case, (using $('#content','body')), but no use.

答:
what led me to this page is

I have this div with id LING_a_00224.s03

```<code><div id="LING_a_00224.s03" ></div>
</code>```

and when I use jquery selector to get it

```<code>$("#LING_a_00224.s03")
</code>```

I got not element (jquery selector not working)

thats because the dot (.) in the id

jquery will interpret it as  All elements with id="LING_a_00224" and class="s03", not All elements with id="LING_a_00224.s03"

so make sure that id selector does not contains jquery selector symbols like (.)

or
if you don't have control over elements  ids, you can do

```<code>selector=document.getElementById("LING_a_00224.s03");//JQuery selector sometimes fails because id may contains dot on it like #fn12.e2e
$(selector).jqueryFunction()// wrap the JavaScript object into $() to convert it to jquery object
</code>```

hope this helps you

Body:
I simply want to manipulate the elements within the #content div, but $('#content') doesn't seem to work, and yet in other places it does! My relevant code is very simple:

HTML

  <input type='button' value='Save design' id='save'  />

Script

$(document).ready(function(){
   $('#save').click(function(e){
     alert( document.getElementById('content').id); // this works!
     alert($("#content").length); // this works! it outputs "1"
     alert($("#content").id); // this does NOT work - undefined, why?
     //end save function
   });

    $('#content').click(function(e){
       // do stuff // ALL of this works!
    });
});

That is it. If you notice, it does work in some places (the entire click function bound to it is perfectly fine), but where it doesn't work, it strangely does still exist because length = 1. I tried using context as well to search the div, just in case, (using $('#content','body')), but no use.

Body:
what led me to this page is

I have this div with id LING_a_00224.s03

<div id="LING_a_00224.s03" ></div>

and when I use jquery selector to get it

$("#LING_a_00224.s03")

I got not element (jquery selector not working)

thats because the dot (.) in the id

jquery will interpret it as  All elements with id="LING_a_00224" and class="s03", not All elements with id="LING_a_00224.s03"

so make sure that id selector does not contains jquery selector symbols like (.)

or
if you don't have control over elements  ids, you can do

selector=document.getElementById("LING_a_00224.s03");//JQuery selector sometimes fails because id may contains dot on it like #fn12.e2e
$(selector).jqueryFunction()// wrap the JavaScript object into $() to convert it to jquery object

hope this helps you


问:
Having Trouble with aligning a Hamburger Menu and Two Images in one header
I am working on creating what I thought was a simple header!

I have my hamburger menu on the far left, one image right next to the hamburger, on the far right side one more image and a header bottom border.

Here is an image of what I am trying to create:

I am having a very difficult time getting all three images on one line with a space in between the two images. I want the three to be scalable so that if it is viewed on a smaller screen they don't just stack up on top of each other. I also want them to be even and vertically centered.

A bonus fix would be if someone knew how to create the layered look of my far right image with the border showing underneath, but this is not my priority at the moment.

Here is my CSS:

```<code>body {
font-family: "Quicksand", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: absolute;
z-index: 1;
top: 0;
left: 0;
background-color: #ffffff;
overflow-x: hidden;
padding-top: 70px;
transition: 0.5s;
opacity: 0.8;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 20px;
color: #000000;
display: block;
transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
color: #E1E0E1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
padding-top:40px;
}

.openbtn {
background-color: #fffff;
margin-right: 30px;
margin-top: 0;
padding-top: 0;
height: 55px;
}

.openbtn a:active{
color: #ffffff;
}

header {
border-bottom: 1px solid #E1E0E1;
overflow:auto;
margin-left: 35px;
margin-right: 35px;
height: 90px;

}

h1 {
margin-top: 0;
background-color: #ffffff;
margin-right: 0;
}

h1, h2, .openbtn {
display:inline-block;
vertical-align: middle;
}

@media only screen and (max-device-width: 540px) {
h1 {width: 100%;}
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</code>```

Here is my HTML:

```<code><div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">- three</a> <br> <br>
<a href="#">- two</a> <br> <br>
<a href="#">- three</a> <br> <br>
<a href="#">- four</a> <br> <br>
<a href="#">- fivr</a> <br> <br>
</div>

<div style="font-size:30px;cursor:pointer" class="openbtn"
onclick="openNav()">

<img src="hamburger.png"/> </div>

<h1> <img src="lch1.png"/> </h1>

<h2> <img src="lolo1.png"/> </h2>

<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>

</header>
</code>```

答:
Try display: inline-block
So your pictures will be in ohne line and you can them as Display: block elements

Body:
I am working on creating what I thought was a simple header!

I have my hamburger menu on the far left, one image right next to the hamburger, on the far right side one more image and a header bottom border.

Here is an image of what I am trying to create:

I am having a very difficult time getting all three images on one line with a space in between the two images. I want the three to be scalable so that if it is viewed on a smaller screen they don't just stack up on top of each other. I also want them to be even and vertically centered.

A bonus fix would be if someone knew how to create the layered look of my far right image with the border showing underneath, but this is not my priority at the moment.

Here is my CSS:

body {
font-family: "Quicksand", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: absolute;
z-index: 1;
top: 0;
left: 0;
background-color: #ffffff;
overflow-x: hidden;
padding-top: 70px;
transition: 0.5s;
opacity: 0.8;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 20px;
color: #000000;
display: block;
transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
color: #E1E0E1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
padding-top:40px;
}

.openbtn {
background-color: #fffff;
margin-right: 30px;
margin-top: 0;
padding-top: 0;
height: 55px;
}

.openbtn a:active{
color: #ffffff;
}

header {
border-bottom: 1px solid #E1E0E1;
overflow:auto;
margin-left: 35px;
margin-right: 35px;
height: 90px;

}

h1 {
margin-top: 0;
background-color: #ffffff;
margin-right: 0;
}

h1, h2, .openbtn {
display:inline-block;
vertical-align: middle;
}

@media only screen and (max-device-width: 540px) {
h1 {width: 100%;}
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}

Here is my HTML:

×
- three

- two

- three

- four

- fivr


问:
Mongodb Schemas for different types of Posts/Articles
I'm developing an application with Mongodb, Mongoose and Expressjs in which there are articles or posts of different types. For example there's URL post which only includes of a URL or address and doesn't have text inside of it. There's normal posts, Map posts, Image posts and bunch of other types.

Now I want to define the schema of Posts in my Application. I'm a bit confused if I should be defining different schemas for each of these since they should have different attributes and properties when they share some properties or, put all possible properties inside the Post schema and use an attribute with the name of type to specify the type of the post that's been shared.

What's the best practice to do such thing?

答:
It depends on your needs. If you want to run queries on the whole Post collection that can result different types of posts you should use one common schema with a type attribute. If not, go with the separate collections, that makes the system clear and easy to understand.

If you think of use one collection and there are common attributes in each schema you should try the mongoose-schema-extend package. With this you can handle your schemas like classes and do an inheritance.

https://github.com/briankircho/mongoose-schema-extend


问:
Microsoft Excel VBA Scripting: Recursive column matching
```<code>Sub NewMacro()
Dim endRow As Long
endRow = Sheet1.Range("A999999").End(xlUp).Row
For i = 1 To endRow
 If Sheet1.Range("A" & i).Value = Sheet1.Range("F" & i).Value Then
    Sheet1.Range("K" & i).Value = "Yes"     Else
    Sheet1.Range("K" & i).Value = "No"
End If
Next i
End Sub
</code>```

This will compare column A with column F and displays the result in column K.
What I need is if this value is true, then like the above it should compare column B with column G, column C with column H and so on......and should display the results in next column. Please help.

答:
I think you need a loop on the columns:

```<code>Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                End If
            Next c
        Next i
    End With
End Sub
</code>```

This compares column A with F, column B with G, column C with H, column D with I and column E with J.  Results are placed in columns K, L, M, N and O respectively.

This is equivalent to using the formula =IF(A1=F1,"Yes","No") in cell K1 and copying it across and down.

And a version which will update columns with "Yes", but stop as soon as it reaches a "No":

```<code>Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                    Exit For
                End If
            Next c
        Next i
    End With
End Sub
</code>```

Body:
Sub NewMacro()
Dim endRow As Long
endRow = Sheet1.Range("A999999").End(xlUp).Row
For i = 1 To endRow
 If Sheet1.Range("A" & i).Value = Sheet1.Range("F" & i).Value Then
    Sheet1.Range("K" & i).Value = "Yes"     Else
    Sheet1.Range("K" & i).Value = "No"
End If
Next i
End Sub

This will compare column A with column F and displays the result in column K.
What I need is if this value is true, then like the above it should compare column B with column G, column C with column H and so on......and should display the results in next column. Please help.

Body:
I think you need a loop on the columns:

Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                End If
            Next c
        Next i
    End With
End Sub

This compares column A with F, column B with G, column C with H, column D with I and column E with J.  Results are placed in columns K, L, M, N and O respectively.

This is equivalent to using the formula =IF(A1=F1,"Yes","No") in cell K1 and copying it across and down.

And a version which will update columns with "Yes", but stop as soon as it reaches a "No":

Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                    Exit For
                End If
            Next c
        Next i
    End With
End Sub


问:
Read Hibernate entity identity value
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

```<code>class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L
</code>```

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.

答: I can't say 100% no - but I really doubt it since not all Entities are annotated with @Id; there are other variants that can be used such as @EmbeddedId. Given this, can't you just use reflection to get at your id value?

Title: Read Hibernate entity identity value

Body:
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.


问:
Game Maker Networking Issue on Port Bind
I want to create a simple server using GameMaker 1.4. But it's function never works on the first try, no idea why..

```<code>var networkType = network_socket_tcp;
var port = 50000;
var maxClients = 32;
var bufferSize = 1024;
var bufferType = buffer_fixed;
var bufferAlign = 1;

server = network_create_server(networkType, port, maxClients);

global.buffer = buffer_create(bufferSize,bufferType,bufferAlign);
sockets = ds_list_create();

if server s_msg("Server is up! Port: " + string(port));
else s_msg("Server is down!");
</code>```

The message will be "Server down". No matter the port neither the net type.
When I try the same code with a loop, it works on the second try.
Like this:

```<code>var networkType = network_socket_tcp;
var port = 50000;
var maxClients = 32;
var bufferSize = 1024;
var bufferType = buffer_fixed;
var bufferAlign = 1;

server = network_create_server(networkType, port, maxClients);

//////////////////////////////////////////////////////

while (!server && port < 65535){
   port++;
   server = network_create_server(networkType, port, maxClients);
}

//////////////////////////////////////////////////////

global.buffer = buffer_create(bufferSize,bufferType,bufferAlign);
sockets = ds_list_create();

if server s_msg("Server is up! Port: " + string(port));
else s_msg("Server is down!");
</code>```

Here the message will result on "Server up! Port: 50001".
As I said, no matter the port.. it could be set to 50001 at the beginning resulting on create the server to 50002.
Could someone point my mistake?

答: SOLUTION (From user Humayun in GM Forums): network_create_server returns an index from 0, so it can't be checked as false/true since the first index would be 0 which returns false. Explains that on the second try i was creating a second instance to the sever variable indexed as 1, and so returning true.</p>

Body:
I want to create a simple server using GameMaker 1.4. But it's function never works on the first try, no idea why..

var networkType = network_socket_tcp;
var port = 50000;
var maxClients = 32;
var bufferSize = 1024;
var bufferType = buffer_fixed;
var bufferAlign = 1;

server = network_create_server(networkType, port, maxClients);

global.buffer = buffer_create(bufferSize,bufferType,bufferAlign);
sockets = ds_list_create();

if server s_msg("Server is up! Port: " + string(port));
else s_msg("Server is down!");

The message will be "Server down". No matter the port neither the net type.
When I try the same code with a loop, it works on the second try.
Like this:

var networkType = network_socket_tcp;
var port = 50000;
var maxClients = 32;
var bufferSize = 1024;
var bufferType = buffer_fixed;
var bufferAlign = 1;

server = network_create_server(networkType, port, maxClients);

//////////////////////////////////////////////////////

while (!server && port < 65535){
   port++;
   server = network_create_server(networkType, port, maxClients);
}

//////////////////////////////////////////////////////

global.buffer = buffer_create(bufferSize,bufferType,bufferAlign);
sockets = ds_list_create();

if server s_msg("Server is up! Port: " + string(port));
else s_msg("Server is down!");

Here the message will result on "Server up! Port: 50001".
As I said, no matter the port.. it could be set to 50001 at the beginning resulting on create the server to 50002.
Could someone point my mistake?


问:
How do I parse an array/matrix from a text file while preserving its structure?
I am new to python and am trying to write a script that will parse the data contained between each pair of headers in the text file below.

```<code><Keywords>
GTO
</Keywords>
<NumberofNuclei>
2
</NumberofNuclei>
<Nuclear Charges>
6.0
8.0
1.0
1.0
</Nuclear Charges>
<Primitive Exponents>
8.264000000000e+01  1.241000000000e+01  2.824000000000e+00
8.989000000000e-02  2.292000000000e+00  2.292000000000e+00
8.380000000000e-01  8.380000000000e-01  2.920000000000e-01
</Primitive Exponents>
</code>```

My attempt at a code that can do this is shown below. However, I am having difficulty parsing the matrix under Primitive Exponents while preserving its 3x3 structure. I don't want it written as a list.

```<code>with open('toysystem.txt','r') as f:
 data = f.read()
 nc = re.findall(r'<Nuclear Charges>(.*?)</Nuclear Charges>',data,re.DOTALL)
 nc1 = [elem.replace('\n',',').strip(',') for elem in nc]
 non = re.findall(r'<NumberofNuclei>(.*?)</NumberofNuclei>',data,re.DOTALL)
 non1 = int("".join(map(str, non)))
 kw = re.findall(r'<Keywords>(.*?)</Keywords>',data,re.DOTALL)
 kw1 = "".join(map(str, kw)).replace('\n','')
 pe = np.array(re.findall(r'<Primitive Exponents>(.*?)</Primitive Exponents>',data,re.DOTALL))
</code>```

Any ideas on how to approach this problem/modify my code to extract the matrix as is (a 3x3 array)?

Thank you!

答:
You are having trouble with this because findall() returns a list, in this case a list with one element, and numpy.array() reasonably translates a 1-list into an array with one element. Some work is needed to get the string into a 3x3 matrix before you ask numpy to turn it into an array.

```<code>pe_match = re.search(r'<Primitive Exponents>(.*?)</Primitive Exponents>',data,re.DOTALL)
#  Extract the numbers from the enclosing tags and split into 3 lines
matrix = pe_match.group(1).strip("\n").split("\n")
#  Turn each line into a 3-list
matrix2 = [m.split() for m in matrix]
pe = np.array(matrix2)
</code>```

This gives you a 3x3 numpy array of strings.

```<code>array([['8.264000000000e+01', '1.241000000000e+01', '2.824000000000e+00'],
       ['8.989000000000e-02', '2.292000000000e+00', '2.292000000000e+00'],
       ['8.380000000000e-01', '8.380000000000e-01', '2.920000000000e-01']],
      dtype='|S18')
</code>```

That will of course need further conversion before you can use it, but your question was about the matrix structure.

Body:
I am new to python and am trying to write a script that will parse the data contained between each pair of headers in the text file below.

<Keywords>
GTO
</Keywords>
<NumberofNuclei>
2
</NumberofNuclei>
<Nuclear Charges>
6.0
8.0
1.0
1.0
</Nuclear Charges>
<Primitive Exponents>
8.264000000000e+01  1.241000000000e+01  2.824000000000e+00
8.989000000000e-02  2.292000000000e+00  2.292000000000e+00
8.380000000000e-01  8.380000000000e-01  2.920000000000e-01
</Primitive Exponents>

My attempt at a code that can do this is shown below. However, I am having difficulty parsing the matrix under Primitive Exponents while preserving its 3x3 structure. I don't want it written as a list.

with open('toysystem.txt','r') as f:
 data = f.read()
 nc = re.findall(r'<Nuclear Charges>(.*?)</Nuclear Charges>',data,re.DOTALL)
 nc1 = [elem.replace('\n',',').strip(',') for elem in nc]
 non = re.findall(r'<NumberofNuclei>(.*?)</NumberofNuclei>',data,re.DOTALL)
 non1 = int("".join(map(str, non)))
 kw = re.findall(r'<Keywords>(.*?)</Keywords>',data,re.DOTALL)
 kw1 = "".join(map(str, kw)).replace('\n','')
 pe = np.array(re.findall(r'<Primitive Exponents>(.*?)</Primitive Exponents>',data,re.DOTALL))

Any ideas on how to approach this problem/modify my code to extract the matrix as is (a 3x3 array)?

Thank you!

Body:
You are having trouble with this because findall() returns a list, in this case a list with one element, and numpy.array() reasonably translates a 1-list into an array with one element. Some work is needed to get the string into a 3x3 matrix before you ask numpy to turn it into an array.

pe_match = re.search(r'<Primitive Exponents>(.*?)</Primitive Exponents>',data,re.DOTALL)
#  Extract the numbers from the enclosing tags and split into 3 lines
matrix = pe_match.group(1).strip("\n").split("\n")
#  Turn each line into a 3-list
matrix2 = [m.split() for m in matrix]
pe = np.array(matrix2)

This gives you a 3x3 numpy array of strings.

array([['8.264000000000e+01', '1.241000000000e+01', '2.824000000000e+00'],
       ['8.989000000000e-02', '2.292000000000e+00', '2.292000000000e+00'],
       ['8.380000000000e-01', '8.380000000000e-01', '2.920000000000e-01']],
      dtype='|S18')

That will of course need further conversion before you can use it, but your question was about the matrix structure.


问:
How can I split a concatenated xml file and name the extracted files using strings
How do I split a large concatenated xml files into individual xml files with the files named using strings?

input.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>
</code>```

I want to read the strings file="xxxx-yyyyyyyy.XML" and create output files named as xxxx.XML

output xml files:

1001.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>
</code>```

1002.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>
</code>```

1008.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>
</code>```

My preference is to use bash shell tools such as cat, awk, sed and or xml tools such as xmllint or similar, and log stdout and stderr to a logfile.

Appreciate approaches and testable solutions

答:
Consider the following gawk approach (if your input is constructed as in the question, line by line):

```<code>awk '/<?xml version/{ getline dt; getline typedoc;
     if (match(typedoc,/file="([0-9]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS dt ORS typedoc > fn; next;
     }}{ print > fn }
' input.xml 2> err.log
</code>```

Results:

```<code>cat 1001.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>
</code>```

```<code>cat 1002.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>
</code>```

```<code>cat 1008.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>
</code>```

/<?xml version/ - on encountering line /<?xml version/ with xml declaration

getline dt; - capture next line with <!DOCTYPE

getline typedoc; - capture next line with starting type-of-doc tag

if (match(typedoc,/file="([0-9]+)-[^"]+.XML"/,a)) - match file attribute value

the 1st captured group ([0-9]+) will be assigned to the 1st array element a[1]

Body:
How do I split a large concatenated xml files into individual xml files with the files named using strings?

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>

I want to read the strings file="xxxx-yyyyyyyy.XML" and create output files named as xxxx.XML

output xml files:

1001.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>

1002.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>

1008.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>

My preference is to use bash shell tools such as cat, awk, sed and or xml tools such as xmllint or similar, and log stdout and stderr to a logfile.

Appreciate approaches and testable solutions

Body:
Consider the following gawk approach (if your input is constructed as in the question, line by line):

awk '/<?xml version/{ getline dt; getline typedoc;
     if (match(typedoc,/file="([0-9]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS dt ORS typedoc > fn; next;
     }}{ print > fn }
' input.xml 2> err.log

Results:

cat 1001.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1001-20170101.XML" date="20170101">
</type-of-doc>

cat 1002.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1002-20170101.XML" date="20170101">
</type-of-doc>

cat 1008.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type-of-doc SYSTEM "file.dtd" [ ]>
<type-of-doc lang="EN" dtd-version="v1" file="1008-20170101.XML" date="20170101">
</type-of-doc>

/<?xml version/ - on encountering line /<?xml version/ with xml declaration

getline dt; - capture next line with <!DOCTYPE

getline typedoc; - capture next line with starting type-of-doc tag

if (match(typedoc,/file="([0-9]+)-[^"]+.XML"/,a)) - match file attribute value

the 1st captured group ([0-9]+) will be assigned to the 1st array element a[1]


问:
gitignore binary files that have no extension
How can binary files be ignored in git using the .gitignore file?

Example:

```<code>$ g++ hello.c -o hello
</code>```

The "hello" file is a binary file. Can git ignore this file ?

答:
I created a .gitignore file with two entries in GOPATH directory.

```<code>/bin
/pkg
</code>```

It ignore all the compiled developments, currently.

Body:
How can binary files be ignored in git using the .gitignore file?

Example:

$ g++ hello.c -o hello

The "hello" file is a binary file. Can git ignore this file ?

Body:
I created a .gitignore file with two entries in GOPATH directory.

/bin
/pkg

It ignore all the compiled developments, currently.


问:
Overflow not working for (pixi) canvas positioned outside it's parent (offscreen)
On flowen.me, I'm using the PIXI canvas to generate an effect (it's my photo with a scroll effect).

I have tried different elements with overflow: body, div child of body containing all other elements, parent element itself, etc. But the horizontal scroll bar always appears. Whether I use overflow-x or just overflow.

I tested this on my Chrome browser, iPhone SE, latest IOS and on my MacBook Pro. All sharing the same results.

Anyone have a suggestion or workaround?

答:
didn't search correctly before I posted, this gave me the answer:
How to hide canvas content from parent rounded corners in any webkit for Mac?

a position:relative to the element with overflow hidden


问:
Can't start Compute engine after upgrading from Free Trial
I used GCP on a Free Trial for a couple of month and set up and a Compute engine VM, when the Trial budget ended the VM went down and I can't restart it even after upgrading to monthly payments.

Every time I want to restart the VM i get this error:

The default network interface [nic0] is frozen.

I tried to create a new VM, but also got an error:

Google Compute Engine is not ready for use yet in the project. It may take several minutes if Google Compute Engine has just been enabled, or if this is the first time you use Google Compute Engine in the project.

Created a new service account and played with roles, but the result is still the same.

What should I do in this situation?

Thanks in advance!

Best regards, Ivan

答:
This issue looks like a known issue from Google side:

Workaround:
1. Try creating a new VPC network using the following:
https://cloud.google.com/sdk/gcloud/reference/compute/networks/create

Now create a VM instance using the new network

Create a new project under the same billing account and try creating VM using the default network


问:
error: cannot find symbol - working with file scanner loops
What does this error mean? On every line of the code below the try catch block this error occurs. I'm confused as to why this error keeps appearing.

My imports:

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

My method:

```<code>public static void readLists(ArrayList <String> list1, ArrayList <String> list2)

      {
 Scanner list1s;
Scanner list2s;

      try
      {
        list1s = new Scanner(new File("list1.txt"));
        list2s = new Scanner(new File ("list2.txt"));
      }
      catch(FileNotFoundException ex)
      {
        System.out.println("File not found!\n");
      }

      while(list1s.hasNext())
        list1.add(list1s.next());

      while(list2s.hasNext())
        list2.add(list2s.next());

      list1s.close();
      list2s.close();

    }
</code>```

Updated code was from the suggestions in the comments. However, I get the following error:  variable list1s might not have been initialized
      while(list1s.hasNext())

If I do not have the scanner declaration and initialization in the try/catch. Any idea as to why this is happening?

答:
```<code>static Scanner list1s;
static  Scanner list2s;
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)

{

    try
    {
        list1s = new Scanner(new File("list1.txt"));
        list2s = new Scanner(new File ("list2.txt"));
    }
    catch(FileNotFoundException ex)
    {
        System.out.println("File not found!\n");
    }
// Your code
}
</code>```

Just for reference: class and instance variables when declared, are automatically given their default values.

Body:
What does this error mean? On every line of the code below the try catch block this error occurs. I'm confused as to why this error keeps appearing.

My imports:

import java.util.*;
import java.io.*;

My method:

public static void readLists(ArrayList <String> list1, ArrayList <String> list2)

      {
 Scanner list1s;
Scanner list2s;

      try
      {
        list1s = new Scanner(new File("list1.txt"));
        list2s = new Scanner(new File ("list2.txt"));
      }
      catch(FileNotFoundException ex)
      {
        System.out.println("File not found!\n");
      }

      while(list1s.hasNext())
        list1.add(list1s.next());

      while(list2s.hasNext())
        list2.add(list2s.next());

      list1s.close();
      list2s.close();

    }

Updated code was from the suggestions in the comments. However, I get the following error:  variable list1s might not have been initialized
      while(list1s.hasNext())

If I do not have the scanner declaration and initialization in the try/catch. Any idea as to why this is happening?

Body:
static Scanner list1s;
static  Scanner list2s;
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)

{

    try
    {
        list1s = new Scanner(new File("list1.txt"));
        list2s = new Scanner(new File ("list2.txt"));
    }
    catch(FileNotFoundException ex)
    {
        System.out.println("File not found!\n");
    }
// Your code
}

Just for reference: class and instance variables when declared, are automatically given their default values.


问:
Can i publish android studio project on iphone app store?
I am still a beginner and I really don't know much and am working on my first app on android studio.
So is it possible to publish android studio project on iPhone App Store? If not is there any other way to do that?</p>

答:
You cannot publish a packaged compiled .apk Android Package file to an IOS app store. But an IPA file to IOS store

Google Play: - For Google play store you need to register for a  Google play dev console account, plus a stock & rooted version of Android latest OS build phone

See this

Apple Store: - You need to have a Mac, plus an Apple developer license. A code editor like XCode, a know-how of programming language like Swift 3, an SDK toolkit & an iPhone

See Link1 and Link2.


问:
Only show logging info in dev-mode in NodeJS/Browser
I have a javascript class which can be used in both the browser and NodeJS.

Suppose the class looks like this

```<code>class BarFoo {
    lookup() {
         // Do magic
         if (magicFailed && window.DEVELOP) {
             console.log('Show some info to help debugging...');
         }
    }
    ...
}
</code>```

To make this example also work for NodeJS I can imaging that the global
In this example I only show the log message if the app is in developing mode (window.DEVELOP === true). But I would like to use this class also in a nodeJS app, so I don't have a window object. What is the preferred way to set this up for both?

答:
You could do it like this:

Start your app with:

```<code>NODE_ENV=development node app.js
</code>```

Then check it like so:

```<code>const isServer = typeof window === 'undefined'
const isDev = isServer ? process.env.NODE_ENV === 'development' : window.DEVELOP

if (isDev) {
  // ...
}
</code>```

Body:
I have a javascript class which can be used in both the browser and NodeJS.

Suppose the class looks like this

class BarFoo {
    lookup() {
         // Do magic
         if (magicFailed && window.DEVELOP) {
             console.log('Show some info to help debugging...');
         }
    }
    ...
}

To make this example also work for NodeJS I can imaging that the global
In this example I only show the log message if the app is in developing mode (window.DEVELOP === true). But I would like to use this class also in a nodeJS app, so I don't have a window object. What is the preferred way to set this up for both?

Body:
You could do it like this:

Start your app with:

NODE_ENV=development node app.js

Then check it like so:

const isServer = typeof window === 'undefined'
const isDev = isServer ? process.env.NODE_ENV === 'development' : window.DEVELOP

if (isDev) {
  // ...
}


问:
Flask-WTF form not getting data
I'm using Flask-WTF to submit a form but I'm running into some difficulties and I can't seem to find any help or other examples.  My code is below, but here's what I've found so far.  form.validate_on_submit() is not evaluating to true so it is skipping out of that entire block.  Next I tried to see what was happening with the request read by python.  When I printed out the value (after I initialized LoginForm) of "form.username.data" it printed out "None" so it seems like the form isn't getting created correctly?

I checked the post request that the browser is sending and the necessary information is all visible in that request!

Here's my login form code:

```<code>   from flask.ext.wtf import Form
      from wtforms import TextField, PasswordField
      from wtforms.validators import Required

     class LoginForm(Form):
      username = TextField('username', validators = [Required()])
      pin = PasswordField('pin', validators = [Required()])
</code>```

Here's the route logic:

```<code>@app.route('/login', methods = ['GET', 'POST'])
def login():

    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm(request.form)

    print form.errors

    if form.validate_on_submit():
        if form.username is None or form.username == "":
            print "invalid user"
            flash('Invalid login. Please try again.')
            return redirect(url_for('login'))
        user = db.session.query(User).filter_by(username=form.username).filter_by(password=form.pin).first()
        print user
        if user is None:
            flash('User does not exist. Please register.')
            return redirect(url_for('welcome'))

        login_user(user)
        return redirect(url_for('dashboard'))
    print "didn't validate"
    return render_template('login.html', title = 'Sign In', form = form)
</code>```

config code:

```<code>CSRF_ENABLED = True
</code>```

And here's the form HTML:

```<code>{% extends 'base.html' %}

{% block content %}
<h1>Sign In</h1>
<form action="" method="post" name="login">
    {{ form.hidden_tag()}}
    <p>
        Please enter your username:<br>
        {{ form.username }}<br>
    </p>
    <p>
        Please enter your pin:<br>
        {{ form.pin }}<br>
    </p>
    <p><input type="submit" value="Sign In"></p>
</form>
{% endblock %}
</code>```

I've looked at this for days but I'm at a loss for what to do next. Any pointers or anything obvious I'm missing?

答:
Make sure you place the csrf_token inside the form if you're using flask-WTF:</p>

```<code><form method="POST" action="<page for action>">
    {{ name-of-form.csrf_token }}
    ....
    {{ wtf.form_field(name-of-form.name-of-submit-button) }}
</form>
</code>```

Title: Flask-WTF form not getting data

Body:
I'm using Flask-WTF to submit a form but I'm running into some difficulties and I can't seem to find any help or other examples.  My code is below, but here's what I've found so far.  form.validate_on_submit() is not evaluating to true so it is skipping out of that entire block.  Next I tried to see what was happening with the request read by python.  When I printed out the value (after I initialized LoginForm) of "form.username.data" it printed out "None" so it seems like the form isn't getting created correctly?

I checked the post request that the browser is sending and the necessary information is all visible in that request!

Here's my login form code:

   from flask.ext.wtf import Form
      from wtforms import TextField, PasswordField
      from wtforms.validators import Required

     class LoginForm(Form):
      username = TextField('username', validators = [Required()])
      pin = PasswordField('pin', validators = [Required()])

Here's the route logic:

@app.route('/login', methods = ['GET', 'POST'])
def login():

    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm(request.form)

    print form.errors

    if form.validate_on_submit():
        if form.username is None or form.username == "":
            print "invalid user"
            flash('Invalid login. Please try again.')
            return redirect(url_for('login'))
        user = db.session.query(User).filter_by(username=form.username).filter_by(password=form.pin).first()
        print user
        if user is None:
            flash('User does not exist. Please register.')
            return redirect(url_for('welcome'))

        login_user(user)
        return redirect(url_for('dashboard'))
    print "didn't validate"
    return render_template('login.html', title = 'Sign In', form = form)

config code:

CSRF_ENABLED = True

And here's the form HTML:

{% extends 'base.html' %}

{% block content %}

Sign In

<form action="" method="post" name="login">
    {{ form.hidden_tag()}}

        Please enter your username:

        {{ form.username }}

        Please enter your pin:

        {{ form.pin }}

<input type="submit" value="Sign In">

</form>
{% endblock %}

I've looked at this for days but I'm at a loss for what to do next. Any pointers or anything obvious I'm missing?

Body:
Make sure you place the csrf_token inside the form if you're using flask-WTF:

<form method="POST" action="<page for action>">
    {{ name-of-form.csrf_token }}
    ....
    {{ wtf.form_field(name-of-form.name-of-submit-button) }}
</form>


问:
Log-in to Website
I'm trying to create an Excel macro that will log me into this website. I've written macros to log me into to other websites, but this one is somehow different.

When I use the following code to programmatically insert the username and password and then programmatically click the "log-in" button, the webpage comes back with the message

Error: please provide a username and Error: Please provide a
  password

```<code>Sub LogIn()
' Open IE and navigate to the log-in page
    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Visible = True
        .navigate "https://www.prudential.com/login"

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
            DoEvents
        Loop
        Application.Wait (Now + TimeValue("0:00:10"))

' Enter the necessary information on the Login web page and click the submit button
        ie.document.getElementById("username").Value = "abcdef"
        ie.document.getElementById("password").Value = "12345678"
        ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
             DoEvents
        Loop
    End With

' Do stuff

' Quit IE
    ie.Quit
End Sub
</code>```

I can see that my code has inserted the username and password into the webpage boxes, but for some reason after successfully clicking the submit button, the username and password are not being detected.

What code will successfully insert the username and password so that it can be processed by the web page?  You'll know that your code works when you get the following error message:

We are unable to verify your username and password. Please try again.

Thanks for your help!

答:
Try the code below:</p>

```<code>Option Explicit

Const READYSTATE_COMPLETE       As Long = 4
Const URL_String                As String = "https://www.prudential.com/login"

Sub Login()

    Dim IE As Object
    Dim ObjElement As Object

    ' using Late Binding
    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .navigate URL_String
        .Visible = True
    End With

    Do While (IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE)
        DoEvents
    Loop

    IE.document.getElementByid("username").Value = "abcdef"
    IE.document.getElementByid("password").Value = "12345678"

    ' Optional: I didn't need the wait time
    Application.Wait (Now + TimeValue("0:00:01"))

    Set ObjElement = IE.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")
    ObjElement(0).Click

    Set IE = Nothing

End Sub
</code>```

Title: Log-in to Website

Body:
I'm trying to create an Excel macro that will log me into this website. I've written macros to log me into to other websites, but this one is somehow different.

When I use the following code to programmatically insert the username and password and then programmatically click the "log-in" button, the webpage comes back with the message

Error: please provide a username and Error: Please provide a
  password

Sub LogIn()
' Open IE and navigate to the log-in page
    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Visible = True
        .navigate "https://www.prudential.com/login"

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
            DoEvents
        Loop
        Application.Wait (Now + TimeValue("0:00:10"))

' Enter the necessary information on the Login web page and click the submit button
        ie.document.getElementById("username").Value = "abcdef"
        ie.document.getElementById("password").Value = "12345678"
        ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
             DoEvents
        Loop
    End With

' Do stuff

' Quit IE
    ie.Quit
End Sub

I can see that my code has inserted the username and password into the webpage boxes, but for some reason after successfully clicking the submit button, the username and password are not being detected.

What code will successfully insert the username and password so that it can be processed by the web page?  You'll know that your code works when you get the following error message:

We are unable to verify your username and password. Please try again.

Thanks for your help!

Body:
Try the code below:

Option Explicit

Const READYSTATE_COMPLETE       As Long = 4
Const URL_String                As String = "https://www.prudential.com/login"

Sub Login()

    Dim IE As Object
    Dim ObjElement As Object

    ' using Late Binding
    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .navigate URL_String
        .Visible = True
    End With

    Do While (IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE)
        DoEvents
    Loop

    IE.document.getElementByid("username").Value = "abcdef"
    IE.document.getElementByid("password").Value = "12345678"

    ' Optional: I didn't need the wait time
    Application.Wait (Now + TimeValue("0:00:01"))

    Set ObjElement = IE.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")
    ObjElement(0).Click

    Set IE = Nothing

End Sub


问:
ReactiveX how to pause observable
I'm using ReactiveX in iOS/Swift (RxSwift).

Let's say I have an observable:

```<code>let dataUpdates = ...
</code>```

Which I'm subscribed to:

```<code>dataUpdates.subscribeNext({ data in
    // update tableView with data
    // maybe move to a difference cell with an animation
})
</code>```

If I received an update while I'm animating, I don't want to receive the next update until the animation finishes (I don't want to loose the updates that happen during the animation either).

So all I need is to pause the emitting of that dataUpdates observable.

How can I achieve this?

答:
Use BehaviorSubject to create a valve that pauses and resumes the updates. Note that you will then need some backpressure support (i.e. buffering) in dataUpdates for the updates that arrive when the valve is closed.

So in pseudo code (I don't code switft, so excuse my syntax)

```<code>// create a BehaviorSubject with default value true. It will always emit
// the latest value when subscribed to, thus it is kind of a variable
let valve = BehaviorSubject(value: true)

// we are only interested to get one `true` value. When the latest value
// received by the valve is `true`, this will give a value immediately when
// subscribed to. When the latest value is `false`, this will not give
// any events until it is true.
let openValve = valve.filter{$0}.take(1)

// for each data update, pass it through if the valve is open and otherwise
// start waiting for it to turn true
let pauseableDataUpdates = dataUpdates.concatMap{update in openValve.map { _ in update}}

// now when you start rendering, you do
valve.on(.Next(false))

// and after animation is done, you do
valve.on(.Next(true))
</code>```

Title: ReactiveX how to pause observable

Body:
I'm using ReactiveX in iOS/Swift (RxSwift).

Let's say I have an observable:

let dataUpdates = ...

Which I'm subscribed to:

dataUpdates.subscribeNext({ data in
    // update tableView with data
    // maybe move to a difference cell with an animation
})

If I received an update while I'm animating, I don't want to receive the next update until the animation finishes (I don't want to loose the updates that happen during the animation either).

So all I need is to pause the emitting of that dataUpdates observable.

How can I achieve this?

Body:
Use BehaviorSubject to create a valve that pauses and resumes the updates. Note that you will then need some backpressure support (i.e. buffering) in dataUpdates for the updates that arrive when the valve is closed.

So in pseudo code (I don't code switft, so excuse my syntax)

// create a BehaviorSubject with default value true. It will always emit
// the latest value when subscribed to, thus it is kind of a variable
let valve = BehaviorSubject(value: true)

// we are only interested to get one `true` value. When the latest value
// received by the valve is `true`, this will give a value immediately when
// subscribed to. When the latest value is `false`, this will not give
// any events until it is true.
let openValve = valve.filter{$0}.take(1)

// for each data update, pass it through if the valve is open and otherwise
// start waiting for it to turn true
let pauseableDataUpdates = dataUpdates.concatMap{update in openValve.map { _ in update}}

// now when you start rendering, you do
valve.on(.Next(false))

// and after animation is done, you do
valve.on(.Next(true))


问:
Routes rewritten for rails 3
```<code>map.resources :users do |user|
user.resources :votes
user.resources :voteable do |mv|
mv.resources :votes
end
end
</code>```

would be this in rails 3 correct:

```<code>resources :users do
 resources :votes, :books do
  resources :votes

resources :books
resources :users
</code>```

I checked here http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/ and on stackoverflow, but I just wanted to make sure. I am trying to get the thumbs up gem(vote_fu with some modifications) to work, and I think my issues are coming from the routes.rb

答:
The first block would be in rails3:

```<code>resources :users do
  resources :votes
  resources :voteable do
    resources :votes
  end
end
</code>```

You were missing the end statements.

Title: Routes rewritten for rails 3

Body:
map.resources :users do |user|
user.resources :votes
user.resources :voteable do |mv|
mv.resources :votes
end
end

would be this in rails 3 correct:

resources :users do
 resources :votes, :books do
  resources :votes

resources :books
resources :users

I checked here http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/ and on stackoverflow, but I just wanted to make sure. I am trying to get the thumbs up gem(vote_fu with some modifications) to work, and I think my issues are coming from the routes.rb

Body:
The first block would be in rails3:

resources :users do
  resources :votes
  resources :voteable do
    resources :votes
  end
end

You were missing the end statements.


问:
How to change CATextLayer string throughout the video composition?

I want to create a video in which i want to change the text of CATextLayer with every second of video and create a new composition.

答:
You can add animation of text change on your CATextLayer and use AVVideoCompositionCoreAnimationTool for export

here is an example how to use AVVideoCompositionCoreAnimationTool


问:
Store CLLocationCoordinate2D to NSUserDefaults
I am new to iphone development, and i want to store CLLocationCoordinate2D object to NSUserDefaults.
I am Trying

```<code>    [defaults setObject:location forKey:@"userLocation"];
</code>```

But it gives error 'Sending CLLocationCoordinate2D to parameter of incompatible type id'

So How  to store CLLocationCoordinate2D into NSUserDefaults?
Thanks.

答:
As others have said, first convert it into a Dictionary or Data object and then save it as you normally would. In Swift I highly recommend using extensions. Here's what I did:

```<code>extension CLLocationCoordinate2D {

    private static let Lat = "lat"
    private static let Lon = "lon"

    typealias CLLocationDictionary = [String: CLLocationDegrees]

    var asDictionary: CLLocationDictionary {
        return [CLLocationCoordinate2D.Lat: self.latitude,
                CLLocationCoordinate2D.Lon: self.longitude]
    }

    init(dict: CLLocationDictionary) {
        self.init(latitude: dict[CLLocationCoordinate2D.Lat]!,
                  longitude: dict[CLLocationCoordinate2D.Lon]!)
    }

}
</code>```

Body:
I am new to iphone development, and i want to store CLLocationCoordinate2D object to NSUserDefaults.
I am Trying

    [defaults setObject:location forKey:@"userLocation"];

But it gives error 'Sending CLLocationCoordinate2D to parameter of incompatible type id'

So How  to store CLLocationCoordinate2D into NSUserDefaults?
Thanks.

Body:
As others have said, first convert it into a Dictionary or Data object and then save it as you normally would. In Swift I highly recommend using extensions. Here's what I did:

extension CLLocationCoordinate2D {

    private static let Lat = "lat"
    private static let Lon = "lon"

    typealias CLLocationDictionary = [String: CLLocationDegrees]

    var asDictionary: CLLocationDictionary {
        return [CLLocationCoordinate2D.Lat: self.latitude,
                CLLocationCoordinate2D.Lon: self.longitude]
    }

    init(dict: CLLocationDictionary) {
        self.init(latitude: dict[CLLocationCoordinate2D.Lat]!,
                  longitude: dict[CLLocationCoordinate2D.Lon]!)
    }

}


问:
How to create bottom navigation bar similar to instagram
I am an android newbie trying to create a bottom navigation bar for my new android app similar to one there in Instagram. Like this  where clicking on the search icon adds a search bar in action bar.
I am building an app for reminding the user about his medical appointments which has three navigation tabs at the bottom. I have created till this  after this I am stuck. Should I use three activities to display the content of corresponding tabs or fragments and how can I achieve that.

I need a recyclerview to display appointments. How can I display the search bar only when the search icon at bottom is clicked.
 Have searched a lot on achieving this but could not find anything useful.

Any suggestions for code or library which achieves the same would be great help thanks.

答:
The concept of tabs is that you have to have a MainActivity, which will handle let's say 3 fragments. With the code that @Alireza suggested, you will handle the change between fragments. Please look over a tutorial on how to implement Tabs ( like this one here ) . After that, in your "SearchFragment.java" you will build your XML accordingly with your Search bar on top, and recycler view below, or whatever you wish. Suggestion: When using fragments, be sure to have a Context mContext = getActivity(); defined first, as it will be easier for you to implement all the features.

*For you to achieve the bottom tab effect, you can move
 android.support.design.widget.TabLayout
to the bottom of the screen


问:
Infrared output in verilog
I have to design an infrared transmitter using a FPGA and Verilog.

One of the conditions is to send a packet every 10Hz , I have a counter that creates a secondary clock at 10Hz from the master clock (100MHz).
The packet contains Start-Gap-Select-Gap-Right-Gap-Left-Gap-Forward-Gap-Backwards-Gap. I have a FSM that do this transition at the postive edge of the 10Hz secondary clock.
Each of these blocks within the packet has its size, with Gap being just empty space that separates them. The direction blocks have bigger size when selected and smaller otherwise.
With the condition that the receiver has a pulse frequency of 36kHz I have another counter that reduces the master clock to 36kHz which i use to generate the pulse sizes for the Start, Select etc. and make the output led 1 while the counter counts up to that size (for cases start, select..) and 0 for Gap state.

However when I look at the LED through my smartphone camera it shows it is on all the time which is what I expect to see as it should send packets 10 times per second.

The problem is that the car is not moving at all, my question is is this the correct logic of doing the things or I am missing something?
Thanks

Requested code:

The counter for the 36kHz pulse

```<code>always@(posedge CLK) begin
    if(RESET) begin
       Counter <= 0;
        SEC_CLK <= 0;
    end
    else if(Counter == 2778) begin
        Counter <= 0;
        SEC_CLK <= 1'b1;
    end
    else begin
        Counter <= Counter + 1;
        SEC_CLK <= 1'b0;
    end
end
</code>```

The 10Hz counter, don't know whether is good to reduce the 36kHz or use the Master Clock, but it is a nice round number so I used the Master CLock

```<code>always@(posedge CLK) begin
    if(sec_counter == 100000) begin
        sec_counter <= 0;
        send <= 1;
    end
    else begin
        sec_counter <= sec_counter +1;
        send <= 0;
    end
 end`
</code>```

The FSM LOGIC:

```<code>always@(Curr_State) begin
           case(Curr_State)
               1'd0: begin //START
                   Next_State <= 1'd1;
                   Previous_State <= Next_State;
                   max_count <= StartBurstSize;
                   flag <= 0;
               end
               1'd1: begin //GAP
                   if(Previous_State <= 1'd7)
                       Next_State<=1'd0;
                   else
                      Next_State <= Previous_State +1;
                   max_count <= GapSize;
                   flag <= 1;
                                       IR_LED = 1'b1;

                  if(change)
                      Curr_State <= Next_State;
                  else
                      Next_State <= Curr_State;
               end
               1'd2: begin //SELECT
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   max_count <= CarSelectBurstSize;
                   IR_LED = 1'b0;
                   flag <= 0;
                   if(change)
                       Curr_State <= Next_State;
                   else
                       Next_State <= Curr_State;
               end
               1'd3: begin //RIGHT
                   if(BTNR)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                   if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd4: begin //LEFT
                   if(BTNL)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                   if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd5: begin //FORWARD
                   if(BTNU)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                    if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd6: begin //Backwards
                   if(BTND)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                    if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end

          endcase
end
</code>```

SENDING THE PULSES TO THE IR LED

```<code>always@(posedge SEC_CLK) begin
    if(send) begin
        if(Pcounter == max_count) begin //COUNTING BLOCK SIZE
            Pcounter <= 0;
            IR_LED=1'b0;
       end
       else begin
            if(flag)
                IR_LED=1'b0; //GAP
            else
                IR_LED=1'b1;
            Pcounter <= Pcounter+1;
        end
   end
 end
</code>```

答:
I don't know if you still care about this question, but in your case statements you have something like

```<code>  1'd2: begin //SELECT
</code>```

or even

```<code>Previous_State <= 1'd7
</code>```

However, 1'd means a decimal number 1-bit wide, so it cannot ever be anything different than 0 or 1, the most significant bits just get discarded.

Have you tried to simulate this?

Title: Infrared output in verilog

Body:
I have to design an infrared transmitter using a FPGA and Verilog.

One of the conditions is to send a packet every 10Hz , I have a counter that creates a secondary clock at 10Hz from the master clock (100MHz).
The packet contains Start-Gap-Select-Gap-Right-Gap-Left-Gap-Forward-Gap-Backwards-Gap. I have a FSM that do this transition at the postive edge of the 10Hz secondary clock.
Each of these blocks within the packet has its size, with Gap being just empty space that separates them. The direction blocks have bigger size when selected and smaller otherwise.
With the condition that the receiver has a pulse frequency of 36kHz I have another counter that reduces the master clock to 36kHz which i use to generate the pulse sizes for the Start, Select etc. and make the output led 1 while the counter counts up to that size (for cases start, select..) and 0 for Gap state.

However when I look at the LED through my smartphone camera it shows it is on all the time which is what I expect to see as it should send packets 10 times per second.

The problem is that the car is not moving at all, my question is is this the correct logic of doing the things or I am missing something?
Thanks

Requested code:

The counter for the 36kHz pulse

always@(posedge CLK) begin
    if(RESET) begin
       Counter <= 0;
        SEC_CLK <= 0;
    end
    else if(Counter == 2778) begin
        Counter <= 0;
        SEC_CLK <= 1'b1;
    end
    else begin
        Counter <= Counter + 1;
        SEC_CLK <= 1'b0;
    end
end

The 10Hz counter, don't know whether is good to reduce the 36kHz or use the Master Clock, but it is a nice round number so I used the Master CLock

always@(posedge CLK) begin
    if(sec_counter == 100000) begin
        sec_counter <= 0;
        send <= 1;
    end
    else begin
        sec_counter <= sec_counter +1;
        send <= 0;
    end
 end`

The FSM LOGIC:

always@(Curr_State) begin
           case(Curr_State)
               1'd0: begin //START
                   Next_State <= 1'd1;
                   Previous_State <= Next_State;
                   max_count <= StartBurstSize;
                   flag <= 0;
               end
               1'd1: begin //GAP
                   if(Previous_State <= 1'd7)
                       Next_State<=1'd0;
                   else
                      Next_State <= Previous_State +1;
                   max_count <= GapSize;
                   flag <= 1;
                                       IR_LED = 1'b1;

                  if(change)
                      Curr_State <= Next_State;
                  else
                      Next_State <= Curr_State;
               end
               1'd2: begin //SELECT
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   max_count <= CarSelectBurstSize;
                   IR_LED = 1'b0;
                   flag <= 0;
                   if(change)
                       Curr_State <= Next_State;
                   else
                       Next_State <= Curr_State;
               end
               1'd3: begin //RIGHT
                   if(BTNR)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                   if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd4: begin //LEFT
                   if(BTNL)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                   if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd5: begin //FORWARD
                   if(BTNU)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                    if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end
               1'd6: begin //Backwards
                   if(BTND)
                       max_count <= AsserBurstSize;
                   else
                       max_count <= DeAssertBurstSize;
                   Next_State <= 1'd1;
                   Previous_State <= Curr_State;
                   flag <= 0;
                    if(change)
                      Curr_State <= Next_State;
                   else
                      Next_State <= Curr_State;
                       IR_LED = 1'b1;
               end

          endcase
end

SENDING THE PULSES TO THE IR LED

always@(posedge SEC_CLK) begin
    if(send) begin
        if(Pcounter == max_count) begin //COUNTING BLOCK SIZE
            Pcounter <= 0;
            IR_LED=1'b0;
       end
       else begin
            if(flag)
                IR_LED=1'b0; //GAP
            else
                IR_LED=1'b1;
            Pcounter <= Pcounter+1;
        end
   end
 end

Body:
I don't know if you still care about this question, but in your case statements you have something like

  1'd2: begin //SELECT

or even

Previous_State <= 1'd7

However, 1'd means a decimal number 1-bit wide, so it cannot ever be anything different than 0 or 1, the most significant bits just get discarded.

Have you tried to simulate this?


问:
How can I display image and play audio from a URL given in JSON data?
link to JSON data -> http://starlord.hackerearth.com/sureify/cokestudio
On executing the program in browser it displays URL and not the image or audio like this ->

http://hck.re/3Cm0IX

http://hck.re/5dh4D5

http://hck.re/U1bRnt

http://hck.re/eLtjUb

My code:

```<code><body>

<div id="cover_img" width="150px" height="150px">  </div>

<script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response; //request.response contains all our JSON data
        showdata(myjsondata);

    }

    function showdata(data){

        for(var i=0;i<data.length;i++){
            document.write(data[i].cover_image +"<br>");
        }
    }
</script>
</body>
</code>```

答:
You need to create  tags and populate their src property like below:

```<code>function showdata(data){

    for(var i=0;i<data.length;i++){
        document.write("<br/>");
        document.write(data[i].cover_image +"<br>");
        var str = "<IMG src='"+data[i].cover_image+"'/>";
        document.write(str);
        document.write("<br/>");
        str = "<a href='"+data[i].url+"'>"+data[i].song+"</a>";
        document.write(str);
    }
}
</code>```

Body:
You need to create <IMG> tags and populate their src property like below:

function showdata(data){

    for(var i=0;i<data.length;i++){
        document.write("<br/>");
        document.write(data[i].cover_image +"<br>");
        var str = "<IMG src='"+data[i].cover_image+"'/>";
        document.write(str);
        document.write("<br/>");
        str = "<a href='"+data[i].url+"'>"+data[i].song+"</a>";
        document.write(str);
    }
}


问:
Error unused argument (invisible) in CA in r (FactoMineR)
I use the following code:

```<code>library(FactoMineR)
women_work=read.table("http://factominer.free.fr/classical-methods/datasets/women_work.txt", header=TRUE, row.names=1, sep="\t")
</code>```

When I use the following command:
res.ca.col = CA(women_work[,1:3])
I get the graph. However, when I run:

```<code>> res.ca.rows = CA(women_work[,1:3], invisible="col")
Error in CA(women_work[, 1:3], invisible = "col") :
  unused argument (invisible = "col")
</code>```

I get an error. Same for

```<code>> res.ca.col = CA(women_work[,1:3], invisible="row")
Error in CA(women_work[, 1:3], invisible = "row") :
  unused argument (invisible = "row")
</code>```

答:
invisible is not a valid parameter of CA function, but it is for plot.CA

From the FactoMineR documentation:

```<code>CA Usage:
CA(X, ncp = 5, row.sup = NULL, col.sup = NULL,
      quanti.sup=NULL, quali.sup = NULL, graph = TRUE,
      axes = c(1,2), row.w = NULL, excl=NULL)
</code>```

and:

```<code>plot.CA Usage:
plot(x, axes = c(1, 2),
xlim = NULL, ylim = NULL,
invisible = c("none","row","col","row.sup","col.sup","quali.sup"),
...etc. )
</code>```

Here x in the plot() would take a CA object. So you would write something like:

```<code>res.ca.rows = CA(women_work[,1:3])
plot(res.ca.rows, invisible="col")
</code>```

Body:
I use the following code:

library(FactoMineR)
women_work=read.table("http://factominer.free.fr/classical-methods/datasets/women_work.txt", header=TRUE, row.names=1, sep="\t")

When I use the following command:
res.ca.col = CA(women_work[,1:3])
I get the graph. However, when I run:

> res.ca.rows = CA(women_work[,1:3], invisible="col")
Error in CA(women_work[, 1:3], invisible = "col") :
  unused argument (invisible = "col")

I get an error. Same for

> res.ca.col = CA(women_work[,1:3], invisible="row")
Error in CA(women_work[, 1:3], invisible = "row") :
  unused argument (invisible = "row")

Body:
invisible is not a valid parameter of CA function, but it is for plot.CA

From the FactoMineR documentation:

CA Usage:
CA(X, ncp = 5, row.sup = NULL, col.sup = NULL,
      quanti.sup=NULL, quali.sup = NULL, graph = TRUE,
      axes = c(1,2), row.w = NULL, excl=NULL)

and:

plot.CA Usage:
plot(x, axes = c(1, 2),
xlim = NULL, ylim = NULL,
invisible = c("none","row","col","row.sup","col.sup","quali.sup"),
...etc. )

Here x in the plot() would take a CA object. So you would write something like:

res.ca.rows = CA(women_work[,1:3])
plot(res.ca.rows, invisible="col")