问:
How to change the text input color of "prompt" method in Cordova?
Using navigator.dialogs.prompt method, the typing dialog appears on the screen, but the text is white (same color as background) so the user cannot see what is typing.

I'm using pure Cordova. What to do?

答:
You also need to add :

```<code>promptInput.setTextColor(0xff888888);
</code>```

after

```<code>promptInput.setHint(defaultText);
</code>```

Body:
You also need to add :

promptInput.setTextColor(0xff888888);

after

promptInput.setHint(defaultText);


来源: stackexchange

问:
How to append two bytes in python?
Say you have b'\x04' and b'\x00' how can you combine them as b'\x0400'?

ContentLicense: CC BY-SA 4.0

Title: How to append two bytes in python?

Body:
Using python 3:

>>> a = b'\x04'
>>> b = b'\x00'
>>> a+b
b'\x04\x00'

ContentLicense: CC BY-SA 3.0


问:
How do I recover an object if I didn't def it?
I am using Clojure in a REPL. Suppose I execute something like (read-line) which returns a string object, but I don't do anything like (def x (read-line)) which would save that string object anywhere specific.

Is the object hanging around somewhere where I can recover it, and if so how?

答:
The last three results are bound to *1, *2 and *3 and the last exception to *e e.g.

```<code>> (read-line)
> hello world

> *1
"hello world"
</code>```

Body:
The last three results are bound to *1, *2 and *3 and the last exception to *e e.g.

> (read-line)
> hello world

> *1
"hello world"


问:
What simple Eclipse tricks do you know?

Possible Duplicate:

  Hidden features of Eclipse

I've just discovered that if you type sysout then hold ctrl and press space it changes to System.out.println()

答:
you can also indent the code properly.

select the code you want to format and press ctrl +shift+ 'F'

this will indent your data properly.

ContentLicense: CC BY-SA 2.5

Title: What simple Eclipse tricks do you know?


问:
Dynamically adjusted forms inside FieldList
I'm using Flask and Flask-WTF and I need to create a form that contains several blocks (subforms) of a similar structure (like a subform with one SelectField and one TextAreaField). As the docs suggest, I can use FormField together with FieldList to achieve this goal. However, I need to tweak my SelectField's dynamically (changing their choices at runtime according to values in the database). The docs now suggest

Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation.

One can find an example of this approach here. However, FormField is accepting form_class, not an instance (at least, according to the docs), so it seems that these two recipes do not play well together.

Are there any other ideas?

答:
Okay, it's easier than I thought. You have to create those subforms with empty choices, create list of them and then adjust choices inside the list items.

```<code>class UserForm(wtforms.Form):
# must inherit from wtforms.Form, not flask-WTForms'
# see http://stackoverflow.com/questions/15649027/wtforms-csrf-flask-fieldlist
    first_name = StringField('First Name', [validators.DataRequired()])
    last_name = StringField('Last Name', [validators.DataRequired()])
    accepted_policy = BooleanField('Accept Policy')
    experience = SelectField('Experience', coerce=int)

class UsersForm(Form):
    users = FieldList(FormField(UserForm), min_entries=2)

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

    form = UsersForm(users=[{}, {}, {}])
    form.users[0].experience.choices=[(1, 'One'), (2, 'Two')]
    form.users[1].experience.choices = [(1, 'Uno'), (2, 'Du')]
    form.users[2].experience.choices = [(0, 'Zero')]
    return render_template("hello.html", form=form)
</code>```

And here is a template:

```<code>{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

<form method=post>
  <dl>
      {{ form.hidden_tag()}}
      {%  for user_entry_form in form.users %}
          {{ user_entry_form.name }}
    {{ render_field(user_entry_form.first_name) }}
    {{ render_field(user_entry_form.last_name) }}
    {{ render_field(user_entry_form.experience) }}
      {%  endfor %}
  </dl>
  <p><input type=submit value=Go!>
</form>
</code>```

Body:
Okay, it's easier than I thought. You have to create those subforms with empty choices, create list of them and then adjust choices inside the list items.

class UserForm(wtforms.Form):
# must inherit from wtforms.Form, not flask-WTForms'
# see http://stackoverflow.com/questions/15649027/wtforms-csrf-flask-fieldlist
    first_name = StringField('First Name', [validators.DataRequired()])
    last_name = StringField('Last Name', [validators.DataRequired()])
    accepted_policy = BooleanField('Accept Policy')
    experience = SelectField('Experience', coerce=int)

class UsersForm(Form):
    users = FieldList(FormField(UserForm), min_entries=2)

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

    form = UsersForm(users=[{}, {}, {}])
    form.users[0].experience.choices=[(1, 'One'), (2, 'Two')]
    form.users[1].experience.choices = [(1, 'Uno'), (2, 'Du')]
    form.users[2].experience.choices = [(0, 'Zero')]
    return render_template("hello.html", form=form)

And here is a template:

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

<form method=post>
  <dl>
      {{ form.hidden_tag()}}
      {%  for user_entry_form in form.users %}
          {{ user_entry_form.name }}
    {{ render_field(user_entry_form.first_name) }}
    {{ render_field(user_entry_form.last_name) }}
    {{ render_field(user_entry_form.experience) }}
      {%  endfor %}
  </dl>
  <p><input type=submit value=Go!>
</form>


问:
Display Google location in Android layout
I am using Google Place Picker to get the user current location and send it to the other user in a chat dialog, but what I want is to display that location in the chat dialog as a message element.

How can I do that?

答: My suggestions would be to get the picked location's latitude and longitude, then send it to user/server as per your system congfiguration. Then in other user side, show the google map view in inside chatbox, you can use MapFragment for this, then add location marker at the received latitude and longitude in google map.


答:
Everyone should have a good split/parse function as Zohar Peled linked to.

Another option if you can't use (or want) a UDF.

Example

```<code>Select A.Date
      ,C.RetVal
 From  YourTable A
 Cross Apply (values (col1),(col2),(col3),(col4)) B (Value)
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(B.Value,'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                Cross Apply x.nodes('x') AS B(i)
             ) C
 Where C.RetVal is not null
</code>```

Returns

```<code>Date        RetVal
2017-04-02  txt1
2017-04-02  txt2
2017-04-03  txt1
2017-04-03  txt4
...
</code>```

Title: Return date from value exploded in some columns on SQL Server

Body:
I would like to return the date for each string exploded by slash on SQL Server.

My database table:

id | date       | col1        | col2      | col3  | col4
---+------------+-------------+-----------+-------+------------
1  | 2017-04-02 | /txt1/txt2  |           |       |
2  | 2017-04-03 |             | /txt1/txt4|       |
3  | 2017-04-04 |             |/txt2/txt3 |       |
4  | 2017-04-05 |             |/txt4      |       |/txt5/txt6

Result wanted:

2017-04-02 txt1
2017-04-02 txt2
2017-04-03 txt1
2017-04-03 txt4
2017-04-04 txt2
2017-04-04 txt3
2017-04-05 txt4
2017-04-05 txt5
2017-04-05 txt6

Thank you
Pierre

Body:
Everyone should have a good split/parse function as Zohar Peled linked to.

Another option if you can't use (or want) a UDF.

Example

Select A.Date
      ,C.RetVal
 From  YourTable A
 Cross Apply (values (col1),(col2),(col3),(col4)) B (Value)
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(B.Value,'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                Cross Apply x.nodes('x') AS B(i)
             ) C
 Where C.RetVal is not null

Returns

Date        RetVal
2017-04-02  txt1
2017-04-02  txt2
2017-04-03  txt1
2017-04-03  txt4
...


问:
Flash video player that supports streaming m4v files
I'm looking for a Flash video player that is able to stream m4v files on all browsers. Example file:
http://podcasts.cnn.net/cnn/big/podcasts/cnnnewsroom/video/2010/11/23/the.daily.11.23.cnn.m4v

Unfortunately, I can't convert the format since it originates from 3rd party servers. I can't rely on HTML5 video since not all browsers support this format and the encoding it contains.

I've already tried several players such as JW Player, Kaltura, Video JS, Projekktor, and more. Testing them with Firefox and IE, some of them couldn't play the m4v file at all, while others downloaded the entire file before starting to play it.

If an open source solution is available, and one that has a powerful JavaScript API, that would be great.

Thanks!

答: You can use VLC or write your own code.</p>

Body: You can use VLC or write your own code.


问:
Varnish cache doesn't hit first time
I just learned and implemented varnish reverse proxy to increase my website speed.

Everything works fine but something minor bothers me.

For some reason, when I check page TTFB for the first time, I get .999s, however, when I rerun the test the number drops to .237s.

I use the following website to check TTFB:
https://www.webpagetest.org

and my website is:
https://www.findfestival.com/

It makes me wonder if the first request to the website hits the cache. When I use curl I can see x-varnish but still it's strange that first time clicking on links are slower compared to the second time clicking on them. (specifically on mobile)

Can you please help me understand why first time Varnish cache doesn't hit?

This is my default.vcl is:

Thanks,

PS, I have seen this post and already tried the solution with no luck!

Varnish Cache first time hit

答:
Seeing how you have X-Mod-Pagespeed in your headers and minimalistic VCL, the conclusion is that you need to take a look at Downstream Caching and make sure that PageSpeed would not send Cache-Control: max-age=0, no-cache which breaks Varnish caching for the most part.

In my own experience, Pagespeed does not play well with Varnish even with downstream caching configuration applied.

It "loves" to send the aforementioned header no matter what. Even if you manage to turn this behaviour off, it results in PageSpeed's own assets not having proper Cache-Control headers plus a few more interesting issues like causing Varnish "hit-for-pass" when rebeaconing has to take place - which is really bad and breaks caching further.

Also have a look at possible configurations. You might want to put PageSpeed at your SSL terminator level (option #1) - that way you don't need Downstream Cache configuration and PageSpeed will be "in front" of Varnish.

Title: Varnish cache doesn't hit first time


问:
SQL QUERY: Can I get different row values and display it as different columns when testing query?
this is a sample of the database I am working

I want something like this, displaying specific rows as a column

答:
The problem here is that when you display a value from row B as a column attached to row A, you need to specify why is that value exactly from row B (rather than, say, row C). You can wing it to an extent, but this is increasingly deprecated in MySQL (and not possible in other flavors of SQL). For this same reason, if you GROUP BY some columns, you shouldn't specify a non-GROUP or non-aggregate value in the SELECT; otherwise it's ambiguous which value the engine should pick.

So what you ask is the same thing as doing a JOIN for each column:

```<code>SELECT maintable.*,
    b.location_nr AS col2,
    c.location_nr AS col4,
    d.location_nr AS col5
FROM maintable
    LEFT JOIN maintable AS b ON (... AND b.type = 2)
    LEFT JOIN maintable AS c ON (... AND c.type = 4)
    LEFT JOIN maintable AS d ON (... AND d.type = 5)
WHERE maintable.type = 42;
</code>```

So here you get all records of type 42, then, if one of these (Juan) has also a record of type 2 in the same table, then it will appear in column col2, and so on.

If such a row is not present, col2 will be valued NULL. If more than one row appears, then you will get multiple rows.

Another alternative:

```<code>SELECT ...,
   (SELECT location_nr FROM maintable AS b WHERE ... AND b.type = 2) AS col2,
   ...
</code>```

Here, too, you must supply your JOIN conditions for the secondary records to be picked up.

--

That said, you might probably be better off changing the database layout and adding an "attribute" table, only leaving the main information in the primary table.

Body:
The problem here is that when you display a value from row B as a column attached to row A, you need to specify why is that value exactly from row B (rather than, say, row C). You can wing it to an extent, but this is increasingly deprecated in MySQL (and not possible in other flavors of SQL). For this same reason, if you GROUP BY some columns, you shouldn't specify a non-GROUP or non-aggregate value in the SELECT; otherwise it's ambiguous which value the engine should pick.

So what you ask is the same thing as doing a JOIN for each column:

SELECT maintable.*,
    b.location_nr AS col2,
    c.location_nr AS col4,
    d.location_nr AS col5
FROM maintable
    LEFT JOIN maintable AS b ON (... AND b.type = 2)
    LEFT JOIN maintable AS c ON (... AND c.type = 4)
    LEFT JOIN maintable AS d ON (... AND d.type = 5)
WHERE maintable.type = 42;

So here you get all records of type 42, then, if one of these (Juan) has also a record of type 2 in the same table, then it will appear in column col2, and so on.

If such a row is not present, col2 will be valued NULL. If more than one row appears, then you will get multiple rows.

Another alternative:

SELECT ...,
   (SELECT location_nr FROM maintable AS b WHERE ... AND b.type = 2) AS col2,
   ...

Here, too, you must supply your JOIN conditions for the secondary records to be picked up.

--

That said, you might probably be better off changing the database layout and adding an "attribute" table, only leaving the main information in the primary table.


问:
buildroot new fs can't install grub2
I'm traing to use buildroot and compile new embedded system for testing.
Everything looks ok I use last kernel 4.9.16 and buildroot is from 02.2017. After compiling I can't install grub2 there's now grub software on new root file system and second there's now bash in /bin and anywhere? There's only ash shell.
It's weird because the same procedure I made on mint 17 couple days ago and it works like a charm. I changed disk in my laptop and now I'm using fresh manjaro. I don't think this could be a problem because when I compile new system I can't chose bash in menu but I chose grub2 as bootloader.</p>

答:
Regarding bash: Buildroot by default only installs Busybox, which provides a more minimalistic shell called ash, which is sufficient for most purposes. If you really need bash, you can also get it by enabling it in the Buildroot menuconfig.

Regarding grub2, please have a look at the help text of the Grub2 option in Buildroot, it explains how to install it.

Title: buildroot new fs can't install grub2


问:
Regex multiline replacement failing to strip anything
I have a large text file with the following example of text in it. There are many "CHARTS" blocks, probably 200+ in total.

```<code>CHARTS
  Color=14671839
  Layer=7
  [0] Font=MS SAN SERIF,10,0,F,F,
'''other lines'''
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
</code>```

I am trying to strip all blocks where "Layer=7" meaning the above text would end up as

```<code>CHARTS
 Color=14671839

  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
</code>```

I have used the following:

```<code>$contents =~ s/CHARTS(?s)Layer\=7(?s).*?\[28\]\=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,//g;
</code>```

I am not getting any errors BUT nothing is being stripped.

I have spent the last hour playing around with it but am getting nowhere. Can someone point me in the right direction?

Many thanks

答:
The idea is to ignore all CHARTS blocks which have a Layer attribute assigned to something other than 7 from being removed:

```<code>$contents =~ s/CHARTS\R*(^(?!CHARTS) *+(?(?=Layer=(?:7\d+|[^7]))(*SKIP)(*F)|.*)\R)*//gm;
</code>```

Live demo

Body:
I have a large text file with the following example of text in it. There are many "CHARTS" blocks, probably 200+ in total.

CHARTS
  Color=14671839
  Layer=7
  [0] Font=MS SAN SERIF,10,0,F,F,
'''other lines'''
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

CHARTS
 Color=14671839
  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

I am trying to strip all blocks where "Layer=7" meaning the above text would end up as

CHARTS
 Color=14671839

  Layer=4
  [0] Font=MS SAN SERIF,10,0,F,F,
...other lines...
  [28]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

I have used the following:

$contents =~ s/CHARTS(?s)Layer\=7(?s).*?\[28\]\=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,//g;

I am not getting any errors BUT nothing is being stripped.

I have spent the last hour playing around with it but am getting nowhere. Can someone point me in the right direction?

Many thanks

Body:
The idea is to ignore all CHARTS blocks which have a Layer attribute assigned to something other than 7 from being removed:

$contents =~ s/CHARTS\R*(^(?!CHARTS) *+(?(?=Layer=(?:7\d+|[^7]))(*SKIP)(*F)|.*)\R)*//gm;

Live demo


问:
how to add gtk in sublime text 3 to create graphical user interface for c programs
I'm learning c programming language. Almost I completed all the syntaxes and example programs. I want to create graphical user interface for the source code written in C. A lot of browsing in google I found that it is possible with gtk+. Now I'm using Sublime Text 3 to write and compile my C programs. Is there any way to add gtk+ with the sublimt text.

答:
You can use Make if you have it installed on your system. Or if it's just a single .c file, you can quickly use the command line. See this questions on how to compile and run C programs from within sublime text.

To get the CFLAGS and linking flags use:

```<code>pkg-config gtk+-3.0 --cflags --libs
</code>```

As you have not stated the OS you are using I am going to assume Linux, or some Unix.

then:

```<code>gcc -Wall -Wpedantic -Wextra -g $(pkg-config gtk+-3.0 --cflags --libs) gtk.c -o gtk
</code>```

Body:
You can use Make if you have it installed on your system. Or if it's just a single .c file, you can quickly use the command line. See this questions on how to compile and run C programs from within sublime text.

To get the CFLAGS and linking flags use:

pkg-config gtk+-3.0 --cflags --libs

As you have not stated the OS you are using I am going to assume Linux, or some Unix.

then:

gcc -Wall -Wpedantic -Wextra -g $(pkg-config gtk+-3.0 --cflags --libs) gtk.c -o gtk


问:
oauth2-server-php not returning refresh token
Using this oauth2 library for PHP, I am validating a user via client_credentials like this:

server.php

```<code>$server = new OAuth2\Server($storage, [
'access_lifetime' => 3600, // 1 hour
'refresh_token_lifetime' => 50400, // 14 days
]);

$server->addGrantType(new OAuth2\GrantType\ClientCredentials($server->getStorage('client_credentials'), ['always_issue_new_refresh_token' => true])));
</code>```

Then in my endpoint (token.php):

```<code>require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$server->handleTokenRequest($request)->send(); //returns the token object
</code>```

Although a new access_token is returned, no refresh_token is returned:

```<code>{"access_token":"501a3d087db7532d4e4350402f9a5da332d71dfc","expires_in":3600,"token_type":"Bearer","scope":null}
</code>```

How do you get the refresh_token?

答:
This is a normal behaviour.
With the Client Credentials grant type the refresh tokens are useless because the client can get a new access token by asking a new one when he wants.

Moreover I found a closed issue where the author of the library you use clearly explains that there is no bug here.

As mentioned in this answer, you will find in the RFC6749 section 4.4.3 that the refresh token SHOULD NOT be included.

You can also read this question and the accepted answer.

Body:
Using this oauth2 library for PHP, I am validating a user via client_credentials like this:

server.php

$server = new OAuth2\Server($storage, [
'access_lifetime' => 3600, // 1 hour
'refresh_token_lifetime' => 50400, // 14 days
]);

$server->addGrantType(new OAuth2\GrantType\ClientCredentials($server->getStorage('client_credentials'), ['always_issue_new_refresh_token' => true])));

Then in my endpoint (token.php):

require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$server->handleTokenRequest($request)->send(); //returns the token object

Although a new access_token is returned, no refresh_token is returned:

{"access_token":"501a3d087db7532d4e4350402f9a5da332d71dfc","expires_in":3600,"token_type":"Bearer","scope":null}

How do you get the refresh_token?


问:
What is causing Numba's AttributeError: 'NoneType' object has no attribute 'pysig'?
When I try to run this code:

```<code>from numba import njit, int64
from numba.types import List

@njit(int64(List(int64, True)))
def f(a):
    a[0] = 0
    return a[0]

@njit(List(int64)())
def g(): return [f([0])]
</code>```

I get the following. Why is this? How do I make it figure out the types correctly?

```<code>Traceback (most recent call last):
  File "Temp.py", line 9, in <module>
    @njit(List(int64)())
  File "numba\decorators.py", line 172, in wrapper
    disp.compile(sig)
  File "numba\dispatcher.py", line 350, in compile
    flags=flags, locals=self.locals)
  File "numba\compiler.py", line 644, in compile_extra
    return pipeline.compile_extra(func)
  File "numba\compiler.py", line 361, in compile_extra
    return self.compile_bytecode(bc, func_attr=self.func_attr)
  File "numba\compiler.py", line 370, in compile_bytecode
    return self._compile_bytecode()
  File "numba\compiler.py", line 631, in _compile_bytecode
    return pm.run(self.status)
  File "numba\compiler.py", line 251, in run
    raise patched_exception
numba.errors.TypingError: Caused By:
Traceback (most recent call last):
  File "numba\compiler.py", line 243, in run
    res = stage()
  File "numba\compiler.py", line 458, in stage_nopython_frontend
    self.locals)
  File "numba\compiler.py", line 759, in type_inference_stage
    infer.propagate()
  File "numba\typeinfer.py", line 510, in propagate
    raise errors[0]
TypingError: Internal error at <numba.typeinfer.CallConstraint object at 0x00000000071C82E8>:
--%<-----------------------------------------------------------------
Traceback (most recent call last):
  File "numba\typeinfer.py", line 111, in propagate
    constraint(typeinfer)
  File "numba\typeinfer.py", line 270, in __call__
    self.resolve(typeinfer, typevars, fnty)
  File "numba\typeinfer.py", line 297, in resolve
    sig = context.resolve_function_type(fnty, pos_args, kw_args)
  File "numba\typing\context.py", line 113, in resolve_function_type
    return func.get_call_type(self, args, kws)
  File "numba\types.py", line 334, in get_call_type
    sig.pysig = self.pysig
AttributeError: 'NoneType' object has no attribute 'pysig'
--%<-----------------------------------------------------------------
File "Temp.py", line 10
</code>```

答:
Changing the decorator signature for f from @njit(int64(List(int64, True))) to @njit(int64(List(int64))) makes things work for me on Numba 0.31.0.

For f, a is not a reflected list, so it would appear that setting that flag to True is causing issues. For Numba 0.31.0 I get a different error message.

In general though, I would allow Numba to do it's own type inference for the inputs and outputs. I'm not sure what version you're using, but in recent versions, there is rarely a reason to define the types in the decorator signature. If you're curious about what the type inferencer is doing, just use nb.njit or nb.jit(nopython=True), call the function with your desired inputs, and then examine f.inspect_types() (if your jitted function is f).

Body:
When I try to run this code:

from numba import njit, int64
from numba.types import List

@njit(int64(List(int64, True)))
def f(a):
    a[0] = 0
    return a[0]

@njit(List(int64)())
def g(): return [f([0])]

I get the following. Why is this? How do I make it figure out the types correctly?

Traceback (most recent call last):
  File "Temp.py", line 9, in <module>
    @njit(List(int64)())
  File "numba\decorators.py", line 172, in wrapper
    disp.compile(sig)
  File "numba\dispatcher.py", line 350, in compile
    flags=flags, locals=self.locals)
  File "numba\compiler.py", line 644, in compile_extra
    return pipeline.compile_extra(func)
  File "numba\compiler.py", line 361, in compile_extra
    return self.compile_bytecode(bc, func_attr=self.func_attr)
  File "numba\compiler.py", line 370, in compile_bytecode
    return self._compile_bytecode()
  File "numba\compiler.py", line 631, in _compile_bytecode
    return pm.run(self.status)
  File "numba\compiler.py", line 251, in run
    raise patched_exception
numba.errors.TypingError: Caused By:
Traceback (most recent call last):
  File "numba\compiler.py", line 243, in run
    res = stage()
  File "numba\compiler.py", line 458, in stage_nopython_frontend
    self.locals)
  File "numba\compiler.py", line 759, in type_inference_stage
    infer.propagate()
  File "numba\typeinfer.py", line 510, in propagate
    raise errors[0]
TypingError: Internal error at <numba.typeinfer.CallConstraint object at 0x00000000071C82E8>:
--%<-----------------------------------------------------------------
Traceback (most recent call last):
  File "numba\typeinfer.py", line 111, in propagate
    constraint(typeinfer)
  File "numba\typeinfer.py", line 270, in __call__
    self.resolve(typeinfer, typevars, fnty)
  File "numba\typeinfer.py", line 297, in resolve
    sig = context.resolve_function_type(fnty, pos_args, kw_args)
  File "numba\typing\context.py", line 113, in resolve_function_type
    return func.get_call_type(self, args, kws)
  File "numba\types.py", line 334, in get_call_type
    sig.pysig = self.pysig
AttributeError: 'NoneType' object has no attribute 'pysig'
--%<-----------------------------------------------------------------
File "Temp.py", line 10


问:
php's explode array index
Using php's explode with the following code

```<code>$data="test_1, test_2, test_3";
$temp= explode(",",$data);
</code>```

I get an array like this

```<code>array('0'=>'test_1', '1'=>'test_2', 2='test_3')
</code>```

what I would like to have after explode

```<code>array('1'=>'test_1', '2'=>'test_2', 3='test_3')
</code>```

答:
Lloyd Watkin's answer makes the fewest function calls to achieve the expected result.  It is certainly a superior answer to ManseUK's method which uses four functions in its one-liner after the string has been exploded.

Since this question is nearly 5 years, old there should be something valuable to add if anyone dare to chime in now...

I have two things to address:

The OP and Lloyd Watkins both fail to assign the correct delimiter to their explode method based on the sample string.  The delimiter should be a comma followed by a space.

Sample Input:

```<code>$data="test_1, test_2, test_3";
</code>```

No one has offered a one-liner solution that matches Lloyd's two-function approach.   Here that is: (Demo)

```<code>$temp=array_slice(explode(", ",", $data"),1,null,true);
</code>```

This two-function one-liner prepends the $data string with a comma then a space before exploding it.  Then array_slice ignores the first empty element,  and returns from the second element (1) to the end (null) while preserving the keys (true).

Output as desired:

```<code>array(
    1 => 'test_1',
    2 => 'test_2',
    3 => 'test_3',
)
</code>```

Title: php's explode array index

Body:
Using php's explode with the following code

$data="test_1, test_2, test_3";
$temp= explode(",",$data);

I get an array like this

array('0'=>'test_1', '1'=>'test_2', 2='test_3')

what I would like to have after explode

array('1'=>'test_1', '2'=>'test_2', 3='test_3')

Body:
Lloyd Watkin's answer makes the fewest function calls to achieve the expected result.  It is certainly a superior answer to ManseUK's method which uses four functions in its one-liner after the string has been exploded.

Since this question is nearly 5 years, old there should be something valuable to add if anyone dare to chime in now...

I have two things to address:

The OP and Lloyd Watkins both fail to assign the correct delimiter to their explode method based on the sample string.  The delimiter should be a comma followed by a space.

Sample Input:

$data="test_1, test_2, test_3";

No one has offered a one-liner solution that matches Lloyd's two-function approach.   Here that is: (Demo)

$temp=array_slice(explode(", ",", $data"),1,null,true);

This two-function one-liner prepends the $data string with a comma then a space before exploding it.  Then array_slice ignores the first empty element,  and returns from the second element (1) to the end (null) while preserving the keys (true).

Output as desired:

array(
    1 => 'test_1',
    2 => 'test_2',
    3 => 'test_3',
)


问:
Check if Volume exists - via registry
How can I check, if, let's say, G volume exists - via registry ?

Example:

I have user A and user B, and user A doesn't have volume G configured. I need to check registry to see that B has it, and A does not.

答:
Why using registry? This will do the trick : https://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives.aspx

With sample:

```<code>DriveInfo.GetDrives().StartsWith("G:")
</code>```

Title: Check if Volume exists - via registry

Body:
Why using registry? This will do the trick : https://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives.aspx

With sample:

DriveInfo.GetDrives().StartsWith("G:")


问:
What does the following form do in the code?
```<code><%= form_for [@blog,@blog.comments.build] do |f| %>
    <p><%= f.text_area :text, :size => '40x10' %> </p>
    <p><%= f.submit "Post Comment" %> </p>
<% end %>
</code>```

This is handler by comments_controller, but I would like to know the reason, especially for form_for

答:
It adds a form with a text box, submit button and some hidden authentication related hidden fields for entering comment.
The comment is added to @blog object with relationship:

has_many :comments

Comment is build by the code if not present by:

@blog.comments.build

So overall you get a form for entering comments in a @ blog object. The blog object is necessary in this case and the comment will be automatically combined to the blog entry in proper column in comment record column "blog_id" by default.

This is called Nested Form Relationship, where instead of editing only one record of comment you can combine the parent object also and edit it.

build is basically used to create a structure for object, something like new ( e.g. Model.new). Form action is decided on the basis of given objects. In your case the objects are @blog and @blog.comments.build so the action called will be of either update of Blog controller or Create of Comments Controller..

Hope this helps.

Body:
<%= form_for [@blog,@blog.comments.build] do |f| %>

<%= f.text_area :text, :size => '40x10' %>

<%= f.submit "Post Comment" %>

<% end %>

This is handler by comments_controller, but I would like to know the reason, especially for form_for


问:
using friendly id with includes and where
I was using this query to fetch a property with nested resources

```<code>@property=Property.includes(rooms: [:photos]).where(id: params[:id]).first
</code>```

The above works. But now I want to use friendly_id. So I tried     @property=Property.includes(rooms: [:photos]).friendly.where(id: params[:id]).first which didnt work. All docs for friendly_id uses find instead of where but here how can I make it work?

答:
no, it can't, after check the gem's source code, find that the friendly_id gem doesn't override the activerecord's where method.

And if you use friendly_id, why still query the id?

You can directly query the slug column.

Body:
I was using this query to fetch a property with nested resources

@property=Property.includes(rooms: [:photos]).where(id: params[:id]).first

The above works. But now I want to use friendly_id. So I tried     @property=Property.includes(rooms: [:photos]).friendly.where(id: params[:id]).first which didnt work. All docs for friendly_id uses find instead of where but here how can I make it work?


问:
React - Module Build Failed
I'm trying to a basic React setup with Webpack, but currently getting this console error on the html I'm trying to render.

Not sure why, any ideas?

Module build failed: SyntaxError:

Javascript

```<code>import React from "react";
import { render } from "react-dom";

class App extends React.Component {
    render() {
        return (
            <p>h</p>
        )
    }
}

render(<App/>, document.getElementById('main'));
</code>```

Webpack Config

```<code>const webpack = require('webpack');
const nodeEnv = process.env.NODE_ENV || "production";

module.exports = {
    devtool: "source-map",
    entry: {
        filename: "./index.js"
    },
    output: {
        filename: "build/bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015-native-modules']
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false },
            output: { comments: false },
            sourcemap: true
        }),
        new webpack.DefinePlugin({
            'process.env': { NODE_ENV: JSON.stringify(nodeEnv
            )}
        })
    ]
}
</code>```

Package.JSON

```<code>{
  "name": "joe-react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015-native-modules": "^6.9.4",
    "webpack": "^2.3.2"
  }
}
</code>```

答: You need babel react preset, and I see you use strange preset now, use es2015 instead</p>

Title: React - Module Build Failed

Body:
I'm trying to a basic React setup with Webpack, but currently getting this console error on the html I'm trying to render.

Not sure why, any ideas?

Module build failed: SyntaxError:

Javascript

import React from "react";
import { render } from "react-dom";

class App extends React.Component {
    render() {
        return (

h

        )
    }
}

render(<App/>, document.getElementById('main'));

Webpack Config

const webpack = require('webpack');
const nodeEnv = process.env.NODE_ENV || "production";

module.exports = {
    devtool: "source-map",
    entry: {
        filename: "./index.js"
    },
    output: {
        filename: "build/bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015-native-modules']
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false },
            output: { comments: false },
            sourcemap: true
        }),
        new webpack.DefinePlugin({
            'process.env': { NODE_ENV: JSON.stringify(nodeEnv
            )}
        })
    ]
}

Package.JSON

{
  "name": "joe-react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015-native-modules": "^6.9.4",
    "webpack": "^2.3.2"
  }
}


问:
Template parse errors:Parser Error: Unexpected token - RouterLink
On the below error . Am getting template parse error on RouterLink .

What is the correct way to use the  RouterLink in Angular 2 ?

```<code>      Unhandled Promise rejection: Template parse errors:Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("r">
                 <ul class="nav nav-sidebar">
                    <li class="active"><a [ERROR ->][routerLink]="[/events]">Events</a></li>
                    <li><a [routerLink]="[/task"]>Tasks<"): ng:///t/e.html@30:46Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">                     <ul class="nav nav-sidebar">
                    <li class="active">[ERROR ->]<a [routerLink]="[/events]">Events</a></li>
                    <li><a [routerLink]="[/task"]>Tas"): ng:///t/e.html@30:43, Directive tParser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">
                 <ul class="nav nav-sidebar">
</code>```

答:
You have syntax error, you're using:

```<code><a [routerLink]="[/events]" ... >
</code>```

but instead it should be:

```<code><a [routerLink]="['/events']" ... >
</code>```

or

```<code><a routerLink="/events" ... >
</code>```

Body:
On the below error . Am getting template parse error on RouterLink .

What is the correct way to use the  RouterLink in Angular 2 ?

      Unhandled Promise rejection: Template parse errors:Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("r">

][routerLink]="[/events]">Events

Tasks<"): ng:///t/e.html@30:46Parser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">

[ERROR ->]Events

Tas"): ng:///t/e.html@30:43, Directive tParser Error: Unexpected token / at column 2 in [[/events]] in ng:///t/e.html@30:46 ("ebar">

Body:
You have syntax error, you're using:

<a [routerLink]="[/events]" ... >

but instead it should be:

<a [routerLink]="['/events']" ... >

or

<a routerLink="/events" ... >


问:
Compression to Improve Hard Disk Write Performance
On a modern system can local hard disk write speeds be improved by compressing the output stream?

This question derives from a case I'm working with where a program serially generates and dumps around 1-2GB of text logging data to a raw text file on the hard disk and I think it is IO bound. Would I expect to be able to decrease runtimes by compressing the data before it goes to disk or would the overhead of compression eat up any gain I could get? Would having an idle second core affect this?

I know this would be affected by how much CPU is being used to generate the data so rules of thumb on how much idle CPU time would be needed would be good.

I recall a video talk where someone used compression to improve read speeds for a database but IIRC compressing is a lot more CPU intensive than decompressing.

答:
Yes, this has been true for at least 10 years.  There are operating-systems papers about it.  I think Chris Small may have worked on some of them.

For speed, gzip/zlib compression on lower quality levels is pretty fast; if that's not fast enough you can try FastLZ.  A quick way to use an extra core is just to use popen(3) to send output through gzip.

OwnerDisplayName: BCS

LastEditorDisplayName: BCS

OwnerDisplayName: Norman Ramsey


问:
How can I change php-cli version on Ubuntu 14.04?
I am new to using Linux and I broke some php settings while tampering.

If I execute a php script containing: phpinfo(); it shows the php versions as 5.6,
but via the command line, if I run php -v it returns a version of 7.0.

I want to have both versions match.

How can i fix my command line PATH to also use php 5.6?

答:
```<code>sudo update-alternatives --set php /usr/bin/php5.6
</code>```

Please see: Source

Body:
sudo update-alternatives --set php /usr/bin/php5.6

Please see: Source


问:
How can I rename files in bulk based on their comma-separated contents in shell?
I have hundreds of files suffixed with ".txt". The "txt" files contain "id[0-9]" in a column with delimiter "," from other columns. What I want is to extract the "id[0-9]" as the file name of the corresponding file automatically one by one, any ideas?

for example:  ben.txt ,cotains:

aa,bb,cc,id2233,kk

And many files like this.

Then how can I extract id2233 to replace ben.txt to id2233.txt using shell or other methods？

thanks.

答:
The following is a cautious implementation (won't overwrite existing files; won't move files outside the current directory; not prone to shell injection attacks; uses only builtins, other than the mv command itself).

```<code>#!/bin/bash
for f in *.txt; do
  IFS=, read -r _ _ _ id _ <"$f" || continue
  [[ $id = */* ]] && continue ## refuse to move files outside this directory
  [[ $id = .* ]] && continue ## refuse to give files hidden names
  [[ -e $id.txt ]] && continue ## refuse to overwrite files that already exist
  [[ $f = "$id.txt" ]] && continue ## skip if name already matches destination
  mv -- "$f" "$id.txt"
done
</code>```

Body:
The following is a cautious implementation (won't overwrite existing files; won't move files outside the current directory; not prone to shell injection attacks; uses only builtins, other than the mv command itself).

#!/bin/bash
for f in *.txt; do
  IFS=, read -r _ _ _ id _ <"$f" || continue
  [[ $id = */* ]] && continue ## refuse to move files outside this directory
  [[ $id = .* ]] && continue ## refuse to give files hidden names
  [[ -e $id.txt ]] && continue ## refuse to overwrite files that already exist
  [[ $f = "$id.txt" ]] && continue ## skip if name already matches destination
  mv -- "$f" "$id.txt"
done


问:
Date displaying twice in date picker
Current date is displaying twice in my date picker android app I don't
understand why this is happening.Can anyone tell me what is causing this.

```<code>public void onClick(View v) {

    final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);           // current year
    int mMonth = c.get(Calendar.MONTH);         // current month
    int mDay = c.get(Calendar.DAY_OF_MONTH);    // current day

    datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    t1.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                }

            }, mYear, mMonth, mDay);
    datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
    datePickerDialog.show();
}
</code>```

This is the image

答:
What you are facing is the manner how the date picker is implemented. Usually, the title date should go away if you use it like this:

```<code>datePickerDialog.setTitle("");
</code>```

this call have to be directly before datePickerDialog.show();

Title: Date displaying twice in date picker

Body:
Current date is displaying twice in my date picker android app I don't
understand why this is happening.Can anyone tell me what is causing this.

public void onClick(View v) {

    final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);           // current year
    int mMonth = c.get(Calendar.MONTH);         // current month
    int mDay = c.get(Calendar.DAY_OF_MONTH);    // current day

    datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    t1.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                }

            }, mYear, mMonth, mDay);
    datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
    datePickerDialog.show();
}

This is the image

Body:
What you are facing is the manner how the date picker is implemented. Usually, the title date should go away if you use it like this:

datePickerDialog.setTitle("");

this call have to be directly before datePickerDialog.show();


问:
Program's execution does not end after clicking the close button python (using wxpython-GUI)
I've made a cpu scheduler application using python , i used wxpython to make a frame containing merely a big text area that is updated continously , the problem is that clicking the close button (x) would close the frame but another or multiple frames would appear again and the program continues execution , below is the interface code.

```<code>class Interface(wx.Frame):
    def __init__(self , par , id):
        wx.Frame.__init__(self , par , id , 'XP simulator' , size=(200 , 200 ))
        panel = wx.Panel(self)
        self.sel = 30
        centerPanel = wx.Panel(panel, -1 , size=(100,100) , pos=(50,30))
        self.cpu = CPU(centerPanel, -1)

    def prnt(string , frm):
        print string

    if __name__ =="__main__":

        mutex = threading.Semaphore()
        full = threading.Semaphore(0)
        empty = threading.Semaphore(30)

        buff = util.Queue()
        prod = util.Producer(buff , mutex , empty , full)

        app = wx.App()
        frame = Interface(None, -1)
        frame.Show()

        prod.start()
        print "produced"
        time.sleep(1)
        xp = sched.XPsched(buff , mutex , full , empty, prnt, frame)
        xp.start()

        app.MainLoop()
</code>```

Thanks;)
Nataly..

答:
You have to bind the close event in your wxFrame:

self.Bind(wx.EVT_CLOSE, self.on_close)

then add an on_close method:

```<code>def on_close(self, event):
    self.Destroy()
    sys.exit(0)
</code>```

Body:
I've made a cpu scheduler application using python , i used wxpython to make a frame containing merely a big text area that is updated continously , the problem is that clicking the close button (x) would close the frame but another or multiple frames would appear again and the program continues execution , below is the interface code.

class Interface(wx.Frame):
    def __init__(self , par , id):
        wx.Frame.__init__(self , par , id , 'XP simulator' , size=(200 , 200 ))
        panel = wx.Panel(self)
        self.sel = 30
        centerPanel = wx.Panel(panel, -1 , size=(100,100) , pos=(50,30))
        self.cpu = CPU(centerPanel, -1)

    def prnt(string , frm):
        print string

    if __name__ =="__main__":

        mutex = threading.Semaphore()
        full = threading.Semaphore(0)
        empty = threading.Semaphore(30)

        buff = util.Queue()
        prod = util.Producer(buff , mutex , empty , full)

        app = wx.App()
        frame = Interface(None, -1)
        frame.Show()

        prod.start()
        print "produced"
        time.sleep(1)
        xp = sched.XPsched(buff , mutex , full , empty, prnt, frame)
        xp.start()

        app.MainLoop()

Thanks;)
Nataly..

Body:
You have to bind the close event in your wxFrame:

self.Bind(wx.EVT_CLOSE, self.on_close)

then add an on_close method:

def on_close(self, event):
    self.Destroy()
    sys.exit(0)


问:
XAMPP phpMyadmin: Access denied after changing password
Hi I know its an old question but I have tried many answers and guides but all in vain. I was using phpmyadmin without password on my local machine previously and I changed password using command prompt on windows with following command

mysqladmin.exe -u root password root

Since then I am not able to open my localhost/phpmyadmin and I get following error

1045 - Access denied for user 'root'@'localhost' (using password: NO)

I have tried changing config.inc.php current status of this file is as following

```<code>$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
</code>```

I have tried changing password from localhost/security.php and changed password to 123. I have also tried reseting root password by opening resetroot.bat batch file. I seriously think I have messed all up so if someone can help me here i shall be thank full. I am using Xampp on windows 7

EDIT Also I would like to tell you that I have tried giving new password to

```<code>$cfg['Servers'][$i]['password'] = '';
</code>```

And also to

```<code>$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
</code>```

changing user to root

答:
Open xampp/phpMyAdmin/config.inc and change the line

```<code>$cfg['Servers'][$i]['auth_type'] = 'config';
</code>```

to

```<code>$cfg['Servers'][$i]['auth_type'] = 'cookie';
</code>```

PhpMyAdmin will then show a login screen where you can enter your username and password.

Body:
Hi I know its an old question but I have tried many answers and guides but all in vain. I was using phpmyadmin without password on my local machine previously and I changed password using command prompt on windows with following command

mysqladmin.exe -u root password root

Since then I am not able to open my localhost/phpmyadmin and I get following error

1045 - Access denied for user 'root'@'localhost' (using password: NO)

I have tried changing config.inc.php current status of this file is as following

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

I have tried changing password from localhost/security.php and changed password to 123. I have also tried reseting root password by opening resetroot.bat batch file. I seriously think I have messed all up so if someone can help me here i shall be thank full. I am using Xampp on windows 7

EDIT Also I would like to tell you that I have tried giving new password to

$cfg['Servers'][$i]['password'] = '';

And also to

$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

changing user to root

Body:
Open xampp/phpMyAdmin/config.inc and change the line

$cfg['Servers'][$i]['auth_type'] = 'config';

to

$cfg['Servers'][$i]['auth_type'] = 'cookie';

PhpMyAdmin will then show a login screen where you can enter your username and password.


问:
how can we simulate keyboard keys using vbs?
I'm aware of the probably most common form:

```<code>set wShell = createObject("wscript.shell")
wShell.sendKeys ":){ENTER}"
</code>```

this uncommon and limited way:

```<code>Set ShellApp = CreateObject("Shell.Application")
ShellApp.WindowSwitcher
</code>```

we can hackishly use sleep if we want a sequence of keys which depends on other events:

```<code>WScript.sleep 987
wShell.sendKeys "foo{!}~"
WScript.sleep 789
wShell.sendKeys "^a^c"
</code>```

and we can't really keep a key pressed but we can repeat it many times:

```<code>wShell.sendKeys "{LEFT 42}"
</code>```

now... am I missing something?

答:
yeah, I'm probably missing something.

meanwhile I figured this useful tabled reference might still be useful if shamelessly adapted here:

Most ASCII characters can be represented simply by the character itself.

E.g, the key sequence FRED can be represented by "FRED".

Special keys such as the control keys, function keys etc are encoded with {braces}

```
................................................................................................................
:     Key/Character     :                SendKey                :                 Description                  :
:.......................:.......................................:..............................................:
: ~                     : {~}                                   : Send a tilde (~)                             :
: !                     : {!}                                   : Send an exclamation point (!)                :
: ^                     : {^}                                   : Send a caret (^)                             :
: +                     : {+}                                   : Send a plus sign (+)                         :
: Backspace             : {BACKSPACE} or {BKSP} or {BS}         : Send a Backspace keystroke                   :
: Break                 : {BREAK}                               : Send a Break keystroke                       :
: Caps Lock             : {CAPSLOCK}                            : Press the Caps Lock Key (toggle on or off)   :
: Clear                 : {CLEAR}                               : Clear the field                              :
: Delete                : {DELETE} or {DEL}                     : Send a Delete keystroke                      :
: Insert                : {INSERT} or {INS}                     : Send an Insert keystroke                     :
: Cursor control arrows : {LEFT} / {RIGHT} / {UP} / {DOWN}      : Send a Left/Right/Up/Down Arrow              :
: End                   : {END}                                 : Send an End keystroke                        :
: Enter                 : {ENTER} or ~                          : Send an Enter keystroke                      :
: Escape                : {ESCAPE}                              : Send an Esc keystroke                        :
: F1 through F16        : {F1} through {F16}                    : Send a Function keystroke                    :
: Help                  : {HELP}                                : Send a Help keystroke                        :
: Home                  : {HOME}                                : Send a Home keystroke                        :
: Page Down             : {PGDN}                                : Send a Page Down keystroke                   :
: Page Up               : {PGUP}                                : Send a Page Up keystroke                     :
: Numlock               : {NUMLOCK}                             : Send a Num Lock keystroke                    :
: Scroll lock           : {SCROLLLOCK}                          : Press the Scroll lock Key (toggle on or off) :
: Print Screen          : {PRTSC}                               : Send a Print Screen keystroke                :
:.......................:.......................................:..............................................:
```

To specify keys with any combination of SHIFT, CTRL and ALT keys, precede them as following:

```<code>For SHIFT prefix with +
For CTRL  prefix with ^
For ALT   prefix with %
</code>```

Body:
I'm aware of the probably most common form:

set wShell = createObject("wscript.shell")
wShell.sendKeys ":){ENTER}"

this uncommon and limited way:

Set ShellApp = CreateObject("Shell.Application")
ShellApp.WindowSwitcher

we can hackishly use sleep if we want a sequence of keys which depends on other events:

WScript.sleep 987
wShell.sendKeys "foo{!}~"
WScript.sleep 789
wShell.sendKeys "^a^c"

and we can't really keep a key pressed but we can repeat it many times:

wShell.sendKeys "{LEFT 42}"

now... am I missing something?

Body:
yeah, I'm probably missing something.

meanwhile I figured this useful tabled reference might still be useful if shamelessly adapted here:

Most ASCII characters can be represented simply by the character itself.

E.g, the key sequence FRED can be represented by "FRED".

Special keys such as the control keys, function keys etc are encoded with {braces}

................................................................................................................
:     Key/Character     :                SendKey                :                 Description                  :
:.......................:.......................................:..............................................:
: ~                     : {~}                                   : Send a tilde (~)                             :
: !                     : {!}                                   : Send an exclamation point (!)                :
: ^                     : {^}                                   : Send a caret (^)                             :
: +                     : {+}                                   : Send a plus sign (+)                         :
: Backspace             : {BACKSPACE} or {BKSP} or {BS}         : Send a Backspace keystroke                   :
: Break                 : {BREAK}                               : Send a Break keystroke                       :
: Caps Lock             : {CAPSLOCK}                            : Press the Caps Lock Key (toggle on or off)   :
: Clear                 : {CLEAR}                               : Clear the field                              :
: Delete                : {DELETE} or {DEL}                     : Send a Delete keystroke                      :
: Insert                : {INSERT} or {INS}                     : Send an Insert keystroke                     :
: Cursor control arrows : {LEFT} / {RIGHT} / {UP} / {DOWN}      : Send a Left/Right/Up/Down Arrow              :
: End                   : {END}                                 : Send an End keystroke                        :
: Enter                 : {ENTER} or ~                          : Send an Enter keystroke                      :
: Escape                : {ESCAPE}                              : Send an Esc keystroke                        :
: F1 through F16        : {F1} through {F16}                    : Send a Function keystroke                    :
: Help                  : {HELP}                                : Send a Help keystroke                        :
: Home                  : {HOME}                                : Send a Home keystroke                        :
: Page Down             : {PGDN}                                : Send a Page Down keystroke                   :
: Page Up               : {PGUP}                                : Send a Page Up keystroke                     :
: Numlock               : {NUMLOCK}                             : Send a Num Lock keystroke                    :
: Scroll lock           : {SCROLLLOCK}                          : Press the Scroll lock Key (toggle on or off) :
: Print Screen          : {PRTSC}                               : Send a Print Screen keystroke                :
:.......................:.......................................:..............................................:

To specify keys with any combination of SHIFT, CTRL and ALT keys, precede them as following:

For SHIFT prefix with +
For CTRL  prefix with ^
For ALT   prefix with %


问:
BAPI_SYSTEM_MT_GETALERTDATA, call using Java is returning only 10 recent alerts
BAPI_SYSTEM_MT_GETALERTDATA called using Java is returning only 10 recent alerts. I want to find all the alerts for a given range if dates. Please let me know how we can do it.

答:
The number 10 has nothing to do with BAPI_SYSTEM_MT_GETALERTDATA FM. This parameter is called Maximum Number of Alerts Kept, and it is adjusted in CCMS alert monitoring settings, which is S_B6A_52000011 transaction.

It seems that you simply have such setting on the remote system and this setting cannot be changed remotely. Alerts beyond 10 are not stored at all.


问:
Only read new events from Firebase Database
I was halfway done with implementing Core Data in my iOS app when I realized that Firebase has offline capabilities that would pretty much mimic what I was trying to accomplish the whole time.

In my database which is structured as such:

```<code>- Users
    - user1
    - user2
- Groups
    - group1
        - members
            - user1
        - events
            - event1_By_Auto_Key
            - event2_By_Auto_Key
</code>```

I wanted to locally store all the events that have already been fetched by a user so that I wouldn't have to read all of them every single time I need to get a group's events. Now that I think I'm just going to stick with Firebase's offline capabilities instead of using Core Data, I have a question regarding how to efficiently read events from the database.

As seen from my database's structure the events are stored using the childByAutoId().setValue(data) method, meaning the keys are unknown when inserted. So my console for a given group might look like this:

My question is: how can I only read the new events from a group? The reason I was implementing Core Data was so that I could cache already fetched events, but I'm not sure how I can make sure that I don't re-read data.

答:
There are a few strategies you could use. Since the ids generated are always lexically greater than any existing, you can use startAt() on your query with the newest record you already have. You just need to skip the record that matches the last ID you have. If you keep a timestamp in the events, you can use orderByChild() and the last timestamp and increment by one ms then you don't get any records you already have. It would be something like:</p>

```<code>function getNewEvents(group, arrayOfExistingIds) {
  let lastId = arrayOfExistingIds.sort().pop(),
    ref = admin.database().ref('/Groups/' + group + '/events')
      .orderByKey().startAt(lastId).on('value', function(snap){
        if (snap.key === lastId) return;
        console.log('New record: ' + snap.key);
      })
}
</code>```

Body:
I was halfway done with implementing Core Data in my iOS app when I realized that Firebase has offline capabilities that would pretty much mimic what I was trying to accomplish the whole time.

In my database which is structured as such:

- Users
    - user1
    - user2
- Groups
    - group1
        - members
            - user1
        - events
            - event1_By_Auto_Key
            - event2_By_Auto_Key

I wanted to locally store all the events that have already been fetched by a user so that I wouldn't have to read all of them every single time I need to get a group's events. Now that I think I'm just going to stick with Firebase's offline capabilities instead of using Core Data, I have a question regarding how to efficiently read events from the database.

As seen from my database's structure the events are stored using the childByAutoId().setValue(data) method, meaning the keys are unknown when inserted. So my console for a given group might look like this:

My question is: how can I only read the new events from a group? The reason I was implementing Core Data was so that I could cache already fetched events, but I'm not sure how I can make sure that I don't re-read data.

Body:
There are a few strategies you could use. Since the ids generated are always lexically greater than any existing, you can use startAt() on your query with the newest record you already have. You just need to skip the record that matches the last ID you have. If you keep a timestamp in the events, you can use orderByChild() and the last timestamp and increment by one ms then you don't get any records you already have. It would be something like:

function getNewEvents(group, arrayOfExistingIds) {
  let lastId = arrayOfExistingIds.sort().pop(),
    ref = admin.database().ref('/Groups/' + group + '/events')
      .orderByKey().startAt(lastId).on('value', function(snap){
        if (snap.key === lastId) return;
        console.log('New record: ' + snap.key);
      })
}


问:
Why does my original array gets changed when i only change copied array?
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

```<code>public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}
</code>```

thanks for your time

答:
In Java arrays are objects. You can use the clone() method to copy your array. It will perform a shallow copy - it will work fine with your int array.

```<code>int [][] arr = new int[tiles.length][];
for(int i = 0; i < tiles.length; i++)
    arr[i] = tiles[i].clone();
</code>```

copy a 2d array in java

Body:
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}

thanks for your time

Body:
In Java arrays are objects. You can use the clone() method to copy your array. It will perform a shallow copy - it will work fine with your int array.

int [][] arr = new int[tiles.length][];
for(int i = 0; i < tiles.length; i++)
    arr[i] = tiles[i].clone();

copy a 2d array in java


问:
Building an NSstring out of an NSMutableArray
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?</p>

```<code>  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }
</code>```

答:
Hey, sorry for the bad coding format, posting it again ...</p>

```<code>NSString *ans = @"";
for (id obj in anExpression)
{
    if ([obj isKindOfClass:[NSString class]])
        [ans stringByAppendingString:(NSString *)obj];
    if ([obj isKindOfClass:[NSNumber class]])
        [ans stringByAppendingString:(NSString *)[obj stringValue]];

    NSLog(@"String so far: %@ ", ans);
}
[ans autorelease];
NSLog(@"final string is: %@ ", ans);

return ans;
</code>```

Body:
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?

  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }

Body:
Hey, sorry for the bad coding format, posting it again ...

NSString *ans = @"";
for (id obj in anExpression)
{
    if ([obj isKindOfClass:[NSString class]])
        [ans stringByAppendingString:(NSString *)obj];
    if ([obj isKindOfClass:[NSNumber class]])
        [ans stringByAppendingString:(NSString *)[obj stringValue]];

    NSLog(@"String so far: %@ ", ans);
}
[ans autorelease];
NSLog(@"final string is: %@ ", ans);

return ans;


问:
How to convert day,month,year into date format?
I have been trying to run a python script that converts day,month,year into date format.

I have attempted the following script;

```<code># dateconvert2.py
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()
</code>```

The result should look like;

```<code>>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.
</code>```

As I ran the program, an error appeared saying that the line;

```<code>    monthStr = months[month-1]
</code>```

had an index error.

What can I do to improve this? Please help

答:
If

```<code>monthStr = months[month-1]
</code>```

had an index error, it means month was either smaller than 1 or bigger than 12. You could check it's in the correct range before this line.

A few notes

eval is dangerous, and not needed in this case. You could use split, map and int to extract the integers.

you could use format with %02d to show the dates, if you want to write it yourself

strftime and strptime do exactly what you want. They parse a string to datetime and display a datetime in any given format.

calendar already has month_name. The list has 13 elements though, and the first one is empty.

Modified code :

```<code>def main():
    # get the day month and year
    day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))

    date1 = '%02d/%02d/%d' % (day, month, year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    if month > 0 and month < 13:
        month_str = months[month-1]
        ## alternative :
        # import calendar
        # month_str = calendar.month_name[month]
        date2 = '%s %d, %d' % (month_str, day, year)
        print("The date is", date1, "or", date2+ ".")
    else:
        print("Invalid month")
main()
</code>```

As an example :

```<code>Please enter day, month, year numbers: 24,12,2017
The date is 24/12/2017 or December 24, 2017.
</code>```

but :

```<code>Please enter day, month, year numbers: 24,0,2017
Invalid month
</code>```

Body:
I have been trying to run a python script that converts day,month,year into date format.

I have attempted the following script;

# dateconvert2.py
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()

The result should look like;

>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.

As I ran the program, an error appeared saying that the line;

    monthStr = months[month-1]

had an index error.

What can I do to improve this? Please help

Body:
If

monthStr = months[month-1]

had an index error, it means month was either smaller than 1 or bigger than 12. You could check it's in the correct range before this line.

A few notes

eval is dangerous, and not needed in this case. You could use split, map and int to extract the integers.

you could use format with %02d to show the dates, if you want to write it yourself

strftime and strptime do exactly what you want. They parse a string to datetime and display a datetime in any given format.

calendar already has month_name. The list has 13 elements though, and the first one is empty.

Modified code :

def main():
    # get the day month and year
    day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))

    date1 = '%02d/%02d/%d' % (day, month, year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    if month > 0 and month < 13:
        month_str = months[month-1]
        ## alternative :
        # import calendar
        # month_str = calendar.month_name[month]
        date2 = '%s %d, %d' % (month_str, day, year)
        print("The date is", date1, "or", date2+ ".")
    else:
        print("Invalid month")
main()

As an example :

Please enter day, month, year numbers: 24,12,2017
The date is 24/12/2017 or December 24, 2017.

but :

Please enter day, month, year numbers: 24,0,2017
Invalid month


问:
Submit form with ajax without reload the page?
I have a problem whatever i do to submit a form using Jquery and Ajax, but it still redirected me to the action page of the form, i don't understand if somethings outside Affected the function or what happen.
this is my code:

```<code><form action="add-niveau" method="POST" class="ajax">
  <div>
    <input type="text" name="name" placeholder="Your name">
  </div>
  <div>
    <input type="text" name="email" placeholder="Your email">
  </div>
  <div>
    <textarea rows="4" cols="20" name="comment"></textarea>
  </div>
   <input type="submit" value="send">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">      </script>
<script>
  $('form.ajax').on('submit', function() {
     return false;
  });
</script>
</code>```

Other ajax script:

```<code>var ajaxRequest;

function ajaxFunction() {
try {

    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e) {

    // Internet Explorer Browsers
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {

        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {

            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
}

function getForm(objButton) {
ajaxFunction();
ajaxRequest.onreadystatechange = function() {
    if (ajaxRequest.readyState == 4) {
        document.getElementById("formTag").innerHTML =    ajaxRequest.responseText;
    }
}
var buttonValue = objButton.value;
ajaxRequest.open("get", "get-form/" + buttonValue, true);
ajaxRequest.send(null);
}

// Send form using ajax:
$('form.ajax').on('submit', function(e) {
  e.preventDefault();
});
</code>```

答:
You need to add event.preventDefault(); right after click event since you want to prevent the default form submission.</p>

```<code>$('form.ajax').on('submit', function(event) { // pass the event to function

     event.preventDefault(); // add this line

     $.ajax({
         url: "test.php",
         context: document.body
     }).done(function() {
         alert('Done!');
     });

});
</code>```

Body:
I have a problem whatever i do to submit a form using Jquery and Ajax, but it still redirected me to the action page of the form, i don't understand if somethings outside Affected the function or what happen.
this is my code:

<form action="add-niveau" method="POST" class="ajax">

    <input type="text" name="name" placeholder="Your name">

    <input type="text" name="email" placeholder="Your email">

    <textarea rows="4" cols="20" name="comment"></textarea>

   <input type="submit" value="send">
</form>

Other ajax script:

var ajaxRequest;

function ajaxFunction() {
try {

    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e) {

    // Internet Explorer Browsers
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {

        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {

            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
}

function getForm(objButton) {
ajaxFunction();
ajaxRequest.onreadystatechange = function() {
    if (ajaxRequest.readyState == 4) {
        document.getElementById("formTag").innerHTML =    ajaxRequest.responseText;
    }
}
var buttonValue = objButton.value;
ajaxRequest.open("get", "get-form/" + buttonValue, true);
ajaxRequest.send(null);
}

// Send form using ajax:
$('form.ajax').on('submit', function(e) {
  e.preventDefault();
});

Body:
You need to add event.preventDefault(); right after click event since you want to prevent the default form submission.

$('form.ajax').on('submit', function(event) { // pass the event to function

     event.preventDefault(); // add this line

     $.ajax({
         url: "test.php",
         context: document.body
     }).done(function() {
         alert('Done!');
     });

});


问:
Facebook app links (deep linking) not working on android
I have the following tags in my phonegap app index.html file:

```<code><meta property="al:android:url" content="myApp://test.myapp.me/">
<meta property="al:android:package" content="myapp.market.test">
<meta property="al:android:app_name" content="TestApp">
</code>```

In Facebook url debug tool i see the same tags under "app links android" in the developer tools.

My app package name is: "myapp.market.test"

But if someone click on a shared link on Facebook app, for example: "myapp.me/index.html?id=something" the link opens in the mobile browser instead of opening my app.

As i understand the only meta tag here that responsible for the app to open is "al:android:package".

Am i doing something wrong here ?

答:
You should add this line in your Manifest

```<code><data android:scheme="myApp"/>
</code>```

Don't forget this in "intent-filter" tag of Activity you want to open

```<code><category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</code>```

Body:
I have the following tags in my phonegap app index.html file:

<meta property="al:android:url" content="myApp://test.myapp.me/">
<meta property="al:android:package" content="myapp.market.test">
<meta property="al:android:app_name" content="TestApp">

In Facebook url debug tool i see the same tags under "app links android" in the developer tools.

My app package name is: "myapp.market.test"

But if someone click on a shared link on Facebook app, for example: "myapp.me/index.html?id=something" the link opens in the mobile browser instead of opening my app.

As i understand the only meta tag here that responsible for the app to open is "al:android:package".

Am i doing something wrong here ?

Body:
You should add this line in your Manifest

<data android:scheme="myApp"/>

Don't forget this in "intent-filter" tag of Activity you want to open

<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>


问:
javac: file not found in ProcessBuilder. Commands are separated in ProcessBuilder arguments
First of all I have searched the forum and the web for 5 hours, but couldn't find out what my problem is so I'm hoping this isn't a duplicate.

I am using the Java ProcessBuilder to compile and run a Java Project. When I type

```<code>javac /Users/Katzenmeister/Desktop/Final/src/edu/kit/informatik/citationmanager/*.java
</code>```

to my Terminal on MacOSX I can compile the whole folder without any errors.

In my Program I have the following

```<code>public class CompilerController {

private static File directory;
private static String mainClass;
private static boolean compiled = false;

public static void setDirectory(File directory) {
    CompilerController.directory = directory;
}

public static void setMainClass(String mainClass) {
    CompilerController.mainClass = mainClass;
}

private static void compile() {
    ProcessBuilder pb = new ProcessBuilder("javac",directory.getAbsolutePath()+"/*.java");
    pb.inheritIO();
    try {
        pb.start();
        compiled = true;
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

private static String[] getSourcePath() {

    String[] strArr = directory.toString().split("src");

    strArr[0] += "src";
    strArr[1] += mainClass;

    return strArr;
}

private static void run() {

    ProcessBuilder pb = new ProcessBuilder("java",getSourcePath()[0],getSourcePath()[1]);
    try {
        pb.start();
    } catch(IOException ex) {
        System.out.println(ex);
    }

}

public static void compileRun() {
    compile();
    if (compiled) {
        run();
    }
}
}
</code>```

In my JavaFX Controller class I get the directory by using a DirectoryChooser and passing the absolute path to the CompilerController using setDirectory().

When I run my program I get the following error:

```<code>javac: file not found: /Users/Katzenmeister/Desktop/Final/src/edu/kit/informatik/citationmanager/*.java
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

Which is as far as I can tell the same thing I got working on my Terminal. I have only been coding for 6 Months now so I lack knowledge, but I'm assuming this is due to the JVM Runtime Directory probably. Any help is very welcome. Here are some of the forum links that I have already checked for reference:

ProcessBuilder can't find file?!

Run a .java file using ProcessBuilder

How to run a Java program using ProcessBuilder inside the other Java program. (with -cp and -Xbootclasspath commands)

Compile and Run Java Program from another Java Program

ProcessBuilder can't find file?!

P.S: This is my first question on the forum. I tried my best to fit the etiquette, if I have done anything wrong please tell me so I can edit my question.

EDIT: I got the code to work as follows for anyone who might have a similar problem

```<code>private static void compile() {

    ArrayList<String> files = new ArrayList<>();
    files.add("javac");
    files.add("-sourcepath");
    files.add("./*");

    try {
        for (File file : directory.listFiles()) {
            if (!file.isHidden()) {
                files.add(file.getName());
            }
        }
    } catch(NullPointerException ex) {}

    pb.directory(new File(directory.getAbsolutePath()));
    pb.command(files);
    pb.inheritIO();

    try {
        synchronized (processLock) {
            Process pr = pb.start();
            int i = pr.waitFor();
        }
        compiled = true;
    } catch (IOException ex) {
        System.out.println(ex);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

答:
* is processed differently in the shell vs in ProcessBuilder: it is expanded before being passed to javac in the shell, but it is passed literally in the ProcessBuilder command.

You can see this if you add echo before the command in the shell:

```<code>echo javac /Users/whatever/*.java
</code>```

will print out something like:

```<code>javac /Users/whatever/Foo.java /Users/whatever/Bar.java
</code>```

When you are invoking ProcessBuilder like that, you are doing the equivalent of single-quoting the path in the shell, like this:

```<code>javac '/Users/whatever/*.java'
</code>```

which suppresses glob expansion, so javac receives /Users/whatever/*.java, as you can see if you add echo to the front:

```<code>echo javac '/Users/whatever/*.java'
</code>```

prints

```<code>javac /Users/whatever/*.java
</code>```

You need to expand the glob yourself, e.g. use new File("/your/directory").listFiles(), and pass all the files to the ProcessBuilder explicitly.

Body:
First of all I have searched the forum and the web for 5 hours, but couldn't find out what my problem is so I'm hoping this isn't a duplicate.

I am using the Java ProcessBuilder to compile and run a Java Project. When I type

javac /Users/Katzenmeister/Desktop/Final/src/edu/kit/informatik/citationmanager/*.java

to my Terminal on MacOSX I can compile the whole folder without any errors.

In my Program I have the following

public class CompilerController {

private static File directory;
private static String mainClass;
private static boolean compiled = false;

public static void setDirectory(File directory) {
    CompilerController.directory = directory;
}

public static void setMainClass(String mainClass) {
    CompilerController.mainClass = mainClass;
}

private static void compile() {
    ProcessBuilder pb = new ProcessBuilder("javac",directory.getAbsolutePath()+"/*.java");
    pb.inheritIO();
    try {
        pb.start();
        compiled = true;
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

private static String[] getSourcePath() {

    String[] strArr = directory.toString().split("src");

    strArr[0] += "src";
    strArr[1] += mainClass;

    return strArr;
}

private static void run() {

    ProcessBuilder pb = new ProcessBuilder("java",getSourcePath()[0],getSourcePath()[1]);
    try {
        pb.start();
    } catch(IOException ex) {
        System.out.println(ex);
    }

}

public static void compileRun() {
    compile();
    if (compiled) {
        run();
    }
}
}

In my JavaFX Controller class I get the directory by using a DirectoryChooser and passing the absolute path to the CompilerController using setDirectory().

When I run my program I get the following error:

javac: file not found: /Users/Katzenmeister/Desktop/Final/src/edu/kit/informatik/citationmanager/*.java
Usage: javac <options> <source files>
use -help for a list of possible options

Which is as far as I can tell the same thing I got working on my Terminal. I have only been coding for 6 Months now so I lack knowledge, but I'm assuming this is due to the JVM Runtime Directory probably. Any help is very welcome. Here are some of the forum links that I have already checked for reference:

ProcessBuilder can't find file?!

Run a .java file using ProcessBuilder

How to run a Java program using ProcessBuilder inside the other Java program. (with -cp and -Xbootclasspath commands)

Compile and Run Java Program from another Java Program

ProcessBuilder can't find file?!

P.S: This is my first question on the forum. I tried my best to fit the etiquette, if I have done anything wrong please tell me so I can edit my question.

EDIT: I got the code to work as follows for anyone who might have a similar problem

private static void compile() {

    ArrayList<String> files = new ArrayList<>();
    files.add("javac");
    files.add("-sourcepath");
    files.add("./*");

    try {
        for (File file : directory.listFiles()) {
            if (!file.isHidden()) {
                files.add(file.getName());
            }
        }
    } catch(NullPointerException ex) {}

    pb.directory(new File(directory.getAbsolutePath()));
    pb.command(files);
    pb.inheritIO();

    try {
        synchronized (processLock) {
            Process pr = pb.start();
            int i = pr.waitFor();
        }
        compiled = true;
    } catch (IOException ex) {
        System.out.println(ex);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Body:
* is processed differently in the shell vs in ProcessBuilder: it is expanded before being passed to javac in the shell, but it is passed literally in the ProcessBuilder command.

You can see this if you add echo before the command in the shell:

echo javac /Users/whatever/*.java

will print out something like:

javac /Users/whatever/Foo.java /Users/whatever/Bar.java

When you are invoking ProcessBuilder like that, you are doing the equivalent of single-quoting the path in the shell, like this:

javac '/Users/whatever/*.java'

which suppresses glob expansion, so javac receives /Users/whatever/*.java, as you can see if you add echo to the front:

echo javac '/Users/whatever/*.java'

prints

javac /Users/whatever/*.java

You need to expand the glob yourself, e.g. use new File("/your/directory").listFiles(), and pass all the files to the ProcessBuilder explicitly.


问:
how to toggle each button separately on multiple buttons?
I have same button for multiple times each one have same work that is of hide and show. I have to toggle following data after click on that button

```<code><button type="button" class="pull-right btn menu">
    <span class="glyphicon glyphicon-option-vertical" aria-hidden="true"></span>
</button>
<ul class="downmenu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Separated link</a></li>
</ul>
</code>```

and js code is

```<code>$('.menu').click(function(){
    $(this).each(function(){
    $('.downmenu').toggle('show');
    });
    });
</code>```

my problem is that after click on any button all buttons are working. How to toggle each separately. I have to toggle downmenu ul list on each button so how can i do it?

答:
The loop inside the click event is redundant. The problem is the global selector for .downmenu which selects all elements with that class. The solution is to isolate the element .downmenu next to the button clicked:

```<code>$('.menu').click(function(){
    $(this).next('.downmenu').toggle('show');
});
</code>```

Body:
I have same button for multiple times each one have same work that is of hide and show. I have to toggle following data after click on that button

<button type="button" class="pull-right btn menu">

</button>

Action

Another action

Something else here

Separated link

and js code is

$('.menu').click(function(){
    $(this).each(function(){
    $('.downmenu').toggle('show');
    });
    });

my problem is that after click on any button all buttons are working. How to toggle each separately. I have to toggle downmenu ul list on each button so how can i do it?

Body:
The loop inside the click event is redundant. The problem is the global selector for .downmenu which selects all elements with that class. The solution is to isolate the element .downmenu next to the button clicked:

$('.menu').click(function(){
    $(this).next('.downmenu').toggle('show');
});


问:
DependencyProperty in UserControl doesn't get updated from binding
Here is the reproduction of my problem:

Create a WPF Application

Add a new UserControl to the project

Replace its content with the following

```<code><UserControl
  x:Class="UserControl1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <TextBlock Text="{Binding MyText}"/>
</UserControl>
</code>```

```<code>Public Class UserControl1
  Public Property MyText As String
    Get
      Return GetValue(MyTextProperty)
    End Get
    Set(ByVal value As String)
      SetValue(MyTextProperty, value)
    End Set
  End Property
  Public Shared ReadOnly MyTextProperty As DependencyProperty =
   DependencyProperty.Register("MyText", GetType(String), GetType(UserControl1))
End Class
</code>```

Replace the following in the MainWindow.xaml file:

```<code><Window
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:WpfApplication1"
  Title="MainWindow"
  DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <StackPanel >
    <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"/>
    <src:UserControl1 MyText="{Binding Title}"/>
  </StackPanel>
</Window>
</code>```

As you can see, the UserControl1.MyText property doesn't get updated when the MainWindow.Title changes.

What am I missing? I want the user control to be connected to the parent property, is there a xamly way to do it?

答:
Okay, when I recreate the app (I'm using C#, so I don't think this will make any difference), I notice in my output the binding is failing because UserControl does not have a Title property.

Add ElementName=this to your UserControl1 binding. And set the Name property on the Window to this and that should fix it.

Something like this:

```<code><src:UserControl1 MyText="{Binding Title, ElementName=this}" />
</code>```

The binding works for me when I do that. Hope that helps!

Body:
Here is the reproduction of my problem:

Create a WPF Application

Add a new UserControl to the project

Replace its content with the following

<UserControl
  x:Class="UserControl1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <TextBlock Text="{Binding MyText}"/>
</UserControl>

Public Class UserControl1
  Public Property MyText As String
    Get
      Return GetValue(MyTextProperty)
    End Get
    Set(ByVal value As String)
      SetValue(MyTextProperty, value)
    End Set
  End Property
  Public Shared ReadOnly MyTextProperty As DependencyProperty =
   DependencyProperty.Register("MyText", GetType(String), GetType(UserControl1))
End Class

Replace the following in the MainWindow.xaml file:

<Window
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:WpfApplication1"
  Title="MainWindow"
  DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <StackPanel >
    <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"/>
    <src:UserControl1 MyText="{Binding Title}"/>
  </StackPanel>
</Window>

As you can see, the UserControl1.MyText property doesn't get updated when the MainWindow.Title changes.

What am I missing? I want the user control to be connected to the parent property, is there a xamly way to do it?

Body:
Okay, when I recreate the app (I'm using C#, so I don't think this will make any difference), I notice in my output the binding is failing because UserControl does not have a Title property.

Add ElementName=this to your UserControl1 binding. And set the Name property on the Window to this and that should fix it.

Something like this:

<src:UserControl1 MyText="{Binding Title, ElementName=this}" />

The binding works for me when I do that. Hope that helps!