问:
PYTHONPATH not set automatically in virtualenvs
I installed a virtualbox with xubuntu-16.04.2-desktop on windows 10.
when I create an env running a mezzanine app, I get this error:

```<code>Traceback (most recent call last):
File "manage.py", line 7, in <module>
from mezzanine.utils.conf import real_project_name
ImportError: No module named 'mezzanine'
</code>```

the same when I try to import modules:

```<code>(test) mauri@bison:~$ python -c "import django"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'django'
</code>```

the problem seems to be the PYTHONPATh, not set correctly.
If i set it manually, everything works fine.

```<code>(test) mauri@bison:~$ export
PYTHONPATH="/home/mauri/envs/test/lib/python3.5/site-packages/"
(test) mauri@bison:~$ python -c "import django"
(test) mauri@bison:~$ env
XDG_VTNR=7
LC_PAPER=cs_CZ.UTF-8
LC_ADDRESS=cs_CZ.UTF-8
 XDG_SESSION_ID=c1
....
</code>```

any idea why the PYTHONPATH is not set automatically when I create envs?

thank you so much, and sorry if I miss anything in the explaination, I m pretty new in this field.

答:
Check your bash* if you have any alias overriding the python setup. You can easily check with the command alias from bash:

```<code>$ alias
alias ll='ls -alh'
alias ls='ls -G'
...
</code>```

Body:
I installed a virtualbox with xubuntu-16.04.2-desktop on windows 10.
when I create an env running a mezzanine app, I get this error:

Traceback (most recent call last):
File "manage.py", line 7, in <module>
from mezzanine.utils.conf import real_project_name
ImportError: No module named 'mezzanine'

the same when I try to import modules:

(test) mauri@bison:~$ python -c "import django"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'django'

the problem seems to be the PYTHONPATh, not set correctly.
If i set it manually, everything works fine.

(test) mauri@bison:~$ export
PYTHONPATH="/home/mauri/envs/test/lib/python3.5/site-packages/"
(test) mauri@bison:~$ python -c "import django"
(test) mauri@bison:~$ env
XDG_VTNR=7
LC_PAPER=cs_CZ.UTF-8
LC_ADDRESS=cs_CZ.UTF-8
 XDG_SESSION_ID=c1
....

any idea why the PYTHONPATH is not set automatically when I create envs?

thank you so much, and sorry if I miss anything in the explaination, I m pretty new in this field.

Body:
Check your bash* if you have any alias overriding the python setup. You can easily check with the command alias from bash:

$ alias
alias ll='ls -alh'
alias ls='ls -G'
...


来源: stackexchange

问:
Parse Spanish characters in Objective-C using NSXmlParser
I am using NSXmlParser

I fetch all the data from server, but parsing do not end, because of the Spanish characters in the data. How do I completely parse these Spanish words?

答:
Are you sure the encoding of the document is correct?  What encoding does it use?  Does it include encoding="UTF-8" or some such in the <?xml ... ?> header?

If the XML parser doesn't know the encoding, or the encoding has been incorrectly specified, then it will fail to parse.

If these are encoded as XML entities, are the entities HEX-encoded, or named?  If they are named, they will need to be included in the DTD and you'll need to call setShouldResolveExternalEntities: with YES.

ContentLicense: CC BY-SA 2.5


问:
How to notify UI side from backend using WebApi?
I have to add text that shows the progress of the import. Right now we have the import bar to show progess but i need to add some text above the bar that say "Importing data- (# of # complete)."

For example, if we were importing 100 data, it might say "Importing data- (10 of 100 complete)."

Please suggest if any how we can show that in progress.

答:
For a simple solution, I think you can post your data by batches. Assume you have 100 data, then you post 10 data on each iteration, and OnSuccess function, you just update your UI. You may also need to be very careful for asynchronous requests and a rollback mechanism, it's somehow failed in an iteration, you need to erase your posted data.

Another approach is to go with some real time technologies, like SignalR

Hope my idea helps you somehow.

ContentLicense: CC BY-SA 3.0


问:
CSS center columns of text
I have some song lyrics in a
 with the following class:

```<code>.lyrics
{
    /* position */
    margin: 40px;

    /* text */
    font-size: 18px;
    text-align: center;
    column-width: 300px;
    column-gap: 0;
    column-fill: auto;
    height: 420px;
    max-height: 420px;
}
</code>```

Width of the entire div is constrained to 1120px, and height to 520px.

If lyrics fill 3 columns, it looks fine. However, if lyrics fill 2 columns, space for a third column is left empty.

Is there a way to leave 3-column lyrics as they are, but to center 2-column lyrics, keeping column spacing the same, without resorting to slicing lyrics in javascript and processing the layout myself?

Examples

Correct behaviour with 3-columns: https://jsfiddle.net/udc9d1go/2/

Incorrect behaviour with 2-columns: https://jsfiddle.net/45f23o82/

答: You can try to erase the height setting of the container. That way the height will be dynamic, i.e. according to the contents, and if the contents is simple text (in lines, not in seperate blocks), it should be distributed evenly across the three columns.

Title: CSS center columns of text

Body:
I have some song lyrics in a
 with the following class:

.lyrics
{
    /* position */
    margin: 40px;

    /* text */
    font-size: 18px;
    text-align: center;
    column-width: 300px;
    column-gap: 0;
    column-fill: auto;
    height: 420px;
    max-height: 420px;
}

Width of the entire div is constrained to 1120px, and height to 520px.

If lyrics fill 3 columns, it looks fine. However, if lyrics fill 2 columns, space for a third column is left empty.

Is there a way to leave 3-column lyrics as they are, but to center 2-column lyrics, keeping column spacing the same, without resorting to slicing lyrics in javascript and processing the layout myself?

Examples

Correct behaviour with 3-columns: https://jsfiddle.net/udc9d1go/2/

Incorrect behaviour with 2-columns: https://jsfiddle.net/45f23o82/


问:
saving and retrieving values from session state in asp.net
I am reviewing some web code and I am not exactly sure how ASP.net session state works. Any helps would be gratefully appreciated.

If a User object is saved to the session state during login, and User.FirstName and User.LastName is set. If other web pages retrieve the user object from the session and set the FirstName to something else is that persisted on other web pages? Or, do you need to re-add the user object back to the session once it has been modified? Thanks

答:
This should help you get your head around Sessions in ASP.Net

http://www.codeproject.com/KB/aspnet/ExploringSession.aspx
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net


问:
Reading infinite stream - tail

Problem:

Program to read the lines from infinite stream starting from its end of file.

#Solution:

```<code>import time
def tail(theFile):
    theFile.seek(0,2)   # Go to the end of the file
    while True:
        line = theFile.readline()
        if not line:
            time.sleep(10)    # Sleep briefly for 10sec
            continue
        yield line

if __name__ == '__main__':
    fd = open('./file', 'r+')
    for line in tail(fd):
        print(line)
</code>```

readline() is a non-blocking read, with if check for every line.

Question:

It does not make sense for my program running to wait infinitely, after the process writing to file has close()

1) What would be the EAFP approach for this code, to avoid if?

2) Can generator function return back on file close?

答:
@ChristianDean in his comment answered your first question quite nicely, so I'll answer your second.

I do believe it is possible - you can use theFile's closed attribute and raise a StopIteration exception if the file was closed. Like this:

```<code>def tail(theFile):
    theFile.seek(0, 2)
    while True:
        if theFile.closed:
            raise StopIteration

        line = theFile.readline()
        ...
        yield line
</code>```

Your loop shall cease when the file is closed and the exception is raised.

A more succinct method (thanks, Christian Dean) that does not involve an explicit exception is to test the file pointer in the loop header.

```<code>def tail(theFile):
    theFile.seek(0, 2)
    while not theFile.closed:
        line = theFile.readline()
        ...
        yield line
</code>```

Title: Reading infinite stream - tail

Body:
Problem:

Program to read the lines from infinite stream starting from its end of file.

#Solution:

import time
def tail(theFile):
    theFile.seek(0,2)   # Go to the end of the file
    while True:
        line = theFile.readline()
        if not line:
            time.sleep(10)    # Sleep briefly for 10sec
            continue
        yield line

if __name__ == '__main__':
    fd = open('./file', 'r+')
    for line in tail(fd):
        print(line)

readline() is a non-blocking read, with if check for every line.

Question:

It does not make sense for my program running to wait infinitely, after the process writing to file has close()

1) What would be the EAFP approach for this code, to avoid if?

2) Can generator function return back on file close?

Body:
@ChristianDean in his comment answered your first question quite nicely, so I'll answer your second.

I do believe it is possible - you can use theFile's closed attribute and raise a StopIteration exception if the file was closed. Like this:

def tail(theFile):
    theFile.seek(0, 2)
    while True:
        if theFile.closed:
            raise StopIteration

        line = theFile.readline()
        ...
        yield line

Your loop shall cease when the file is closed and the exception is raised.

A more succinct method (thanks, Christian Dean) that does not involve an explicit exception is to test the file pointer in the loop header.

def tail(theFile):
    theFile.seek(0, 2)
    while not theFile.closed:
        line = theFile.readline()
        ...
        yield line


问:
Can not start tomcat as user
I am using Centos7 with tomcat 7. I need to run tomcat as 'tomcat' user with systemd service script. I used the script from here

It works, but it throws exception as

```<code>56:40.051[%!-5.5p]: ##VelocityEngineInitializationException## --> (ConfigurationAndResourceIntializationHandler.java:78)
com.sz.api.common.exceps.VelocityEngineInitializationException: ##Exception##
        at com.sz.api.services.velocityengine.VelocityEngineHandler.initializeVelocityEngine(VelocityEngineHandler.java:64)
        at com.sz.api.engine.alert.bootup.ConfigurationAndResourceIntializationHandler.initializeVelocityEngine(ConfigurationAndResourceIntializationHandler.java:230)
        at com.sz.api.engine.alert.bootup.ConfigurationAndResourceIntializationHandler.configureHandler(ConfigurationAndResourceIntializationHandler.java:61)
        at com.sz.api.engine.alert.driver.AlertEngineDriver.startSystem(AlertEngineDriver.java:40)
        at com.sz.api.ws.bootstrap.StartUpService.initializeAlertEngine(StartUpService.java:309)
        at com.sz.api.ws.bootstrap.StartUpService.init(StartUpService.java:70)
        at javax.servlet.GenericServlet.init(GenericServlet.java:160)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1267)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1186)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1081)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
        at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
        at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
        at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
        at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
        at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107)
        at com.sz.api.services.velocityengine.VelocityEngineHandler.initializeVelocityEngine(VelocityEngineHandler.java:53)
        ... 22 more
Caused by: java.lang.RuntimeException: Error configuring Log4JLogChute :
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.velocity.util.ExceptionUtils.createWithCause(ExceptionUtils.java:67)
        at org.apache.velocity.util.ExceptionUtils.createRuntimeException(ExceptionUtils.java:45)
        at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:133)
        at org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85)
        at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
        ... 27 more
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
        at java.io.FileOutputStream.open(Native Method)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:142)
        at org.apache.log4j.FileAppender.setFile(FileAppender.java:294)
        at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:207)
        at org.apache.log4j.FileAppender.<init>(FileAppender.java:110)
        at org.apache.log4j.RollingFileAppender.<init>(RollingFileAppender.java:79)
        at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:118)
        ... 29 more
</code>```

Of course, I checked velocity.log permissions, all are fine. I am getting this error only when I run the tomcat as 'tomcat' user. Please advise!

答:
Try this:

Find the location of velocity.log:

```<code>$ cd /
$ find -name "velocity.log"
</code>```

Check the permission of velocity.log:

```<code>$ ls -la velocity.log
</code>```

If not appropriate, change the owner:

```<code>$ chown <user>:<group> velocity.log
</code>```

Title: Can not start tomcat as user

Body:
I am using Centos7 with tomcat 7. I need to run tomcat as 'tomcat' user with systemd service script. I used the script from here

It works, but it throws exception as

56:40.051[%!-5.5p]: ##VelocityEngineInitializationException## --> (ConfigurationAndResourceIntializationHandler.java:78)
com.sz.api.common.exceps.VelocityEngineInitializationException: ##Exception##
        at com.sz.api.services.velocityengine.VelocityEngineHandler.initializeVelocityEngine(VelocityEngineHandler.java:64)
        at com.sz.api.engine.alert.bootup.ConfigurationAndResourceIntializationHandler.initializeVelocityEngine(ConfigurationAndResourceIntializationHandler.java:230)
        at com.sz.api.engine.alert.bootup.ConfigurationAndResourceIntializationHandler.configureHandler(ConfigurationAndResourceIntializationHandler.java:61)
        at com.sz.api.engine.alert.driver.AlertEngineDriver.startSystem(AlertEngineDriver.java:40)
        at com.sz.api.ws.bootstrap.StartUpService.initializeAlertEngine(StartUpService.java:309)
        at com.sz.api.ws.bootstrap.StartUpService.init(StartUpService.java:70)
        at javax.servlet.GenericServlet.init(GenericServlet.java:160)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1267)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1186)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1081)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.Log4JLogChute with the current runtime configuration.
        at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
        at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
        at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
        at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
        at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107)
        at com.sz.api.services.velocityengine.VelocityEngineHandler.initializeVelocityEngine(VelocityEngineHandler.java:53)
        ... 22 more
Caused by: java.lang.RuntimeException: Error configuring Log4JLogChute :
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.apache.velocity.util.ExceptionUtils.createWithCause(ExceptionUtils.java:67)
        at org.apache.velocity.util.ExceptionUtils.createRuntimeException(ExceptionUtils.java:45)
        at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:133)
        at org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85)
        at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
        ... 27 more
Caused by: java.io.FileNotFoundException: velocity.log (Permission denied)
        at java.io.FileOutputStream.open(Native Method)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:142)
        at org.apache.log4j.FileAppender.setFile(FileAppender.java:294)
        at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:207)
        at org.apache.log4j.FileAppender.<init>(FileAppender.java:110)
        at org.apache.log4j.RollingFileAppender.<init>(RollingFileAppender.java:79)
        at org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:118)
        ... 29 more

Of course, I checked velocity.log permissions, all are fine. I am getting this error only when I run the tomcat as 'tomcat' user. Please advise!

Body:
Try this:

Find the location of velocity.log:

$ cd /
$ find -name "velocity.log"

Check the permission of velocity.log:

$ ls -la velocity.log

If not appropriate, change the owner:

$ chown <user>:<group> velocity.log


问:
How do the different compression levels of gzip differ?
I am trying to better understand how different compression levels  (1-9) of gzip differ in the way that encoding is implemented.

I've looked the zlib C source code and it seems that it has to do with how exhaustive the search for the longest matching string is, but looking for more specific information.

For example, do the levels yield any differences in the assignment of Huffman codes?

答:
From what I recall, yes, it is mainly based on the size of the buffer you'll be allocating. The larger the buffer, the better you can compress. If you can allocate a buffer with a size of about input file size × 1.2, then, in most cases, you will get the best compression possible with Huffman.

The reason is that the Huffman table will encompass all the bytes with the best possible outcome when you have such a large buffer. When the algorithm runs out of buffer space, then it needs to reset its table (there is a code in the stream added for that) and that means you start a new encoding table from scratch, which means you lose bytes to redesign that new table...

Although there are cases where resetting can be beneficial (i.e. many bytes set to value X in the first half of your file, and then many more that have value Y in the second half), it is rare that would happens.


问:
How to send and receive a large image using tcp (VB.NET)
I need to send and receive a large image between programs running on different machines within the same network.

I've looked at using upd. However, I ran into problems with the size of the packets and (after breaking the image into smaller pieces to get past this problem) the number of packets needing to be processed all at once - and ultimately packet loss.

I've also thought of sending the image by storing it in a common file folder and receiving it by using file watcher as a trigger. However, this just adds further complexities in setup where common folders don't already exist.

Assuming I'm barking up the right tree looking at TCP, can someone point me to/provide an example of how to send an image file using it (VB.NET would be ideal). Also, are there practical limits to TCP package sizes?

If I am not barking up the right tree, and there is an easier way to do this I'd surely appreciate some guidance/examples.

答:
Consider using WCF (Windows Communication Foundation) with TCP binding. You can even use streaming mode. You don't need to worry about packet size, etc. You only need to be careful about the size of the image. You will need to modify some settings in the service configuration file to allow large messages to be sent.

You can make a proof-of-concept application within a day (no fancy UI, just the absolute minimum functionality). And that is because you are new to the technology. Someone that has worked with WCF beore can do it in about one hour at normal speed.


问:
LibGDX / Box2d - only one rectangle is being rendered by debugrenderer
I'm revisiting LibGDX game programming and I am unfortunately having to re-learn stuff I used to know.

I'm currently using Tiled Map Editor to make a very simple Donkey Kong style level. I have around 20 rectangles in total for the level.

I've created a box2d world in my main GameScreen class and have a for loop to get the rectangle objects into the world and debugrenderer.

My problem is that only the bottom (and first) rectangle I drew is showing up. I have checked the scale, also I put a println() which tells me the object information has been parsed with all the rectangles info showing correct (ie. the rectangles x,y,w,h values) but as I say, only one rectangle shows up on the debugrenderer.

I've just got back into programming after around 6month break and so I'm hoping i've missed something simple. The same code in my old projects still works fine as I've tested some.

Here is my code, any help is massively appreciated. Thanks

```<code>public class GameScreen implements Screen {
    SpriteBatch spriteBatch;
    OrthographicCamera cam;
    Viewport v;

    TmxMapLoader mapLoader;
    TiledMap map;
    OrthogonalTiledMapRenderer mapRenderer;

    World world;
    Box2DDebugRenderer b2dr;
    float mapScale = 10f/140f;

    public GameScreen(){
        spriteBatch = new SpriteBatch();
        cam = new OrthographicCamera();
        v = new FitViewport(Constants.V_WIDTH, Constants.V_HEIGHT, cam);
        cam.setToOrtho(false, v.getWorldWidth(), v.getWorldHeight());

        mapLoader = new TmxMapLoader();
        map = mapLoader.load("level1.tmx");
        mapRenderer = new OrthogonalTiledMapRenderer(map, mapScale);

        world = new World(new Vector2(0,-9.8f), true);
        b2dr = new Box2DDebugRenderer();

        // box2d local variables
        BodyDef bdef = new BodyDef();
        PolygonShape shape = new PolygonShape();
        FixtureDef fdef = new FixtureDef();
        Body body;

        // create platform object rectangles
        for (MapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
            Rectangle rect = ((RectangleMapObject)object).getRectangle();

            bdef.type = BodyDef.BodyType.StaticBody;
            bdef.position.set(rect.getX() + rect.getWidth() / 2 * mapScale, rect.y + rect.getHeight() / 2 * mapScale);

            body = world.createBody(bdef);

            shape.setAsBox(rect.getWidth() / 2 * mapScale, rect.getHeight() / 2 * mapScale);
            fdef.shape = shape;

            body.createFixture(fdef);

        }
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        update(delta);
        clearScreen();
        draw();
    }

    public void update(float dt){
        mapRenderer.setView(cam);
    }

    public void clearScreen(){
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }

    public void draw(){
        spriteBatch.setProjectionMatrix(cam.combined);
        mapRenderer.render();
        b2dr.render(world, cam.combined);

        spriteBatch.begin();

        spriteBatch.end();
    }

    @Override
    public void resize(int width, int height) {
        v.update(width, height);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        spriteBatch.dispose();
    }
}
</code>```

答:
Sorry for wasting time here. I have fixed this.

It was just that I hadnt applied the scale of the map also to the x,y of the rectangles. So i change one line like so, and now it works:

```<code>  bdef.position.set(rect.getX() * mapScale + rect.getWidth() / 2 * mapScale, rect.y * mapScale + rect.getHeight() / 2 * mapScale);
</code>```

Body:
I'm revisiting LibGDX game programming and I am unfortunately having to re-learn stuff I used to know.

I'm currently using Tiled Map Editor to make a very simple Donkey Kong style level. I have around 20 rectangles in total for the level.

I've created a box2d world in my main GameScreen class and have a for loop to get the rectangle objects into the world and debugrenderer.

My problem is that only the bottom (and first) rectangle I drew is showing up. I have checked the scale, also I put a println() which tells me the object information has been parsed with all the rectangles info showing correct (ie. the rectangles x,y,w,h values) but as I say, only one rectangle shows up on the debugrenderer.

I've just got back into programming after around 6month break and so I'm hoping i've missed something simple. The same code in my old projects still works fine as I've tested some.

Here is my code, any help is massively appreciated. Thanks

public class GameScreen implements Screen {
    SpriteBatch spriteBatch;
    OrthographicCamera cam;
    Viewport v;

    TmxMapLoader mapLoader;
    TiledMap map;
    OrthogonalTiledMapRenderer mapRenderer;

    World world;
    Box2DDebugRenderer b2dr;
    float mapScale = 10f/140f;

    public GameScreen(){
        spriteBatch = new SpriteBatch();
        cam = new OrthographicCamera();
        v = new FitViewport(Constants.V_WIDTH, Constants.V_HEIGHT, cam);
        cam.setToOrtho(false, v.getWorldWidth(), v.getWorldHeight());

        mapLoader = new TmxMapLoader();
        map = mapLoader.load("level1.tmx");
        mapRenderer = new OrthogonalTiledMapRenderer(map, mapScale);

        world = new World(new Vector2(0,-9.8f), true);
        b2dr = new Box2DDebugRenderer();

        // box2d local variables
        BodyDef bdef = new BodyDef();
        PolygonShape shape = new PolygonShape();
        FixtureDef fdef = new FixtureDef();
        Body body;

        // create platform object rectangles
        for (MapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
            Rectangle rect = ((RectangleMapObject)object).getRectangle();

            bdef.type = BodyDef.BodyType.StaticBody;
            bdef.position.set(rect.getX() + rect.getWidth() / 2 * mapScale, rect.y + rect.getHeight() / 2 * mapScale);

            body = world.createBody(bdef);

            shape.setAsBox(rect.getWidth() / 2 * mapScale, rect.getHeight() / 2 * mapScale);
            fdef.shape = shape;

            body.createFixture(fdef);

        }
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        update(delta);
        clearScreen();
        draw();
    }

    public void update(float dt){
        mapRenderer.setView(cam);
    }

    public void clearScreen(){
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }

    public void draw(){
        spriteBatch.setProjectionMatrix(cam.combined);
        mapRenderer.render();
        b2dr.render(world, cam.combined);

        spriteBatch.begin();

        spriteBatch.end();
    }

    @Override
    public void resize(int width, int height) {
        v.update(width, height);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        spriteBatch.dispose();
    }
}

Body:
Sorry for wasting time here. I have fixed this.

It was just that I hadnt applied the scale of the map also to the x,y of the rectangles. So i change one line like so, and now it works:

  bdef.position.set(rect.getX() * mapScale + rect.getWidth() / 2 * mapScale, rect.y * mapScale + rect.getHeight() / 2 * mapScale);


问:
javascript If-Else Statement skip If condition
As you can see in the picture the value of the r.SalaryGrade is null. Why it skip my IF condition and goes to Else?. I make sure that if is an empty string and null it will add a class to a textbox. Did I do something wrong?.

```<code> if (r.SalaryGrade == "" && r.SalaryGrade == null) { $("#JobGradeId").addClass('validation'); }
 else { $("#JobGradeId").removeClass('validation'); }
</code>```

答:
Your if condition has an "&&" in it.

```<code>'' and null are different things
</code>```

You need to change how you structure that if statement. You could do something like,

```<code>r.SalaryGrade == "" || r.SalaryGrade == null
</code>```

Body:
As you can see in the picture the value of the r.SalaryGrade is null. Why it skip my IF condition and goes to Else?. I make sure that if is an empty string and null it will add a class to a textbox. Did I do something wrong?.

 if (r.SalaryGrade == "" && r.SalaryGrade == null) { $("#JobGradeId").addClass('validation'); }
 else { $("#JobGradeId").removeClass('validation'); }

Body:
Your if condition has an "&&" in it.

'' and null are different things

You need to change how you structure that if statement. You could do something like,

r.SalaryGrade == "" || r.SalaryGrade == null


问:
Recalculating values with jQuery on orientation change not working
I have created the function in order to deal with some full screen sizing issues on mobile devices. It works very well however does not recalculate the value for height more than once (only calculated on load and not on orientation change). I added the alert to demonstrate that it is not running the calculation more than once. Any help here with allowing for the calculation of this value on each orientation change would be greatly appreciated.

jQuery: (Only runs on mobile devices or inspect mobile configuration)

```<code>function resizeBackground() {
    $(".header__container").removeAttr('style');
    var fixedHeight = $(window).height();
    var bg = $(".home-carousel, .flickity-viewport, .flickity-slider, .carousel-cell, .header__container, .site-header--drawer .nav-bar");
    var softScroll = $(".soft__scroll--container");
    var squiggle = $(".squiggle__container");
    var slideNumbers = $(".slide__numbers");

    bg.height(fixedHeight);
    softScroll.css('top', fixedHeight - 50 + "px");
    slideNumbers.css('top', fixedHeight - 140 + "px");
    squiggle.css('padding-top', 10 + "px");
    console.log(fixedHeight);
}

if(isMobile.any()) {
    $(window).on("load resize", function(event) {
        resizeBackground();
    });
}
</code>```

答:
You expect .header__container to change height when orientationchange, load or resize fire on $(window).

It would...  if it didn't have a height set inside the style attribute, applied by the previous run of resizeBackground() (from bg.height(fixedHeight);).

You need to remove this attribute first, to allow .header__container to resize and give you the correct, updated .height().

Add this as the first line in resizeBackground() and it will work as intended:

$(".header__container").removeAttr('style');
```

<p>You can see the script working properly in this recording: https://youtu.be/z2spumFbuRs</p>

<hr>

<p>Alternatively, you might want to define <code>fixedHeight</code> as:</p>

```var fixedHeight = $(window).height();
```

... which will be slightly less expensive, since it doesn't imply DOM manipulation and resizing before getting the header height (which happens to be 100vh after style is removed).

One last thing: if you bind on resize there is no point in binding on orientationchange, as orientationchange cannot occur without a resize. Additionally, you might want to debounce calls to resizeBackground() and not allow it to run more than 20 times/second.

Body:
I have created the function in order to deal with some full screen sizing issues on mobile devices. It works very well however does not recalculate the value for height more than once (only calculated on load and not on orientation change). I added the alert to demonstrate that it is not running the calculation more than once. Any help here with allowing for the calculation of this value on each orientation change would be greatly appreciated.

jQuery: (Only runs on mobile devices or inspect mobile configuration)

function resizeBackground() {
    $(".header__container").removeAttr('style');
    var fixedHeight = $(window).height();
    var bg = $(".home-carousel, .flickity-viewport, .flickity-slider, .carousel-cell, .header__container, .site-header--drawer .nav-bar");
    var softScroll = $(".soft__scroll--container");
    var squiggle = $(".squiggle__container");
    var slideNumbers = $(".slide__numbers");

    bg.height(fixedHeight);
    softScroll.css('top', fixedHeight - 50 + "px");
    slideNumbers.css('top', fixedHeight - 140 + "px");
    squiggle.css('padding-top', 10 + "px");
    console.log(fixedHeight);
}

if(isMobile.any()) {
    $(window).on("load resize", function(event) {
        resizeBackground();
    });
}

Body:
You expect .header__container to change height when orientationchange, load or resize fire on $(window).

It would...  if it didn't have a height set inside the style attribute, applied by the previous run of resizeBackground() (from bg.height(fixedHeight);).

You need to remove this attribute first, to allow .header__container to resize and give you the correct, updated .height().

Add this as the first line in resizeBackground() and it will work as intended:

$(".header__container").removeAttr('style');

You can see the script working properly in this recording: https://youtu.be/z2spumFbuRs

Alternatively, you might want to define fixedHeight as:

var fixedHeight = $(window).height();

... which will be slightly less expensive, since it doesn't imply DOM manipulation and resizing before getting the header height (which happens to be 100vh after style is removed).

One last thing: if you bind on resize there is no point in binding on orientationchange, as orientationchange cannot occur without a resize. Additionally, you might want to debounce calls to resizeBackground() and not allow it to run more than 20 times/second.


问:
SQLite query returns only one row JDBC JAVA database

I have read the previous questions but none of them seem to match my problem although they might seem similar at first. :/_

So, I am working on a local database on Java(JDBC). When I press a button I should be getting the result of a "SELECT" query. So far so good, but for some reason which my beginner brain does not understand I keep getting only one row from the query. I have even run the same exact query on "DB Browser for SQLite" and it returns the correct result (1+ rows) .
So this is the method I am using to get the result of the query:

```<code>public ResultSet returnBill(int no) throws SQLException{
    String sql = "SELECT * FROM billList WHERE no = " + no + " ;";
    ResultSet thisSet =  stmt.executeQuery(sql); // stmt is a 'Statement' type variable
    return thisSet;
}
</code>```

The method does not crash but it only returns the very first row of a query which should return more than 2 ( while (thisSet.next())  RUNS ONCE). I run other "SELECT" queries on the program which are supposed to return more than one rows and they all work fine so it's not a matter of not being able to start/close the connection etc.

Below is the method being used:

```<code>int number  =  table.getModel().getValueAt(rows, 0);
ResultSet thisSet =  db.returnBill(number);
while (thisSet.next()){
        String name = thisSet.getString("name");
        int quantity = thisSet.getInt("quantity");
        // do something with the returned data
}
</code>```

So I get this magical number from a table (of course I made sure it's not 0, -1 etc.) and I run a query using that number. You could think of the structure of the table consisting of columns :

number |  name  | quantity  |

where 'number' is nonzero.
I understand that probably using this method to run a query on a DB might not be safe or might post security threats but it's not the case right now. I have been working on this project for quite a long time already and I have been through many silly mistakes and I think this is yet one of them. Any help is APPRECIATED ! :D

答:
So yes, it was a silly mistake as I expected.
So I had previously initiated a variable

```<code>Database db = new Database();
</code>```

which opened the database for 2 queries (the SELECT query and an UPDATE query on another table as shown)  which would then be closed at the end of the following code.

When I removed this UPDATE query however the loop executed the correct amount of times. So it seems like the SQLite JDBC is somehow prone to running a SELECT and UPDATE query on the same Statement (as far as my super mega* brain perceives it.)

So I created 2 connections at the very beginning and closed them at the end using one of them for the SELECT and the other one for the UPDATE query:

```<code>Database db = new Database(); // open database
Database db2 = new Database(); // open another creepy one :/

int number  =  table.getModel().getValueAt(rows, 0);
ResultSet thisSet =  db.returnBill(number);
while (thisSet.next()){
        String name = thisSet.getString("name");
        int quantity = thisSet.getInt("quantity");
        // do something with the returned data
        // --------> STUPIDO <----------
        //** Now executing an UPDATE query on db2 :
        // ex.: UPDATE anotherTable SET amount = (current+ "+ quantity+") WHERE name= '" + name+ "' ;";
}
db.closeConn(); // close db ++
db2.closeConn(); // closes db 2
</code>```

I don't know if this is the best approach but it solved my problem, so I'm leaving it so probably it could help. Any suggestions though would be welcomed :D

Body:
I have read the previous questions but none of them seem to match my problem although they might seem similar at first. :/_

So, I am working on a local database on Java(JDBC). When I press a button I should be getting the result of a "SELECT" query. So far so good, but for some reason which my beginner brain does not understand I keep getting only one row from the query. I have even run the same exact query on "DB Browser for SQLite" and it returns the correct result (1+ rows) .
So this is the method I am using to get the result of the query:

public ResultSet returnBill(int no) throws SQLException{
    String sql = "SELECT * FROM billList WHERE no = " + no + " ;";
    ResultSet thisSet =  stmt.executeQuery(sql); // stmt is a 'Statement' type variable
    return thisSet;
}

The method does not crash but it only returns the very first row of a query which should return more than 2 ( while (thisSet.next())  RUNS ONCE). I run other "SELECT" queries on the program which are supposed to return more than one rows and they all work fine so it's not a matter of not being able to start/close the connection etc.

Below is the method being used:

int number  =  table.getModel().getValueAt(rows, 0);
ResultSet thisSet =  db.returnBill(number);
while (thisSet.next()){
        String name = thisSet.getString("name");
        int quantity = thisSet.getInt("quantity");
        // do something with the returned data
}

So I get this magical number from a table (of course I made sure it's not 0, -1 etc.) and I run a query using that number. You could think of the structure of the table consisting of columns :

number |  name  | quantity  |

where 'number' is nonzero.
I understand that probably using this method to run a query on a DB might not be safe or might post security threats but it's not the case right now. I have been working on this project for quite a long time already and I have been through many silly mistakes and I think this is yet one of them. Any help is APPRECIATED ! :D

Body:
So yes, it was a silly mistake as I expected.
So I had previously initiated a variable

Database db = new Database();

which opened the database for 2 queries (the SELECT query and an UPDATE query on another table as shown)  which would then be closed at the end of the following code.

When I removed this UPDATE query however the loop executed the correct amount of times. So it seems like the SQLite JDBC is somehow prone to running a SELECT and UPDATE query on the same Statement (as far as my super mega* brain perceives it.)

So I created 2 connections at the very beginning and closed them at the end using one of them for the SELECT and the other one for the UPDATE query:

Database db = new Database(); // open database
Database db2 = new Database(); // open another creepy one :/

int number  =  table.getModel().getValueAt(rows, 0);
ResultSet thisSet =  db.returnBill(number);
while (thisSet.next()){
        String name = thisSet.getString("name");
        int quantity = thisSet.getInt("quantity");
        // do something with the returned data
        // --------> STUPIDO <----------
        //** Now executing an UPDATE query on db2 :
        // ex.: UPDATE anotherTable SET amount = (current+ "+ quantity+") WHERE name= '" + name+ "' ;";
}
db.closeConn(); // close db ++
db2.closeConn(); // closes db 2

I don't know if this is the best approach but it solved my problem, so I'm leaving it so probably it could help. Any suggestions though would be welcomed :D


问:
Creating “CSS” with “PHP”
I am trying to create inline CSS using PHP Not sure why it is not working
I need to be to write the css based on the data coming from my database This was a test script to see if I could put php between style tags and create css </p>

```<code><!DOCTYPE html>
<html>
<head>
<style>
*{padding-right: 0px; PADDING-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px;}

<?php
echo "<br/>";
echo '.button { ';
echo "<br/>";
echo 'background-color: green;';
echo "<br/>";
echo 'border: none;';
echo "<br/>";
echo 'color: white;';
echo "<br/>";
echo 'padding: 15px 32px;';
echo "<br/>";
echo 'text-align: center;';
echo "<br/>";
echo 'text-decoration: none;';
echo "<br/>";
echo 'display: inline-block;';
echo "<br/>";
echo 'font-size: 16px;';
echo "<br/>";
echo 'margin: 4px 2px;';
echo "<br/>";
echo 'cursor: pointer;';
echo "<br/>";
echo '} ';
echo "<br/>";
?>

</style>
</head>
<body>

<h2>CSS Buttons</h2>

<button>Default Button</button>
<a href="#" class="button">Link Button</a>
<button class="button">Button</button>
<input type="button" class="button" value="Input Button">

</body>
</html>
</code>```

答:
You're creating invalid CSS by putting all those
 tags in the CSS. Use echo "\n"; instead, to put actual newlines. Or just leave them out -- CSS doesn't care if the styles are on the same line or not.

Title: Creating “CSS” with “PHP”

Body:
I am trying to create inline CSS using PHP Not sure why it is not working
I need to be to write the css based on the data coming from my database This was a test script to see if I could put php between style tags and create css

<!DOCTYPE html>

CSS Buttons

<button>Default Button</button>
Link Button
<button class="button">Button</button>
<input type="button" class="button" value="Input Button">

Body: You're creating invalid CSS by putting all those <br/> tags in the CSS. Use echo "\n"; instead, to put actual newlines. Or just leave them out -- CSS doesn't care if the styles are on the same line or not.


问:
Set status bar to light content and dynamically show/hide (UITabBarController with UINavigationControllers)
I have a UITabBarController as the root view controller. Each tab has a view controller embedded inside of a navigation controller. My navigation bars are a dark color so I need the status bar to be set to .lightContent. I also need to hide the status bar dynamically.

If I set "View controller-based status bar appearance" to "NO", I can set the status bar correctly to ".lightContent", but I cannot hide the status bar dynamically.

If I set "View controller-based status bar appearance" to "YES", the status bar will only set to ".lightContent" if a navigation bar is NOT present.

This is what I use in each view controller to show or hide the status bar:

```<code>var shouldHideStatusBar: Bool = false {
    didSet { self.setNeedsStatusBarAppearanceUpdate() }
}
override var prefersStatusBarHidden: Bool { return shouldHideStatusBar }
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide }
override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
</code>```

I have also tried:

navigationController?.navigationBar.barStyle = .black

There must be something I am missing in order to set the status bar to .lightContent and still be able to dynamically show and hide the status bar.

答:
Resulted to using a deprecated method:

```<code>UIApplication.shared.setStatusBarHidden(true, with: .slide)
</code>```

Not ideal, but works. Hopefully, someone has a solution without relying on a deprecated method.

Body:
I have a UITabBarController as the root view controller. Each tab has a view controller embedded inside of a navigation controller. My navigation bars are a dark color so I need the status bar to be set to .lightContent. I also need to hide the status bar dynamically.

If I set "View controller-based status bar appearance" to "NO", I can set the status bar correctly to ".lightContent", but I cannot hide the status bar dynamically.

If I set "View controller-based status bar appearance" to "YES", the status bar will only set to ".lightContent" if a navigation bar is NOT present.

This is what I use in each view controller to show or hide the status bar:

var shouldHideStatusBar: Bool = false {
    didSet { self.setNeedsStatusBarAppearanceUpdate() }
}
override var prefersStatusBarHidden: Bool { return shouldHideStatusBar }
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide }
override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }

I have also tried:

navigationController?.navigationBar.barStyle = .black

There must be something I am missing in order to set the status bar to .lightContent and still be able to dynamically show and hide the status bar.

Body:
Resulted to using a deprecated method:

UIApplication.shared.setStatusBarHidden(true, with: .slide)

Not ideal, but works. Hopefully, someone has a solution without relying on a deprecated method.


问:
Optional was found nil when downloading image using DispatchQueue swift 3
I am using DispatchQueue.global() to download images from urls that are stored in an array url, these are the steps:

```<code>Array of urls --> let data = contentsOf: array[url] --> display img
</code>```

however I get an error like, check the image below:

and this is what gets print out:

```<code>fatal error: unexpectedly found nil while unwrapping an Optional value
</code>```

code in text format:

```<code>func updateView(){

    for i in 0..<testArray1.count {

        let ImgUrl = URL (string: testArray1[i])!

        DispatchQueue.global().async {

            do {

                let data = try Data(contentsOf: ImgUrl)
                DispatchQueue.global().sync {

                    self.imgArr.append(UIImage(data: data)!)

                }

            } catch {
                //handle the error
            }
        }

    }
}
</code>```

hope this can help you help me.

thank you in advanced

答:
It's possible that you got that data but not failed to create the image. Try this</p>

```<code>        DispatchQueue.global().sync {
            for i in 0..<testArray1.count {
                let imgUrl = URL(string: testArray1[i])!

                do {
                    let data = try Data(contentsOf: imgUrl as URL)
                    if let image = UIImage(data: data) {
                        imgArr.append(image)
                    }
                } catch {
                    print("Unable to load data: \(error)")
                }
            }
        }
</code>```

Body:
I am using DispatchQueue.global() to download images from urls that are stored in an array url, these are the steps:

Array of urls --> let data = contentsOf: array[url] --> display img

however I get an error like, check the image below:

and this is what gets print out:

fatal error: unexpectedly found nil while unwrapping an Optional value

code in text format:

func updateView(){

    for i in 0..<testArray1.count {

        let ImgUrl = URL (string: testArray1[i])!

        DispatchQueue.global().async {

            do {

                let data = try Data(contentsOf: ImgUrl)
                DispatchQueue.global().sync {

                    self.imgArr.append(UIImage(data: data)!)

                }

            } catch {
                //handle the error
            }
        }

    }
}

hope this can help you help me.

thank you in advanced

Body:
It's possible that you got that data but not failed to create the image. Try this

        DispatchQueue.global().sync {
            for i in 0..<testArray1.count {
                let imgUrl = URL(string: testArray1[i])!

                do {
                    let data = try Data(contentsOf: imgUrl as URL)
                    if let image = UIImage(data: data) {
                        imgArr.append(image)
                    }
                } catch {
                    print("Unable to load data: \(error)")
                }
            }
        }


问:
Simple Android searchbar into a string
MY GOAL:take whatever was placed into the search bar and then turn it into a string which can be a variable used across multiple activities. I am wondering on line 92 , would i need a if statement of some sort to see if there are any integers passed. That then would need to be converted into a string. Or Would the code work fine the way it is. Thank you for reading!

package com.karanvir.search;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    Intent intentGoogle;
    Random rn;
    SharedPreferences urls;
    AutoCompleteTextView searchBar;
    public static String urlGlobal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        searchBar=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        Button button=(Button) findViewById(R.id.button);
        Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
         rn= new Random();

        urls=this.getSharedPreferences("com.karanvir.search", Context.MODE_PRIVATE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings4) {
            startActivity(intentGoogle);

            return true;
        } else if(id ==R.id.action_settings2){

            return true;

        }else if (id==R.id.action_settings3){

            return true;

        }else if(id==R.id.action_settings1){
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.alert_dark_frame)
                    .setTitle("About")
                    .setMessage("stuff");
                    return true;

        }

        return super.onOptionsItemSelected(item);
    }

    public void jump(View view){
        //intnet changing target of our code
urlGlobal=searchBar.getText().toString();
        if

        //public static String urlGlobal=

       /* urls.edit().putString("url",searchBar.getText().toString()).apply();
        String Stringurls=urls.getString("url","");*/

        int pageJump = rn.nextInt(3)+1;
        if (pageJump==1){
            startActivity(intentGoogle);
        } else if (pageJump==2){

        } else if(pageJump==3){

        }

    }
}```

答: Turns out it does convert it into a string so there is no need for further complications.</p>

Title: Simple Android searchbar into a string


问:
Vue.js / webpack: how do I clear out old bundle main-*.js files when hot-reload transpiles them?
I'm using Vue.js to make an SPA application with Django and I transpile, uglify, and bundle the code using webpack (specifically webpack-simple from vue-cli setup).

I use the following to "watch" and hot-reload the code:

```<code>$ ./node_modules/.bin/webpack --config webpack.config.js --watch
</code>```

The problem is every time I change the code and it gets built it generates a new bundle .js file and updates webpack-stats.json to point to that one, but doesn't delete the old ones. How do I have it delete the old (useless) files?

webpack.config.js:

```<code>var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')

function resolve (dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    context: __dirname,

    // entry point of our app.
    // assets/js/index.js should require other js modules and dependencies it needs
    entry: './src/main',

    output: {
            path: path.resolve('./static/bundles/'),
            filename: "[name]-[hash].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        }),
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
            {test: /\.vue$/, loader: 'vue-loader'}

        ],
    },

    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
}
</code>```

webpack-stats.json:

```<code>{
   "status":"done",
   "chunks":{
      "main":[
         {
            "name":"main-faa72a69b29c1decd182.js",
            "path":"/Users/me/Code/projectname/static/bundles/main-faa72a69b29c1decd182.js"
         }
      ]
   }
}
</code>```

Also what's a good way to add this to git/source control? Otherwise it changes everytime and I have to add it like so:

```<code>$ git add static/bundles/main-XXXXX.js -f
</code>```

which gets annoying.

Any pointers? Thanks!

答:
You should adjust webpack so a new bundle is only being created when actually building for production.

From the webpack-simple vue-cli template, you'll see that uglifying and minifying only take place when it is set to a production env, not a dev env:

```<code>if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
</code>```

Body:
I'm using Vue.js to make an SPA application with Django and I transpile, uglify, and bundle the code using webpack (specifically webpack-simple from vue-cli setup).

I use the following to "watch" and hot-reload the code:

$ ./node_modules/.bin/webpack --config webpack.config.js --watch

The problem is every time I change the code and it gets built it generates a new bundle .js file and updates webpack-stats.json to point to that one, but doesn't delete the old ones. How do I have it delete the old (useless) files?

webpack.config.js:

var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')

function resolve (dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    context: __dirname,

    // entry point of our app.
    // assets/js/index.js should require other js modules and dependencies it needs
    entry: './src/main',

    output: {
            path: path.resolve('./static/bundles/'),
            filename: "[name]-[hash].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        }),
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
            {test: /\.vue$/, loader: 'vue-loader'}

        ],
    },

    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
}

webpack-stats.json:

{
   "status":"done",
   "chunks":{
      "main":[
         {
            "name":"main-faa72a69b29c1decd182.js",
            "path":"/Users/me/Code/projectname/static/bundles/main-faa72a69b29c1decd182.js"
         }
      ]
   }
}

Also what's a good way to add this to git/source control? Otherwise it changes everytime and I have to add it like so:

$ git add static/bundles/main-XXXXX.js -f

which gets annoying.

Any pointers? Thanks!

Body:
You should adjust webpack so a new bundle is only being created when actually building for production.

From the webpack-simple vue-cli template, you'll see that uglifying and minifying only take place when it is set to a production env, not a dev env:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}


答:
r.salaryGrade = "" as the first conditional passed, therefore it cannot be equal to null ( as it HAS a value of "" which is not null ).

You can change the && to an || and if either is true it will continue on.

Title: javascript If-Else Statement skip If condition


问:
Uploading files to Sails.js server using FormData
I'm using react-dropzone to upload multiple files to a Sails.js server. Since react-dropzone gives me the list of dropped files, I'm appending them to a FormData object. With this, when the request hits the server, the req.file('myfile').upload() won't work, since I don't have any input[type=file] on the page and I'm working with AJAX. My question is: Does Skipper have any method to handle FormData uploads or I need to use Multer or something like that?

答:
Well... in the end, I was using FormData the wrong way. If anyone out there aren't seeing the files array in the server, just make sure to not use brackets in the key you append to FormData.</p>

```<code>// Incorrect
formdata.append('files[]', file)

// Correct
formdata.append('files', file)
</code>```

Body:
Well... in the end, I was using FormData the wrong way. If anyone out there aren't seeing the files array in the server, just make sure to not use brackets in the key you append to FormData.

// Incorrect
formdata.append('files[]', file)

// Correct
formdata.append('files', file)


问:
Is Rectangle A = Rectangle(3, 4); equivalent to Rectangle A(3,4);?
Below is my code:

```<code>#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}
</code>```

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!

答:
In this case, there's a significant difference between what actually happens, and what theoretically sort of happens.

The first is simple: Rectangle A(3, 4); just constructs a Rectangle with width and height initialized to 3 and 4. It's all done in "one step" using the Rectangle(int, int); constructor you defined. Simple and straightforward--so it's what's generally preferred and recommended when it's possible.

Then let's consider: Rectangle B = Rectangle(3,4);. In theory, this constructs a temporary object, then copy-constructs B from that temporary.

In practice, what happens is that the compiler checks that it would be able to create the temporary object, and that it would be able to use the copy constructor to initialize B from that temporary. Having checked that this would be possible, nearly any competent compiler (at least when optimization is enabled, and often even when it's not) will generate code essentially identical to what it did for creating A.

If, however, you delete the copy constructor, by adding:

```<code>Rectangle(Rectangle const &) = delete;
</code>```

...then the compiler will find that it can't copy construct B from the temporary, and will refuse to compile the code. Even if the final, generated code never actually uses the copy constructor, it has to be available for this to work.

Finally, let's look at your third example (with the syntax corrected):

```<code>Rectangle *C = new Rectangle(3, 4);
</code>```

Despite looking somewhat like the line above that created B, the construction involved is really much more like the previous one that you used to create A. Only one object is (even theoretically) created. It's allocated from the free store and directly initialized using your Rectangle(int, int); constructor.

Then the address of that object is used to initialize C (which is only a pointer). Like the initialization of A, this will work even if Rectangle's copy constructor is deleted, because even in theory there's no copying of a Rectangle involved.

None of these involves an assignment operator. If you were to delete the assignment operator:

```<code>Rectangle &operator=(Rectangle const &) = delete;
</code>```

...all this code would still be fine, because (despite the use of the =) there's no assignment anywhere in the code.

To use an assignment (if you really insisted on doing so) you could (for example) do something like:

```<code>Rectangle A(3, 4);
Rectangle B = Rectangle(5, 6);
B = A;
</code>```

This still uses only constructors to create and initialize A and B, but then uses the assignment operator to assign the value of A to B. In this case, if you deleted the assignment operator as shown above, the code would fail (would not compile).

Some of our misunderstanding seems to stem from the fact that the compiler with automatically create "special member functions" for you if you don't do something to prevent it from doing so. One of the ways you can prevent it from doing so is the = delete; syntax shown above, but that's not the only one. For example, if your class includes a member variable of reference type, the compiler won't create an assignment operator for you. If you start with something simple like this:

```<code>struct Rectangle {
    int width, height;
};
</code>```

...the compiler will generate a default constructor, copy constructor, move constructor, copy assignment and move assignment operators, all entirely automatically.

Body:
Below is my code:

#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!

Body:
In this case, there's a significant difference between what actually happens, and what theoretically sort of happens.

The first is simple: Rectangle A(3, 4); just constructs a Rectangle with width and height initialized to 3 and 4. It's all done in "one step" using the Rectangle(int, int); constructor you defined. Simple and straightforward--so it's what's generally preferred and recommended when it's possible.

Then let's consider: Rectangle B = Rectangle(3,4);. In theory, this constructs a temporary object, then copy-constructs B from that temporary.

In practice, what happens is that the compiler checks that it would be able to create the temporary object, and that it would be able to use the copy constructor to initialize B from that temporary. Having checked that this would be possible, nearly any competent compiler (at least when optimization is enabled, and often even when it's not) will generate code essentially identical to what it did for creating A.

If, however, you delete the copy constructor, by adding:

Rectangle(Rectangle const &) = delete;

...then the compiler will find that it can't copy construct B from the temporary, and will refuse to compile the code. Even if the final, generated code never actually uses the copy constructor, it has to be available for this to work.

Finally, let's look at your third example (with the syntax corrected):

Rectangle *C = new Rectangle(3, 4);

Despite looking somewhat like the line above that created B, the construction involved is really much more like the previous one that you used to create A. Only one object is (even theoretically) created. It's allocated from the free store and directly initialized using your Rectangle(int, int); constructor.

Then the address of that object is used to initialize C (which is only a pointer). Like the initialization of A, this will work even if Rectangle's copy constructor is deleted, because even in theory there's no copying of a Rectangle involved.

None of these involves an assignment operator. If you were to delete the assignment operator:

Rectangle &operator=(Rectangle const &) = delete;

...all this code would still be fine, because (despite the use of the =) there's no assignment anywhere in the code.

To use an assignment (if you really insisted on doing so) you could (for example) do something like:

Rectangle A(3, 4);
Rectangle B = Rectangle(5, 6);
B = A;

This still uses only constructors to create and initialize A and B, but then uses the assignment operator to assign the value of A to B. In this case, if you deleted the assignment operator as shown above, the code would fail (would not compile).

Some of our misunderstanding seems to stem from the fact that the compiler with automatically create "special member functions" for you if you don't do something to prevent it from doing so. One of the ways you can prevent it from doing so is the = delete; syntax shown above, but that's not the only one. For example, if your class includes a member variable of reference type, the compiler won't create an assignment operator for you. If you start with something simple like this:

struct Rectangle {
    int width, height;
};

...the compiler will generate a default constructor, copy constructor, move constructor, copy assignment and move assignment operators, all entirely automatically.


问:
how the empty string ("") store in memory in Java?
How the empty string ("") store in memory in Java?

The empty string "" is 0 length, then how to store it in memory?

答:
Borrowed from this answer. The program prints 32 bytes for the empty string (and 0 for "" which is in the string pool).

```<code>public static void main(String... args) {
    long free1 = free();
    String s = "";
    long free2 = free();
    String s2 = new String("");
    long free3 = free();
    if (free3 == free1) System.err.println("You need to use -XX:-UseTLAB");
    System.out.println("\"\" took " + (free1 - free2) + " bytes and new String(\"\") took " + (free2
            - free3) + " bytes.");
}

private static long free() {
    return Runtime.getRuntime().freeMemory();
}
</code>```

Also, check this answer.

Body:
Borrowed from this answer. The program prints 32 bytes for the empty string (and 0 for "" which is in the string pool).

public static void main(String... args) {
    long free1 = free();
    String s = "";
    long free2 = free();
    String s2 = new String("");
    long free3 = free();
    if (free3 == free1) System.err.println("You need to use -XX:-UseTLAB");
    System.out.println("\"\" took " + (free1 - free2) + " bytes and new String(\"\") took " + (free2
            - free3) + " bytes.");
}

private static long free() {
    return Runtime.getRuntime().freeMemory();
}

Also, check this answer.


问:
How to create JSON from strings without creating a custom class using JSON.Net library
I have this method in which I'm trying to create JSON string:

```<code>//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1,  string val2, string val3,string val4,  string val5, string val6)
{
    //process the six arguments and three key-related member variables to create a JSON array
    //don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class

    var configs = new List<CustomClass>
                         { new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
                            , new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
                        };
    var jsonData = JsonConvert.SerializeObject(configs);
   return jsonData;
}

//A class in another file
public class CustomClass
{
    public string FirstKey { get; set; }
    public string SecondKey{ get; set; }
    public string ThirdKey{ get; set; }

}
</code>```

I'm trying to create the JSON array using JSON.Net. The expected output is as below:

```<code>[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]
</code>```

Here val1 to val6 values should get replaced by the argument values at run-time.

Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format. But soon I stumbled upon the world of escape characters which can deform a JSON string e.g. \r.

I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.

Anyways, coming back to my problem. I was able to solve my problem by creating a custom class having three properties FirstKey, SecondKey, and ThirdKey. Then, create an object of the class, then assign the values in arguments val1 and val2 to then and then use JsonConvert.SerializeObject API.

I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes. Creating a class CustomClass altogether feels like an overhead here. I'm looking for something of sort of like StringBuilder.Append API if it is available in the JSON library I'm using. I'm not sure if I'm missing any of the APIs in JSON.Net.

答:
As mentioned in the comments, you could just as easily have created it using anonymous objects.</p>

```<code>private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6) {

    var configs = new[]
    {
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3},
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    var jsonData = JsonConvert.SerializeObject(configs);

    return jsonData;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this method in which I'm trying to create JSON string:

//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1,  string val2, string val3,string val4,  string val5, string val6)
{
    //process the six arguments and three key-related member variables to create a JSON array
    //don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class

    var configs = new List<CustomClass>
                         { new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
                            , new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
                        };
    var jsonData = JsonConvert.SerializeObject(configs);
   return jsonData;
}

//A class in another file
public class CustomClass
{
    public string FirstKey { get; set; }
    public string SecondKey{ get; set; }
    public string ThirdKey{ get; set; }

}

I'm trying to create the JSON array using JSON.Net. The expected output is as below:

[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]

Here val1 to val6 values should get replaced by the argument values at run-time.

Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format. But soon I stumbled upon the world of escape characters which can deform a JSON string e.g. \r.

I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.

Anyways, coming back to my problem. I was able to solve my problem by creating a custom class having three properties FirstKey, SecondKey, and ThirdKey. Then, create an object of the class, then assign the values in arguments val1 and val2 to then and then use JsonConvert.SerializeObject API.

I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes. Creating a class CustomClass altogether feels like an overhead here. I'm looking for something of sort of like StringBuilder.Append API if it is available in the JSON library I'm using. I'm not sure if I'm missing any of the APIs in JSON.Net.

Body:
As mentioned in the comments, you could just as easily have created it using anonymous objects.

private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6) {

    var configs = new[]
    {
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3},
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    var jsonData = JsonConvert.SerializeObject(configs);

    return jsonData;
}


问:
C non-blocking keyboard input
I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.

Is there a simple way to do this? I figure I could possibly do it with select() but that seems like a lot of work.

Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?

答: On UNIX systems, you can use sigaction call to register a signal handler for SIGINT signal which represents the Control+C key sequence. The signal handler can set a flag which will be checked in the loop making it to break appropriately.

OwnerDisplayName: Zxaos

Title: C non-blocking keyboard input

LastEditorDisplayName: Zxaos

OwnerDisplayName: Mehrdad Afshari


问:
Caused by: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling:
I am trying to create table using anko library in kotlin like below

```<code>override fun onCreate(db: SQLiteDatabase?) {
    db!!.createTable(PersonTable.Name, true,
            Pair(PersonTable.ID, INTEGER + PRIMARY_KEY + AUTOINCREMENT),
            Pair(PersonTable.PersonName, TEXT),
            Pair(PersonTable.Domain, TEXT),
            Pair(PersonTable.MobileNumber, REAL))
}
</code>```

I am getting below error when I am adding AUTOINCREMENT to ID. It works without AUTOINCREMENT. What is the way to make any attribute as AUTOINCREMENT using anko library.

```<code>  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.williamsro.fourthdemo, PID: 4799
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.williamsro.fourthdemo/com.williamsro.fourthdemo.MainActivity}: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS `Person`(id INTEGER PRIMARY KEY org.jetbrains.anko.db.SqlTypeModifierImpl@7d0b905, person_name TEXT, domain TEXT, mobile_number REAL);
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
      at android.app.ActivityThread.-wrap12(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6077)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
   Caused by: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS `Person`(id INTEGER PRIMARY KEY org.jetbrains.anko.db.SqlTypeModifierImpl@7d0b905, person_name TEXT, domain TEXT, mobile_number REAL);
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1675)
      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1606)
      at org.jetbrains.anko.db.DatabaseKt.createTable(Database.kt:80)
      at com.williamsro.fourthdemo.AppDbHelpler.onCreate(AppDbHelpler.kt:17)
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
      at org.jetbrains.anko.db.ManagedSQLiteOpenHelper.openDatabase(Database.kt:166)
      at org.jetbrains.anko.db.ManagedSQLiteOpenHelper.use(Database.kt:157)
      at com.williamsro.fourthdemo.MainActivity.insertPerson(MainActivity.kt:44)
      at com.williamsro.fourthdemo.MainActivity.onCreate(MainActivity.kt:72)
      at android.app.Activity.performCreate(Activity.java:6664)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
      at android.app.ActivityThread.-wrap12(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6077)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
I got the same problem and found a workaround. I was able to hardcode that part of SQL statement, using SqlType.create function.

```<code>override fun onCreate(db: SQLiteDatabase) {
    db.createTable(CrimeTable.TABLE_NAME, true,
            CrimeTable.ID to SqlType.create("INTEGER PRIMARY KEY AUTOINCREMENT"),
            CrimeTable.UUID to TEXT,
            CrimeTable.TITLE to TEXT,
            CrimeTable.DATE to INTEGER,
            CrimeTable.IS_SOLVED to TEXT
    )
}
</code>```

I checked the generated SQL in the DB Browser and it was working perfectly. I never got that error again ever since.

```<code>CREATE TABLE `crimes`(_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid TEXT, title TEXT, date INTEGER, isSolved TEXT)
</code>```

Body:
I am trying to create table using anko library in kotlin like below

override fun onCreate(db: SQLiteDatabase?) {
    db!!.createTable(PersonTable.Name, true,
            Pair(PersonTable.ID, INTEGER + PRIMARY_KEY + AUTOINCREMENT),
            Pair(PersonTable.PersonName, TEXT),
            Pair(PersonTable.Domain, TEXT),
            Pair(PersonTable.MobileNumber, REAL))
}

I am getting below error when I am adding AUTOINCREMENT to ID. It works without AUTOINCREMENT. What is the way to make any attribute as AUTOINCREMENT using anko library.

  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.williamsro.fourthdemo, PID: 4799
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.williamsro.fourthdemo/com.williamsro.fourthdemo.MainActivity}: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS `Person`(id INTEGER PRIMARY KEY org.jetbrains.anko.db.SqlTypeModifierImpl@7d0b905, person_name TEXT, domain TEXT, mobile_number REAL);
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
      at android.app.ActivityThread.-wrap12(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6077)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
   Caused by: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS `Person`(id INTEGER PRIMARY KEY org.jetbrains.anko.db.SqlTypeModifierImpl@7d0b905, person_name TEXT, domain TEXT, mobile_number REAL);
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1675)
      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1606)
      at org.jetbrains.anko.db.DatabaseKt.createTable(Database.kt:80)
      at com.williamsro.fourthdemo.AppDbHelpler.onCreate(AppDbHelpler.kt:17)
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
      at org.jetbrains.anko.db.ManagedSQLiteOpenHelper.openDatabase(Database.kt:166)
      at org.jetbrains.anko.db.ManagedSQLiteOpenHelper.use(Database.kt:157)
      at com.williamsro.fourthdemo.MainActivity.insertPerson(MainActivity.kt:44)
      at com.williamsro.fourthdemo.MainActivity.onCreate(MainActivity.kt:72)
      at android.app.Activity.performCreate(Activity.java:6664)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
      at android.app.ActivityThread.-wrap12(ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6077)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
I got the same problem and found a workaround. I was able to hardcode that part of SQL statement, using SqlType.create function.

override fun onCreate(db: SQLiteDatabase) {
    db.createTable(CrimeTable.TABLE_NAME, true,
            CrimeTable.ID to SqlType.create("INTEGER PRIMARY KEY AUTOINCREMENT"),
            CrimeTable.UUID to TEXT,
            CrimeTable.TITLE to TEXT,
            CrimeTable.DATE to INTEGER,
            CrimeTable.IS_SOLVED to TEXT
    )
}

I checked the generated SQL in the DB Browser and it was working perfectly. I never got that error again ever since.

CREATE TABLE `crimes`(_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid TEXT, title TEXT, date INTEGER, isSolved TEXT)


问:
How to display XML RSS feed by PHP
I have an assignment to display my XML RSS via PHP on a website, so far I have tried multiple things and all have failed. And I was unable to find the answer since most people do RSS feed by PHP from MySQL database to get a live feed of posts.

XML RSS

```<code><?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>Treehouse front page</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  <item>
    <title>Code Academy</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  </item>
</channel>

</rss>
</code>```

How can I display this file via PHP?

答:
Try to use the DOMDocument() class, for example:

```<code>$rss = new DOMDocument();
$rss->load("http://yoursite.com/rss/");

$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array (
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
        );
    array_push($feed, $item);
}
</code>```

This is a tip. I hope I have helped you.

Title: How to display XML RSS feed by PHP

Body:
I have an assignment to display my XML RSS via PHP on a website, so far I have tried multiple things and all have failed. And I was unable to find the answer since most people do RSS feed by PHP from MySQL database to get a live feed of posts.

XML RSS

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>Treehouse front page</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  <item>
    <title>Code Academy</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  </item>
</channel>

</rss>

How can I display this file via PHP?

Body:
Try to use the DOMDocument() class, for example:

$rss = new DOMDocument();
$rss->load("http://yoursite.com/rss/");

$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array (
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
        );
    array_push($feed, $item);
}

This is a tip. I hope I have helped you.


答:
As there is && in the if statement. it does not go in the if statement. Just try this for clarification- just make an if statement

String s= "";

IF(s == null)
print "it is null";

else
print "it is not null";

See yourself whether String s can be empty and null at the same time.

Body:
As you can see in the picture the value of the r.SalaryGrade is null. Why it skip my IF condition and goes to Else?. I make sure that if is an empty string and null it will add a class to a textbox. Did I do something wrong?.

 if (r.SalaryGrade == "" && r.SalaryGrade == null) { $("#JobGradeId").addClass('validation'); }
 else { $("#JobGradeId").removeClass('validation'); }


问:
Wordpress add_rewrite_rule not working
This may seem like a duplicate question, but I've read through as many SO posts with similar titles, and every one of them got much farther than I've been able to, so it seems that I must be doing something basic wrong, but I have no idea what it is.  That said, here's my issue:

I'm following the steps in the 'Basic Usage' section of the add_rewrite_rule documentation page, making sure to flush and regenerate rewrite rules.

I've got a page with an id of 68, and I want to redirect this:

http://localhost.test.wordpress/leaf/68

to this:

http://localhost.test.wordpress/index.php?page_id=68

I have verified that the latter does exist, and that I can navigate to it directly.

So in my theme's functions.php file, I wrote the following:

function custom_rewrite_basic() {
    add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

And then I went to the Settings -> Permalinks section of my WP admin panel and hit 'Save Changes' with no changes, as the docs page directs me to do.

The problem I'm running into is that when I navigate to http://localhost.test.wordpress/leaf/68, I get a 404 error.  Clearly, the docs indicate that this should not be happening, and none of the other SO posts I've seen have had this problem (they get past this step and run into difficulty in some other aspect of the redirect).

The redirect code I put in functions.php is an exact copy/paste from the docs page, and yet because of the 404, I'm led to believe that no WP code is being run at all.  Can you let me know what I'm doing wrong?  I'm completely new to WP.

答:
If the site doesn't seem to be respecting changes you make to the .htaccess file, you should make sure that the <VirtualHost> configuration explicitly gives the .htaccess files permission to override certain configurations.

In your <VirtualHost> entry there should be a <Directory> entry as well. You'll need to add the AllowOverride All command to it, like this:

```<code><Directory /path/to/your/web/document/root>
        AllowOverride All
        Require all granted
</Directory>
</code>```

Also, if the site isn't respecting your Rewrite commands, you should make sure to check your httpd.conf to see if the mod_rewrite module is loaded. Look for a line similar to this:

```<code>LoadModule rewrite_module libexec/apache2/mod_rewrite.so
</code>```

If it is commented out with a #, uncomment that line (remove the #) and then restart your apache.

Title: Wordpress add_rewrite_rule not working

Body:
If the site doesn't seem to be respecting changes you make to the .htaccess file, you should make sure that the <VirtualHost> configuration explicitly gives the .htaccess files permission to override certain configurations.

In your <VirtualHost> entry there should be a <Directory> entry as well. You'll need to add the AllowOverride All command to it, like this:

<Directory /path/to/your/web/document/root>
        AllowOverride All
        Require all granted
</Directory>

Also, if the site isn't respecting your Rewrite commands, you should make sure to check your httpd.conf to see if the mod_rewrite module is loaded. Look for a line similar to this:

LoadModule rewrite_module libexec/apache2/mod_rewrite.so

If it is commented out with a #, uncomment that line (remove the #) and then restart your apache.