问:
Batch file to rename files to specific names
So a quick explanation. We have hundreds of projects and in each of them and in every new project we have a program where we fill in a ton of information. From that we get 20 pdf files that are called File_1, File_2 etc.

What I'd like to do is to rename the files as the example below with a bat file.

```<code>File_1 = abc.pdf

File_2 = xyz.pdf

File_3 = qwe.pdf
</code>```

I want to specific in the bat file what I want file_1 should be called and file_2 etc. The files I get will always be called File_1, File_2 etc and I always want them to be renamed the same. So each time I get those files I just run the bat file. Is there a way to do this? Or is there a better way to do this?

Thanks!

答:
I'm assuming your files will always be called "file_1", "file_2" etc.??
If they are, then you can just write a file with a line for each file. For example

```<code>ren file_1 foo.pdf
ren file_2 bar.pdf
ren file_3 foobar.pdf
</code>```

Note that as you didn't specify extensions for the original filenames, I haven't either.  You would want to put the full file name with extension, or use wildcards if appropriate, e.g. ren file_1.*.  (Be very careful with wildcards though, or you may end up trying to rename multiple files with the same name!)

You could check if the file exists first, and only run the ren on files that are there, or you could run it and let it error for missing files (though I'm sure other people will have reasons why you shouldn't).

You should also consider whether or not there will already be a file with the name you are trying to rename to, because if there the is then the rename will error and fail.

If your files will be different names daily, you will need to give more information as to what you have and what you need.

EDIT - Response to comment below

Copy (and complete) this code, and save it as 'rename.bat' or whatever you need.

```<code>@echo off
ren file_1 abc.pdf
ren file_2 xyz.pdf
ren file_3 qwe.pdf
<<repeat as necessary>>
</code>```

The @echo off just stops the batch file from displayed the commands.  It will still display errors (if the file doesn't exist or if you try to rename a file to an existing filename).  You really should be looking at catching the errors and doing something with it, but if you can be 100% certain that the new filenames don't exist it will work.

Also worth pointing out that as I haven't used full file names, the batch file would need to be in the same folder as your file_1, file_2 etc.

You could use move to specify the full path of the original file, and a new path (it will move and rename the files), but you still have potentially the same problems with duplicate filenames etc.

I'm assuming you will end up with a folder containing file_1, file_2 etc. so you can just copy your batch file into the folder, run it, then move all your renamed files to where they need to go.  Then next time you need to run the file, your folder would only have in it the new set of file_1, file_2 etc. so you could copy in the batch file again, run it... and so on.

EDIT2 - After thought for filenames including spaces

It just occurred to me that your existing files (file_1, file_2 etc.) don't appear to have any spaces in the name, but your new filenames might (you didn't specify the names exactly).  If you have spaces if filenames, make sure to add quotes to the command e.g.

```<code>ren file_1 "my new file.pdf"
</code>```

You can also quote your original filenames too (quoting both wouldn't hurt even if there are no spaces) so you could try

```<code>ren "file_1" "abc.pdf"
ren "file_2" "x y z.pdf"
ren "file_3" "qw   e.pdf"
etc.
</code>```

Body:
So a quick explanation. We have hundreds of projects and in each of them and in every new project we have a program where we fill in a ton of information. From that we get 20 pdf files that are called File_1, File_2 etc.

What I'd like to do is to rename the files as the example below with a bat file.

File_1 = abc.pdf

File_2 = xyz.pdf

File_3 = qwe.pdf

I want to specific in the bat file what I want file_1 should be called and file_2 etc. The files I get will always be called File_1, File_2 etc and I always want them to be renamed the same. So each time I get those files I just run the bat file. Is there a way to do this? Or is there a better way to do this?

Thanks!

Body:
I'm assuming your files will always be called "file_1", "file_2" etc.??
If they are, then you can just write a file with a line for each file. For example

ren file_1 foo.pdf
ren file_2 bar.pdf
ren file_3 foobar.pdf

Note that as you didn't specify extensions for the original filenames, I haven't either.  You would want to put the full file name with extension, or use wildcards if appropriate, e.g. ren file_1.*.  (Be very careful with wildcards though, or you may end up trying to rename multiple files with the same name!)

You could check if the file exists first, and only run the ren on files that are there, or you could run it and let it error for missing files (though I'm sure other people will have reasons why you shouldn't).

You should also consider whether or not there will already be a file with the name you are trying to rename to, because if there the is then the rename will error and fail.

If your files will be different names daily, you will need to give more information as to what you have and what you need.

EDIT - Response to comment below

Copy (and complete) this code, and save it as 'rename.bat' or whatever you need.

@echo off
ren file_1 abc.pdf
ren file_2 xyz.pdf
ren file_3 qwe.pdf
<<repeat as necessary>>

The @echo off just stops the batch file from displayed the commands.  It will still display errors (if the file doesn't exist or if you try to rename a file to an existing filename).  You really should be looking at catching the errors and doing something with it, but if you can be 100% certain that the new filenames don't exist it will work.

Also worth pointing out that as I haven't used full file names, the batch file would need to be in the same folder as your file_1, file_2 etc.

You could use move to specify the full path of the original file, and a new path (it will move and rename the files), but you still have potentially the same problems with duplicate filenames etc.

I'm assuming you will end up with a folder containing file_1, file_2 etc. so you can just copy your batch file into the folder, run it, then move all your renamed files to where they need to go.  Then next time you need to run the file, your folder would only have in it the new set of file_1, file_2 etc. so you could copy in the batch file again, run it... and so on.

EDIT2 - After thought for filenames including spaces

It just occurred to me that your existing files (file_1, file_2 etc.) don't appear to have any spaces in the name, but your new filenames might (you didn't specify the names exactly).  If you have spaces if filenames, make sure to add quotes to the command e.g.

ren file_1 "my new file.pdf"

You can also quote your original filenames too (quoting both wouldn't hurt even if there are no spaces) so you could try

ren "file_1" "abc.pdf"
ren "file_2" "x y z.pdf"
ren "file_3" "qw   e.pdf"
etc.


来源: stackexchange

问:
Is it possible to predict a stack overflow in C on Linux?
There are certain conditions that can cause stack overflows on an x86 Linux system:

struct my_big_object[HUGE_NUMBER] on the stack.  Walking through it eventually causes SIGSEGV.

The alloca() routine (like malloc(), but uses the stack, automatically frees itself, and also blows up with SIGSEGV if it's too big). Update: alloca() isn't formally deprecated as I originally stated; it is merely discouraged.

Is there a way to programmatically detect if the local stack is big enough for a given object?  I know the stack size is adjustable via ulimit, so I have hope there is a way (however non-portable it may be).  Ideally, I would like to be able to do something like this:

```<code>int min_stack_space_available = /* ??? */;
if (object_size < min_stack_space_available)
{
    char *foo = alloca(object_size);
    do_stuff(foo);
}
else
{
    char *foo = malloc(object_size);
    do_stuff(foo);
    free(foo);
}
</code>```

答:
You can use GNU libsigsegv to handle a page fault, including cases where a stack overflow occurs (from its website):

In some applications, the stack overflow handler performs some cleanup or notifies the user and then immediately terminates the application. In other applications, the stack overflow handler longjmps back to a central point in the application. This library supports both uses. In the second case, the handler must ensure to restore the normal signal mask (because many signals are blocked while the handler is executed), and must also call sigsegv_leave_handler() to transfer control; then only it can longjmp away.

OwnerDisplayName: Tom

ContentLicense: CC BY-SA 2.5

Body:
There are certain conditions that can cause stack overflows on an x86 Linux system:

struct my_big_object[HUGE_NUMBER] on the stack.  Walking through it eventually causes SIGSEGV.

The alloca() routine (like malloc(), but uses the stack, automatically frees itself, and also blows up with SIGSEGV if it's too big). Update: alloca() isn't formally deprecated as I originally stated; it is merely discouraged.

Is there a way to programmatically detect if the local stack is big enough for a given object?  I know the stack size is adjustable via ulimit, so I have hope there is a way (however non-portable it may be).  Ideally, I would like to be able to do something like this:

int min_stack_space_available = /* ??? */;
if (object_size < min_stack_space_available)
{
    char *foo = alloca(object_size);
    do_stuff(foo);
}
else
{
    char *foo = malloc(object_size);
    do_stuff(foo);
    free(foo);
}

LastEditorDisplayName: Tom

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Why is this HTTP stream causing my app to get rejected?
I have an app that uses NASA live TV stream for the iphone/ipad which they use in their own app, but my app got rejected because:

2.2     Apps that exhibit bugs will be rejected

Referring to the stream: http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8

```<code>EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=298577
http://liveips.nasa.gov.edgesuite.net/ksc/Edge.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=298577
http://liveips.nasa.gov.edgesuite.net/msfc/Edge.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=532383
http://liveips.nasa.gov.edgesuite.net/ksc/3G.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=532383
http://liveips.nasa.gov.edgesuite.net/msfc/3G.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=838577
http://liveips.nasa.gov.edgesuite.net/ksc/Wifi.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=838577
http://liveips.nasa.gov.edgesuite.net/msfc/Wifi.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=32000
http://liveips.nasa.gov.edgesuite.net/ksc/Edgeaudio.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=32000
http://liveips.nasa.gov.edgesuite.net/msfc/Edgeaudio.m3u8
</code>```

When we accessed
  "http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8",
  we did not find a 64kbps stream...
  verify that the stream advertises and
  measures 64kbps or less

Anyone got an idea?

答:
You will need 64kbps stream if you are going to allow user to watch live streaming on a cellular network, you can use Reachability demo to determine current network status (cellular or wifi) and block user from watching live stream on a cellular network.

See technical note here (TN2224) for more information about HTTP Live Streaming requirements. And you may need to try HTTP Live Streaming Tools on your stream to see what is wrong.

I get a lot of errors from the following command.

```<code>$mediastreamvalidator validate http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8
</code>```

Body:
I have an app that uses NASA live TV stream for the iphone/ipad which they use in their own app, but my app got rejected because:

2.2     Apps that exhibit bugs will be rejected

Referring to the stream: http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8

EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=298577
http://liveips.nasa.gov.edgesuite.net/ksc/Edge.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=298577
http://liveips.nasa.gov.edgesuite.net/msfc/Edge.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=532383
http://liveips.nasa.gov.edgesuite.net/ksc/3G.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=532383
http://liveips.nasa.gov.edgesuite.net/msfc/3G.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=838577
http://liveips.nasa.gov.edgesuite.net/ksc/Wifi.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=838577
http://liveips.nasa.gov.edgesuite.net/msfc/Wifi.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=32000
http://liveips.nasa.gov.edgesuite.net/ksc/Edgeaudio.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1, BANDWIDTH=32000
http://liveips.nasa.gov.edgesuite.net/msfc/Edgeaudio.m3u8

When we accessed
  "http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8",
  we did not find a 64kbps stream...
  verify that the stream advertises and
  measures 64kbps or less

Anyone got an idea?

Body:
You will need 64kbps stream if you are going to allow user to watch live streaming on a cellular network, you can use Reachability demo to determine current network status (cellular or wifi) and block user from watching live stream on a cellular network.

See technical note here (TN2224) for more information about HTTP Live Streaming requirements. And you may need to try HTTP Live Streaming Tools on your stream to see what is wrong.

I get a lot of errors from the following command.

$mediastreamvalidator validate http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8

ContentLicense: CC BY-SA 3.0


问:
Spring requests preprocessing per session
I'd like create Spring request Interceptor which will be able to get some data from session and change some @Autowired components before request.

I can create Interceptor and register it, but it can't get access to session beans:

```<code>@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private MyServicePerSession myServicePerSession;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(myServicePerSession.getName()); // NullPointerException!!!

        return true;
    }
}
</code>```

Above in the method preHandle(...) per each request I get NullPointerException.

Here is my config:

```<code>@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    //...

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor());
    }
}
</code>```

How I said everything work fine except injecting MyServicePerSession.

I will really appreciate if you can give me advice about it, or some other ways to solve that problem.

答:
You are trying to set a new object but you have to set a spring bean.

```<code> new TokenInterceptor() // is not spring bean

@Autowired private TokenInterceptor tokenInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(tokenInterceptor);
    // You have to set bean here
}
</code>```

If this doesn't work, you can check this http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s02.html

Body:
I'd like create Spring request Interceptor which will be able to get some data from session and change some @Autowired components before request.

I can create Interceptor and register it, but it can't get access to session beans:

@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private MyServicePerSession myServicePerSession;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(myServicePerSession.getName()); // NullPointerException!!!

        return true;
    }
}

Above in the method preHandle(...) per each request I get NullPointerException.

Here is my config:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    //...

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor());
    }
}

How I said everything work fine except injecting MyServicePerSession.

I will really appreciate if you can give me advice about it, or some other ways to solve that problem.

Body:
You are trying to set a new object but you have to set a spring bean.

 new TokenInterceptor() // is not spring bean

@Autowired private TokenInterceptor tokenInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(tokenInterceptor);
    // You have to set bean here
}

If this doesn't work, you can check this http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s02.html


问:
AX QueryService 2012 "OR" query - how to?
can anyone give me a nudge in the right direction as to how to do an "OR" query via the Query Service?

In order to do an "AND" query I can simply add two (or more) "Ranges" - this sort of jazz:

```<code>        // build and add our new filter
        QueryDataRangeMetadata range = new QueryDataRangeMetadata
        {
            TableName = dataSource.Table,
            FieldName = fieldName,
            Value = fieldValue,
            Enabled = true
        };

        dataSource.Ranges[ranges.Length - 1] = range;
</code>```

..but how does one do an "OR" ??

答:
I have used this in the past:

```<code>queryBuildRange.value(strFmt('((%1 == %2) || ((%1 == %3) && (%4 == "%5")))',
    fieldStr(InventTable, ItemType),
    any2int(ItemType::Service),
    any2int(ItemType::Item),
    fieldStr(InventTable, ProjCategoryId),
    queryValue("Spares")));
</code>```

Probably is not the cleanest way to do it but will do the job.

Body:
can anyone give me a nudge in the right direction as to how to do an "OR" query via the Query Service?

In order to do an "AND" query I can simply add two (or more) "Ranges" - this sort of jazz:

        // build and add our new filter
        QueryDataRangeMetadata range = new QueryDataRangeMetadata
        {
            TableName = dataSource.Table,
            FieldName = fieldName,
            Value = fieldValue,
            Enabled = true
        };

        dataSource.Ranges[ranges.Length - 1] = range;

..but how does one do an "OR" ??

Body:
I have used this in the past:

queryBuildRange.value(strFmt('((%1 == %2) || ((%1 == %3) && (%4 == "%5")))',
    fieldStr(InventTable, ItemType),
    any2int(ItemType::Service),
    any2int(ItemType::Item),
    fieldStr(InventTable, ProjCategoryId),
    queryValue("Spares")));

Probably is not the cleanest way to do it but will do the job.


问:
How to access a shared folder using python imaplib?
How do you access a shared folder ? This is a shared folder which is visible to other users too. I am currently using outlook where the shared folder is visible along with my personal emails</p>

答:
Following back on my question. After reading enough this seems to work.

While using imaplib and connecting to exchange in python 3

use this,

```<code>result, data=mail.login('personal@domain.com\shared@domain.com','personalPassword')
</code>```

If you have access to this shared mailbox in outlook then you will be able to connect using this. Print the result if it says 'OK' then the code did work.

Body:
Following back on my question. After reading enough this seems to work.

While using imaplib and connecting to exchange in python 3

use this,

result, data=mail.login('personal@domain.com\shared@domain.com','personalPassword')

If you have access to this shared mailbox in outlook then you will be able to connect using this. Print the result if it says 'OK' then the code did work.


问:
Ionic 2 loadingController cssClass not working
I want my loadingController wrapper to be shown with a customized css style but the css's rules doesn't apply to the element (the loadingController wrapper).

I have this in my component:

```<code>ionViewDidLoad() {
    let loader = this.loadingController.create({
        spinner: 'bubbles',
        content: 'getting data...',
        cssClass: 'loadingwrapper'
    });
    loader.present().then(() => {
        //some stuff
        ...
        loader.dismiss();
    });
}
</code>```

and this in my css file:

```<code>.loadingwrapper{
    width: 77% !important;
    height: 15% !important;
    color: black !important;
    font-size: 1.25em !important;
    background-color: aliceblue !important;
    border-radius: 10px !important;
}
</code>```

In spite of doing this (I've even tried whithout "!important"), the changes (none of them) doesn't apply to the loading wrapper and it shows a bit awful.

答:
You have to do it globally inside the variables.scss file.

Android

```<code>$loading-md-border-radius:10px;
</code>```

ios

```<code>$loading-ios-border-radius: 10px
</code>```

Windows

```<code>$loading-wp-border-radius:  10px
</code>```

You can see global variable list here.

Body:
I want my loadingController wrapper to be shown with a customized css style but the css's rules doesn't apply to the element (the loadingController wrapper).

I have this in my component:

ionViewDidLoad() {
    let loader = this.loadingController.create({
        spinner: 'bubbles',
        content: 'getting data...',
        cssClass: 'loadingwrapper'
    });
    loader.present().then(() => {
        //some stuff
        ...
        loader.dismiss();
    });
}

and this in my css file:

.loadingwrapper{
    width: 77% !important;
    height: 15% !important;
    color: black !important;
    font-size: 1.25em !important;
    background-color: aliceblue !important;
    border-radius: 10px !important;
}

In spite of doing this (I've even tried whithout "!important"), the changes (none of them) doesn't apply to the loading wrapper and it shows a bit awful.

Body:
You have to do it globally inside the variables.scss file.

Android

$loading-md-border-radius:10px;

ios

$loading-ios-border-radius: 10px

Windows

$loading-wp-border-radius:  10px

You can see global variable list here.


问:
Finding the depth of a given node in a k-ary tree
I have a k-ary tree, and I need to be able to calculate the depths of the nodes once the tree has been built.

Here's the tree class

```<code>public class DirectoryTree implements Serializable {

    private TreeNode Root;
    private int numNodes;
    private TreeNode Focus;
    private LocalDateTime date;
    private long totalSizeOnDisk;
</code>```

Heres the TreeNode class:

```<code>public class TreeNode implements Serializable{

    private FileSystemEntry data;
    private boolean directory;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private int numChildren;
    private int nodeKey;
    private int depth;
</code>```

My original idea was to queue up all the nodes of the tree in breadth first order, and using the numNodes variable, pop off a given nodes children and set their depth to be whatever the counter variable is, but that doesnt work since then I cant read the popped nodes in order to find the depth of their children. So it seems I need a recursive algorithm or something like that. Maybe a modified breadth first?:

```<code>public void BFTree() {

    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(this.Root);
    TreeNode current;
    while ((current = queue.poll()) != null) {
        BFTree(current, queue);
    }
}

private void BFTree(TreeNode n, Queue<TreeNode> queue) {

    System.out.println(n.getData().getName());
    if (n.isDirectory()) {
        for (int i = 0; i < n.getChildren().size(); i++) {
            queue.add(n.getChildren().get(i));
        }
    }
}
</code>```

答:
In case anyone else stumbles on this

I just modified my breadth first traversal with this:

```<code>if(!n.equals(this.Root)){
        n.setDepth(n.getParent().getDepth() + 1);
}
</code>```

Obviously a given node's depth is just its parent's depth + 1. Root doesn't have a parent, so I just defined it as 0 in the access/base case function

Body:
I have a k-ary tree, and I need to be able to calculate the depths of the nodes once the tree has been built.

Here's the tree class

public class DirectoryTree implements Serializable {

    private TreeNode Root;
    private int numNodes;
    private TreeNode Focus;
    private LocalDateTime date;
    private long totalSizeOnDisk;

Heres the TreeNode class:

public class TreeNode implements Serializable{

    private FileSystemEntry data;
    private boolean directory;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private int numChildren;
    private int nodeKey;
    private int depth;

My original idea was to queue up all the nodes of the tree in breadth first order, and using the numNodes variable, pop off a given nodes children and set their depth to be whatever the counter variable is, but that doesnt work since then I cant read the popped nodes in order to find the depth of their children. So it seems I need a recursive algorithm or something like that. Maybe a modified breadth first?:

public void BFTree() {

    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(this.Root);
    TreeNode current;
    while ((current = queue.poll()) != null) {
        BFTree(current, queue);
    }
}

private void BFTree(TreeNode n, Queue<TreeNode> queue) {

    System.out.println(n.getData().getName());
    if (n.isDirectory()) {
        for (int i = 0; i < n.getChildren().size(); i++) {
            queue.add(n.getChildren().get(i));
        }
    }
}

Body:
In case anyone else stumbles on this

I just modified my breadth first traversal with this:

if(!n.equals(this.Root)){
        n.setDepth(n.getParent().getDepth() + 1);
}

Obviously a given node's depth is just its parent's depth + 1. Root doesn't have a parent, so I just defined it as 0 in the access/base case function


问:
Creating a standalone package in java and take some settings from the configuration file
Anyone plz let us know what to do when we have some configuration file which is basically xml.I want to for example give the path to save the image(for my java program) in a folder from some config file (xml in my case).In that case where should the config file be kept.Rt now every thing is converted to jar file when i create a java standalone package.But i want to give some setting from xml file.What to do in that case.How is it possible.This article only provides to create a single jar file for java project but talks nothing about the configuration settings that u can provide from some external source.

Regards
Sagar

答:
Sagar,

The fact your java program is a standalone package (.jar file) has no bearing on where your configuration file is stored. Your java package is a program and that program can read any file from the file system that it so desires; it does not have to be part of the code inside the IDE i.e. you don't have to write it when you write the program. What you do need is some way, when you start the program, to find and read said configuration file.

Depending on how you expect the program to be configured, you might put that file in a number of locations. For example, /etc/yourimageprogram/config.xml or c:\program files\yourimageprogram\config.xml or perhaps c:\users\Sagar\Application Settings\yourimageprogram\config.xml. Which you choose of those options really depends on what the use case is and that I can't help with.

However, there are some main points to reading any file:

Does it exist?

Are we allowed to open it for reading?

Are we allowed to open it for writing? Might want to know if we want to update the config?

In Java, typically, you would test this with:

```<code>File configfile = new File("C:\test.xml");
if ( configfile.exists() && configfile.canRead() )
{
    // read the file
}
else
{
    // decide what to do if no config exists.
    // might be first run of app.
}
</code>```

The next stage is to parse the file. There are a number of parsers available for XML including sax and org.w3c.dom. What you need to do is to use these to extract the information you require and store that in a class. Probably a singleton class as you're unlikely to have multiple configuration instances per instance of the program.

I suggest you read about XML Parsers and File Handling under Java. Also look at the File object. See all your options for file io in java. These should give you some indication of how to proceed.

Body:
Sagar,

The fact your java program is a standalone package (.jar file) has no bearing on where your configuration file is stored. Your java package is a program and that program can read any file from the file system that it so desires; it does not have to be part of the code inside the IDE i.e. you don't have to write it when you write the program. What you do need is some way, when you start the program, to find and read said configuration file.

Depending on how you expect the program to be configured, you might put that file in a number of locations. For example, /etc/yourimageprogram/config.xml or c:\program files\yourimageprogram\config.xml or perhaps c:\users\Sagar\Application Settings\yourimageprogram\config.xml. Which you choose of those options really depends on what the use case is and that I can't help with.

However, there are some main points to reading any file:

Does it exist?

Are we allowed to open it for reading?

Are we allowed to open it for writing? Might want to know if we want to update the config?

In Java, typically, you would test this with:

File configfile = new File("C:\test.xml");
if ( configfile.exists() && configfile.canRead() )
{
    // read the file
}
else
{
    // decide what to do if no config exists.
    // might be first run of app.
}

The next stage is to parse the file. There are a number of parsers available for XML including sax and org.w3c.dom. What you need to do is to use these to extract the information you require and store that in a class. Probably a singleton class as you're unlikely to have multiple configuration instances per instance of the program.

I suggest you read about XML Parsers and File Handling under Java. Also look at the File object. See all your options for file io in java. These should give you some indication of how to proceed.


问:
Check if list view contain item
i have a listview with 3 columns (id , name, author), i use this method to add row:

```<code>     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }
</code>```

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

```<code>  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }
</code>```

Can you help me please? thank you

答:
I think you missed a "!" (not) in your code.

```<code>(!listView1.Items.ContainsKey(book.id))
     {
  listView1.Items.Add(lvi1);
     }
</code>```

Your code is saying that if your listview contains that key, you will add another entry that has that key. But it seems you want to do the opposite, right? If your listview does not contain an entry with that key, you want to add an entry that has that key.

Title: Check if list view contain item

Body:
i have a listview with 3 columns (id , name, author), i use this method to add row:

     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }

Can you help me please? thank you

Body:
I think you missed a "!" (not) in your code.

(!listView1.Items.ContainsKey(book.id))
     {
  listView1.Items.Add(lvi1);
     }

Your code is saying that if your listview contains that key, you will add another entry that has that key. But it seems you want to do the opposite, right? If your listview does not contain an entry with that key, you want to add an entry that has that key.


问:
iOS UIWebView or WKWebView URL redirect
I have an URL: http://listen.streamonomy.com/cooljazzflorida (for example). This is an URL I parse in a PLS file (provided by SHOUTcast radios) for streaming audio. When I open it from a browser (Safari or Google Chrome), this URL is redirected to http://streaming.shoutcast.com/cooljazzflorida?lang=fr-fr and I can play the stream.

However, in my iOS application, using UIWebView or WKWebView, the redirected URL is http://streaming.shoutcast.com/cooljazzflorida_64?lang=fr-fr (then with _64), not the same from the browser, and I have the error "The file you require cannot be found".

Any ideas please ? Thanks.

EDIT: A sample code to illustrate the problem:

https://github.com/iDevelopper/RedirectURLSample.git

```<code>#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    webView.delegate = self;
    [self.view addSubview:webView];

    NSString *urlString = @"http://listen.streamonomy.com/cooljazzflorida";
    /* If you enter this url using Safari browser, the redirected url is:
     http://streaming.shoutcast.com/cooljazzflorida?lang=fr-fr
     */
    NSURL *urlToPlay = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlToPlay];
    [webView loadRequest:request];
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSURL *url = [webView.request mainDocumentURL];
    NSLog(@"DID FINISH The Redirected URL is: %@", url);
    /*
     The redirected url is: (not the same returned by the browser and this url is not found)
     http://streaming.shoutcast.com/cooljazzflorida_64?lang=en-us
    */

    // Set AVPlayerItem with the redirected URL
    // ...
}

@end
</code>```

答:
The _64 address really does not exist and it's Streamonomy's fault to not noticing it yet and fixing their redirection logic. The different redirection target is based on User-Agent header in your request. I suspect that Streamonomy is trying to guess the requesting device and query different bitrates. I found you two examples:

Mozilla/5.0 (iPad; CPU OS 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML, like Gecko) Version/10.0 Mobile/14C89 Safari/602.1

redirects to existing URL

Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1

redirects to the nonexistent _64

Go figure what is the exact threshold :-) Also noticeably, setting a totally bogus UA like ignoremeidontneedyourhelp redirects to the "correct" (existing) URL. But it's not an useful strategy if you intend to use that UI/WKWebView for normal public web browsing. Websites could be strangely rendered or otherwise broken.

Title: iOS UIWebView or WKWebView URL redirect

Body:
I have an URL: http://listen.streamonomy.com/cooljazzflorida (for example). This is an URL I parse in a PLS file (provided by SHOUTcast radios) for streaming audio. When I open it from a browser (Safari or Google Chrome), this URL is redirected to http://streaming.shoutcast.com/cooljazzflorida?lang=fr-fr and I can play the stream.

However, in my iOS application, using UIWebView or WKWebView, the redirected URL is http://streaming.shoutcast.com/cooljazzflorida_64?lang=fr-fr (then with _64), not the same from the browser, and I have the error "The file you require cannot be found".

Any ideas please ? Thanks.

EDIT: A sample code to illustrate the problem:

https://github.com/iDevelopper/RedirectURLSample.git

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    webView.delegate = self;
    [self.view addSubview:webView];

    NSString *urlString = @"http://listen.streamonomy.com/cooljazzflorida";
    /* If you enter this url using Safari browser, the redirected url is:
     http://streaming.shoutcast.com/cooljazzflorida?lang=fr-fr
     */
    NSURL *urlToPlay = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlToPlay];
    [webView loadRequest:request];
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSURL *url = [webView.request mainDocumentURL];
    NSLog(@"DID FINISH The Redirected URL is: %@", url);
    /*
     The redirected url is: (not the same returned by the browser and this url is not found)
     http://streaming.shoutcast.com/cooljazzflorida_64?lang=en-us
    */

    // Set AVPlayerItem with the redirected URL
    // ...
}

@end


问:
Ocassional Error loading script
I have some sites that I've been creating and they work fine but sometimes the pages will load and look like this

It'll usually work fine again if I reload the page but the problem is annoying and occurs around 20% of the time.

答:
i went to that url and got it the first time, but then was not able to reproduce it.
do you have load sharing with multiple servers?
watch the network tab in the inspector for anything and post back what you see.</p>

Title: Ocassional Error loading script


问:
How to convert all nested list nodes into json?
The following works but it is leaving some
 out when converting, see the output on this jsFiddle and we will see that it is leaving some nodes out

HTML

```<code><div id="tree">
  <ul class="sortable">
     <li>Pallacanestro
         <ul class="sortable">
             <li>Dinamo
                 <ul class="sortable">
                     <li>Logan</li>
                 </ul>
             </li>
         </ul>
     </li>
    <li>Calcio
        <ul class="sortable">
            <li>Milan
                <ul class="sortable">
                    <li>Goal</li>
                </ul>
            </li>
        </ul>
    </li>
  </ul>
</div>
<div id="d" style="margin-top: 40px; padding-top: 20px;">Output:<br><br>``````</div><br>``````</div>
</code>```

JS

```<code>var out = [];
function processOneLi(node) {
    var aNode = node.contents().first();
    var retVal = {
        "name": aNode.text().trim(),
        "url": aNode.attr("href")
    };
    node.find("> .sortable > li").each(function() {
        if (!retVal.hasOwnProperty("children")) {
            retVal.children = [];
        }
        retVal.children.push(processOneLi($(this)));
    });
    return retVal;
}
$("#tree > ul > li").each(function() {
    out.push(processOneLi($(this)));
});

$('#d pre').text(JSON.stringify(out[0], null, 2));
</code>```

The output is missing a

```<code>{
  "name": "Pallacanestro",
  "children": [
    {
      "name": "Dinamo",
      "children": [
        {
          "name": "Logan"
        }
      ]
    }
  ]
}
</code>```

答:
If I'm understanding you correctly, you say you're missing Calcio in the output.

You need to change:

$('#d pre').text(JSON.stringify(out[0], null, 2));

to

$('#d pre').text(JSON.stringify(out, null, 2));

You were only asking it to output the first item in the array out.  You want to show the entire array.

Body:
The following works but it is leaving some
 out when converting, see the output on this jsFiddle and we will see that it is leaving some nodes out

HTML

Pallacanestro

Dinamo

Logan

Calcio

Milan

Goal

Output:

JS

var out = [];
function processOneLi(node) {
    var aNode = node.contents().first();
    var retVal = {
        "name": aNode.text().trim(),
        "url": aNode.attr("href")
    };
    node.find("> .sortable > li").each(function() {
        if (!retVal.hasOwnProperty("children")) {
            retVal.children = [];
        }
        retVal.children.push(processOneLi($(this)));
    });
    return retVal;
}
$("#tree > ul > li").each(function() {
    out.push(processOneLi($(this)));
});

$('#d pre').text(JSON.stringify(out[0], null, 2));

The output is missing a

{
  "name": "Pallacanestro",
  "children": [
    {
      "name": "Dinamo",
      "children": [
        {
          "name": "Logan"
        }
      ]
    }
  ]
}


问:
Heroku can't find gunicorn command
I'm trying to put a small Flask app on Heroku. When it starts, it gives me the following message, from the logs:

```<code>2015-03-11T01:05:26.737788+00:00 heroku[web.1]: State changed from crashed to starting
2015-03-11T01:05:31.409851+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2015-03-11T01:05:33.863601+00:00 app[web.1]: bash: gunicorn: command not found
2015-03-11T01:05:34.644419+00:00 heroku[web.1]: Process exited with status 127
2015-03-11T01:05:34.668264+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

My Procfile is

```<code>web: gunicorn application:app
</code>```

, and application.py is the file I want to run. I looked up this problem and saw that it was sometimes caused by gunicorn not being in requirements.txt, but my requirements.txt has it, with this line:

```<code>gunicorn==19.3.0
</code>```

.
I tried running

```<code>heroku run pip install gunicorn
</code>```

and it told me it installed gunicorn-19.3.0 successfully. But when I tried running it on Heroku with

```<code>heroku run gunicorn
</code>```

it against gave me the "bash: gunicorn: command not found" message.

答:
Add gunicorn to requirements.txt.

In pursuit of 12-factor apps, changes to the filesystem made with heroku run are ephemeral.

Title: Heroku can't find gunicorn command

Body:
I'm trying to put a small Flask app on Heroku. When it starts, it gives me the following message, from the logs:

2015-03-11T01:05:26.737788+00:00 heroku[web.1]: State changed from crashed to starting
2015-03-11T01:05:31.409851+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2015-03-11T01:05:33.863601+00:00 app[web.1]: bash: gunicorn: command not found
2015-03-11T01:05:34.644419+00:00 heroku[web.1]: Process exited with status 127
2015-03-11T01:05:34.668264+00:00 heroku[web.1]: State changed from starting to crashed

My Procfile is

web: gunicorn application:app

, and application.py is the file I want to run. I looked up this problem and saw that it was sometimes caused by gunicorn not being in requirements.txt, but my requirements.txt has it, with this line:

gunicorn==19.3.0

.
I tried running

heroku run pip install gunicorn

and it told me it installed gunicorn-19.3.0 successfully. But when I tried running it on Heroku with

heroku run gunicorn

it against gave me the "bash: gunicorn: command not found" message.


问:
BigQuery SQL how to get total count when using LIMIT
If I use LIMIT 10 in a SQL query (using BigQuery), is there a way to also return the total count?

For example, 100 rows exist. How can I query to return the first 10 but also display to users how many rows are available in total without doing a separate count(id) aggregate query?

答:
To add to Mikhail's answer, you may want to do this to see the count of the unique values in a grouped query. In the following example, there are 10 unique values of R, but you only want to see the the first 4, along with the count of the unique rows. I also added showing the count for each group and overall count of every row. (Standard SQL below)

```<code>WITH YourTable AS (
  SELECT 1 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 10 AS r
)
SELECT
  r,
  SUM(1) OVER (ORDER BY r ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CountOfAllUniqueRows,
  COUNT(r) AS CountOfEachR,
  SUM(COUNT(R)) OVER (ORDER BY r ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CountOfAllRows
FROM YourTable
GROUP BY r
ORDER BY r
LIMIT 4
</code>```

And giving the results of:

```<code>r   CountOfAllUniqueRows    CountOfEachR    CountOfAllRows
1   10                      8               68
2   10                      6               68
3   10                      7               68
4   10                      6               68
</code>```

Body:
To add to Mikhail's answer, you may want to do this to see the count of the unique values in a grouped query. In the following example, there are 10 unique values of R, but you only want to see the the first 4, along with the count of the unique rows. I also added showing the count for each group and overall count of every row. (Standard SQL below)

WITH YourTable AS (
  SELECT 1 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 1 AS r UNION ALL
  SELECT 2 AS r UNION ALL
  SELECT 3 AS r UNION ALL
  SELECT 4 AS r UNION ALL
  SELECT 5 AS r UNION ALL
  SELECT 6 AS r UNION ALL
  SELECT 7 AS r UNION ALL
  SELECT 8 AS r UNION ALL
  SELECT 9 AS r UNION ALL
  SELECT 10 AS r
)
SELECT
  r,
  SUM(1) OVER (ORDER BY r ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CountOfAllUniqueRows,
  COUNT(r) AS CountOfEachR,
  SUM(COUNT(R)) OVER (ORDER BY r ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CountOfAllRows
FROM YourTable
GROUP BY r
ORDER BY r
LIMIT 4

And giving the results of:

r   CountOfAllUniqueRows    CountOfEachR    CountOfAllRows
1   10                      8               68
2   10                      6               68
3   10                      7               68
4   10                      6               68


问:
How i know when job occur on list view (SQL Server 2000)
I trying to write a job monitor on Listview, I get information from sysjob and sysjobhistory tables in msdb database. How I know when  job occur on list view?

I don't understand about run_time column. I want to show last job on top line and show time
when job occur as shown in picture (i have 2 job Fern and Same)

Form sysjobhistory show number code that I don’t know it mean such as 70000,71000 …
but I want to show time as 11.00am, 10.00am... as shown in picture.

I want to show info continuously follow time schedule recurring for monitoring JOB.

```<code>  public void GetJobsAndStatus()
   {
       string sqlJobQuery = "select j.job_id, j.name, j.enabled, jh.run_status, jh.message, jh.run_date, jh.step_name, jh.run_time from sysjobs j inner join sysjobhistory jh on j.job_id = jh.job_id";

       // create SQL connection and set up SQL Command for query
       using (SqlConnection _con = new SqlConnection("server=10.15.13.70;database=msdb;user id=sa;pwd="))
       using (SqlCommand _cmd = new SqlCommand(sqlJobQuery, _con))
       {
           try
           {
               // open connection
               _con.Open();

               // create SQL Data Reader and grab data
               using (SqlDataReader rdr = _cmd.ExecuteReader())
               {
                   // as long as we get information from the reader
                   while (rdr.Read())
                   {
                       Guid jobID = rdr.GetGuid(0);        // read Job_id
                       string jobName = rdr.GetString(1);  // read Job name
                       byte jobEnabled = rdr.GetByte(2);   // read Job enabled flag
                       int jobStatus = rdr.GetInt32(3);    // read run_state from jobhistory
                       string jobMessage = rdr.GetString(4);
                       int jobRunDate = rdr.GetInt32(5);
                       string jobStepName = rdr.GetString(6);
                       int jobRunTime = rdr.GetInt32(7);

                       String[] lviData = new String[]
        {
            jobID.ToString(),
            jobName.ToString(),
            jobStepName.ToString(),
            jobMessage.ToString(),
            jobStatus.ToString(),
            jobRunDate.ToString(),
            jobRunTime.ToString(),

        };
            ListViewItem lvi = new ListViewItem(lviData);
            listView1.Items.Add(lvi);

              }

                   rdr.Close();
               }
           }
           catch (Exception e)
           {

               MessageBox.Show(e.Message);
           }
           // close connection again
           _con.Close();

          // return _jobs;
       }
   }
</code>```

The result did not meet expectations such as the arrangement of the line.

Please suggestion how to do.(using MS Visual Studio 2008 (C#)) Thank you.

And Thank you for your past help.

答:
I have application on client for get job info form sql server via ODBC.

Is it possible if I use timer to get job info every 1s and show job info on listview. *i want everything is realtime *

how to do?

```<code>  private void button1_Click_1(object sender, EventArgs e)
    {

            timer1.Enabled = true;

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        GetJobsAndStatus();
    }
</code>```

Body:
I trying to write a job monitor on Listview, I get information from sysjob and sysjobhistory tables in msdb database. How I know when  job occur on list view?

I don't understand about run_time column. I want to show last job on top line and show time
when job occur as shown in picture (i have 2 job Fern and Same)

Form sysjobhistory show number code that I don’t know it mean such as 70000,71000 …
but I want to show time as 11.00am, 10.00am... as shown in picture.

I want to show info continuously follow time schedule recurring for monitoring JOB.

  public void GetJobsAndStatus()
   {
       string sqlJobQuery = "select j.job_id, j.name, j.enabled, jh.run_status, jh.message, jh.run_date, jh.step_name, jh.run_time from sysjobs j inner join sysjobhistory jh on j.job_id = jh.job_id";

       // create SQL connection and set up SQL Command for query
       using (SqlConnection _con = new SqlConnection("server=10.15.13.70;database=msdb;user id=sa;pwd="))
       using (SqlCommand _cmd = new SqlCommand(sqlJobQuery, _con))
       {
           try
           {
               // open connection
               _con.Open();

               // create SQL Data Reader and grab data
               using (SqlDataReader rdr = _cmd.ExecuteReader())
               {
                   // as long as we get information from the reader
                   while (rdr.Read())
                   {
                       Guid jobID = rdr.GetGuid(0);        // read Job_id
                       string jobName = rdr.GetString(1);  // read Job name
                       byte jobEnabled = rdr.GetByte(2);   // read Job enabled flag
                       int jobStatus = rdr.GetInt32(3);    // read run_state from jobhistory
                       string jobMessage = rdr.GetString(4);
                       int jobRunDate = rdr.GetInt32(5);
                       string jobStepName = rdr.GetString(6);
                       int jobRunTime = rdr.GetInt32(7);

                       String[] lviData = new String[]
        {
            jobID.ToString(),
            jobName.ToString(),
            jobStepName.ToString(),
            jobMessage.ToString(),
            jobStatus.ToString(),
            jobRunDate.ToString(),
            jobRunTime.ToString(),

        };
            ListViewItem lvi = new ListViewItem(lviData);
            listView1.Items.Add(lvi);

              }

                   rdr.Close();
               }
           }
           catch (Exception e)
           {

               MessageBox.Show(e.Message);
           }
           // close connection again
           _con.Close();

          // return _jobs;
       }
   }

The result did not meet expectations such as the arrangement of the line.

Please suggestion how to do.(using MS Visual Studio 2008 (C#)) Thank you.

And Thank you for your past help.

Body:
I have application on client for get job info form sql server via ODBC.

Is it possible if I use timer to get job info every 1s and show job info on listview. *i want everything is realtime *

how to do?

  private void button1_Click_1(object sender, EventArgs e)
    {

            timer1.Enabled = true;

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        GetJobsAndStatus();
    }


问:
SAS Proc MI SAS output
Proc MI is used to impute missing values in a SAS dataset. Is there a way to obtain a SAS code from Proc MI procedure, so that we can score datasets with missing value without having to use Proc MI procedure? This is needed so that dataset in production environment can be score consistently. I dont want to use Proc MI in production environment.

Thanks!

答: I don't believe this is possible, at least not in the way that it is for proc import. If you want to use a purely deterministic imputation algorithm, you will need to write your own data step to do it.

Title: SAS Proc MI SAS output


问:
Value in cell to match in a List I have and do it to every cell under that too(Title Not Good)
I would like the macro/code to take the Product that was entered in that cell (relative reference I guess) and scan a list of Products I have. If it doesn't match I would like the message box to tell me which product entered doesn't match with one in my product list and to return its row number where it was entered.

So to give you another example. Lets say we'll enter a number "1" in a cell. I need the macro to search my list of numbers 1-100, if 1 isn't in there I would like it to tell me. Let's say the next number entered (in the following cell under) was a 101. A message box would tell me 101 is not in my number list and its located in row 2.

It probably needs loops. As I will have a range of about 500 cells going down in that column that I would like it to search that product with a list.

答:
Right click on Sheet Tab --> View Code --> and paste the code given below into the opened code window --> Close the VB Editor --> Save your workbook as Macro-Enabled Workbook.
The following code assumes that you have a named range called "List" on Sheet2 (code name not the tab name).
If you input a value in column A starting from row2, the code will automatically check if the value you entered is found in the named range List and if it doesn't find that value, a msgbox will be popped up to give you some information.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Target.Column = 1 And Target.Row > 1 Then
    If Target <> "" Then
        If Application.CountIf(Sheet2.Range("List"), Target.Value) = 0 Then
            MsgBox "The value " & Target.Value & " you entered in cell " & Target.Address(0, 0) & " was not found in the List", vbExclamation, "Item Not Found!"
        End If
    End If
End If
End Sub
</code>```

Edit:

Replace the above proposed code with the following code.
The following code will be useful if you change multiple cells at once and will provide you a list of all the values which were not found in the List named range.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim str As String
Dim Found As Boolean
str = "The following values were not found in the List." & vbNewLine & vbNewLine
If Target.Column = 1 And Target.Row > 1 Then
    For Each cell In Target
        If cell <> "" Then
            If Application.CountIf(Sheet2.Range("List"), cell.Value) = 0 Then
                Found = True
                str = str & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
            End If
        End If
    Next cell
End If
If Found Then MsgBox str, vbExclamation, "Values Not Found!"
End Sub
</code>```

Body:
Right click on Sheet Tab --> View Code --> and paste the code given below into the opened code window --> Close the VB Editor --> Save your workbook as Macro-Enabled Workbook.
The following code assumes that you have a named range called "List" on Sheet2 (code name not the tab name).
If you input a value in column A starting from row2, the code will automatically check if the value you entered is found in the named range List and if it doesn't find that value, a msgbox will be popped up to give you some information.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Target.Column = 1 And Target.Row > 1 Then
    If Target <> "" Then
        If Application.CountIf(Sheet2.Range("List"), Target.Value) = 0 Then
            MsgBox "The value " & Target.Value & " you entered in cell " & Target.Address(0, 0) & " was not found in the List", vbExclamation, "Item Not Found!"
        End If
    End If
End If
End Sub

Edit:

Replace the above proposed code with the following code.
The following code will be useful if you change multiple cells at once and will provide you a list of all the values which were not found in the List named range.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim str As String
Dim Found As Boolean
str = "The following values were not found in the List." & vbNewLine & vbNewLine
If Target.Column = 1 And Target.Row > 1 Then
    For Each cell In Target
        If cell <> "" Then
            If Application.CountIf(Sheet2.Range("List"), cell.Value) = 0 Then
                Found = True
                str = str & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
            End If
        End If
    Next cell
End If
If Found Then MsgBox str, vbExclamation, "Values Not Found!"
End Sub


问:
Web Api Request Throws "Error while copying content to a stream."
I'm trying to implement this code example, but get a HttpRequestException - "Error while copying content to a stream." when the ReadAsStringAsync() method is called.  The inner exception is "Cannot access a disposed object."  I'm using Fiddler to make the request.  I don't understand. Can someone explain why I'm getting this exception and offer a solution?

Web Api Method:

```<code>public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    try
    {
        var jsonString = await request.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {
        throw;
    }
    return new HttpResponseMessage(HttpStatusCode.Created);
}
</code>```

Fiddler (POST):

```<code>User-Agent: Fiddler
Host: localhost:23567
Content-Length: 18
Content-Type: application/json; charset=utf-8
Body{"Test":1}
</code>```

Edit:

I have a clue, but need verification.  On the Web Api controller, I have an ActionFilterAttribute and in its OnActionExecuting override, there's this line:

```<code>public override async void OnActionExecuting(HttpActionContext actionContext)
{
    // omitted code
    actionContext.Request.Content.ReadAsStreamAsync();
}
</code>```

Could it be that because the Content is read here, it's not available again?  If so, how can I make it available in the method?  Is the Content here the same as the HttpRequestMessage?  This may contain an answer.

答:
I hope this (late) post will help someone someday...

In short: the accepted answer suggests to read the entire file as string (and not as stream) in order to bypass a read problem

BUT... reading a file as a string is not such a great idea

I figured out that replacing MultipartFormDataStreamProvider with MultipartMemoryStreamProvider works great - and let you read your uploaded file as desired

My code (at least the relevant parts of it)

```<code>    [HttpPost]
    [Route("upload/file")] // you may replace this route to suit your api service
    public async Task<IHttpActionResult> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Unsupported media type");
        }

        try
        {
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            if (provider.Contents.Count == 0) return InternalServerError(new Exception("Upload failed"));

            var file = provider.Contents[0]; // if you handle more then 1 file you can loop provider.Contents

            var buffer = await file.ReadAsByteArrayAsync();

            // .. do whatever needed here

            return Ok();

        }
        catch (Exception ex)
        {
            return BadRequest(ex.GetBaseException().Message);
        }
    }
</code>```

Body:
I'm trying to implement this code example, but get a HttpRequestException - "Error while copying content to a stream." when the ReadAsStringAsync() method is called.  The inner exception is "Cannot access a disposed object."  I'm using Fiddler to make the request.  I don't understand. Can someone explain why I'm getting this exception and offer a solution?

Web Api Method:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    try
    {
        var jsonString = await request.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {
        throw;
    }
    return new HttpResponseMessage(HttpStatusCode.Created);
}

Fiddler (POST):

User-Agent: Fiddler
Host: localhost:23567
Content-Length: 18
Content-Type: application/json; charset=utf-8
Body{"Test":1}

Edit:

I have a clue, but need verification.  On the Web Api controller, I have an ActionFilterAttribute and in its OnActionExecuting override, there's this line:

public override async void OnActionExecuting(HttpActionContext actionContext)
{
    // omitted code
    actionContext.Request.Content.ReadAsStreamAsync();
}

Could it be that because the Content is read here, it's not available again?  If so, how can I make it available in the method?  Is the Content here the same as the HttpRequestMessage?  This may contain an answer.

Body:
I hope this (late) post will help someone someday...

In short: the accepted answer suggests to read the entire file as string (and not as stream) in order to bypass a read problem

BUT... reading a file as a string is not such a great idea

I figured out that replacing MultipartFormDataStreamProvider with MultipartMemoryStreamProvider works great - and let you read your uploaded file as desired

My code (at least the relevant parts of it)

    [HttpPost]
    [Route("upload/file")] // you may replace this route to suit your api service
    public async Task<IHttpActionResult> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Unsupported media type");
        }

        try
        {
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            if (provider.Contents.Count == 0) return InternalServerError(new Exception("Upload failed"));

            var file = provider.Contents[0]; // if you handle more then 1 file you can loop provider.Contents

            var buffer = await file.ReadAsByteArrayAsync();

            // .. do whatever needed here

            return Ok();

        }
        catch (Exception ex)
        {
            return BadRequest(ex.GetBaseException().Message);
        }
    }


问:
How to prevent quotes being output as html escape codes in c#
I'm not actually sure this is c# per se but I'm working in a .cshtml file (in episerver).

I'm setting a string variable that includes quotes. This is a simplified version:

```<code>@{
    var backgroundcontent = "class='background' data-transition='mytransition'";
    if (Model.CurrentBlock.Photo) {
        backgroundcontent = "class='photo' data-transition='none'";
    }
  }
</code>```

When this is rendered in the page, I'm getting ' which is great if I'm rendering it inside a tag, but not when I need it in the tag itself.

Am I stuck with the html quotes (and have to do something more complicated like setting two variables for the attributes), or is there a way to override them?

答: Try Html.Raw(backgroundcontent);, this should prevent default string escaping.

Body:
I'm not actually sure this is c# per se but I'm working in a .cshtml file (in episerver).

I'm setting a string variable that includes quotes. This is a simplified version:

@{
    var backgroundcontent = "class='background' data-transition='mytransition'";
    if (Model.CurrentBlock.Photo) {
        backgroundcontent = "class='photo' data-transition='none'";
    }
  }

When this is rendered in the page, I'm getting ' which is great if I'm rendering it inside a tag, but not when I need it in the tag itself.

Am I stuck with the html quotes (and have to do something more complicated like setting two variables for the attributes), or is there a way to override them?


问:
How to geocode a phone number in the United States?
I am looking for a way to get the latitude and longitude coordinates of any area code + prefix land line phone in the United States.  Does anyone know of a data provider or service that could be used to do this?

EDIT:  I understand that the location of cell phones or VOIP lines probably cannot be geocoded and this is fine by me.  I am only interested in POTS phone numbers.  Although, it would be nice to be able to identify the type of phone service based on the prefix (if this is even possible).

答:
[EveryoneAPI][1] [edit: link now goes to a new site not related] will do exactly what you're looking for.

You can limit your query to location-only by adding "data=location" to your HTTP request, and you'll get back something like this:

```<code>"location": {
  "city": "Birmingham",
  "geo": {
    "latitude": "33.51685254860801",
    "longitude": "-86.81075983815001"
  },
  "state": "AL",
  "zip": "35203"
}
</code>```

Disclaimer: I am the CEO of Telo.
[1]: https://www.everyoneapi.com/

Body:
[EveryoneAPI][1] [edit: link now goes to a new site not related] will do exactly what you're looking for.

You can limit your query to location-only by adding "data=location" to your HTTP request, and you'll get back something like this:

"location": {
  "city": "Birmingham",
  "geo": {
    "latitude": "33.51685254860801",
    "longitude": "-86.81075983815001"
  },
  "state": "AL",
  "zip": "35203"
}

Disclaimer: I am the CEO of Telo.
[1]: https://www.everyoneapi.com/

ContentLicense: CC BY-SA 4.0


问:
How to solve Invalid JSON Primitive error on Ajax?
I am trying to perform ajax using webmethod on Asp.net,

And I am using JQuery-3.1.1

I want to pass the value to server and get back the value. I don't know what I did wrong.

Asp.net Code

```<code><div class="row">
   <asp:Button ID="btnSave" runat="server" CssClass="btn btn-info"  Text="save" />
</div>
</code>```

Jquery Code

```<code>$(document).ready(function () {
    $('#btnSave').click(function () {
        var name= 'xxx';

        $.ajax({
            type: "POST",
            url: "AjaxWebMethod.aspx/getFileExistOrNot",
            data: '{fileName:'+name+'}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("failed ="+response.d);
            },
            error: function (response) {
                alert("error ="+response.d);  //This alert is executing
            }
        });

        function OnSuccess(response) {
            alert("Result ="+response.d.mydata);
        }
        return false;
    });
});
</code>```

C# code

```<code>public partial class AjaxWebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string mydata="ajaxworking";
        return mydata;
    }
}
</code>```

I don't know really where I did my mistake

Error message on console

{Message: "Invalid JSON primitive: xxx.",…}

ExceptionType:"System.ArgumentException"

Message:"Invalid JSON primitive: xxx."

Can you give the solution with proper reason. that will good for me to understand more, thanks

答:
Your postData is invalid JSON, a string needs quotes around it:

```<code>'{fileName:'+name+'}'
</code>```

It should be:

```<code> '{fileName:"'+name+'"}'
</code>```

Body:
I am trying to perform ajax using webmethod on Asp.net,

And I am using JQuery-3.1.1

I want to pass the value to server and get back the value. I don't know what I did wrong.

Asp.net Code

   <asp:Button ID="btnSave" runat="server" CssClass="btn btn-info"  Text="save" />

Jquery Code

$(document).ready(function () {
    $('#btnSave').click(function () {
        var name= 'xxx';

        $.ajax({
            type: "POST",
            url: "AjaxWebMethod.aspx/getFileExistOrNot",
            data: '{fileName:'+name+'}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("failed ="+response.d);
            },
            error: function (response) {
                alert("error ="+response.d);  //This alert is executing
            }
        });

        function OnSuccess(response) {
            alert("Result ="+response.d.mydata);
        }
        return false;
    });
});

C# code

public partial class AjaxWebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string mydata="ajaxworking";
        return mydata;
    }
}

I don't know really where I did my mistake

Error message on console

{Message: "Invalid JSON primitive: xxx.",…}

ExceptionType:"System.ArgumentException"

Message:"Invalid JSON primitive: xxx."

Can you give the solution with proper reason. that will good for me to understand more, thanks

Body:
Your postData is invalid JSON, a string needs quotes around it:

'{fileName:'+name+'}'

It should be:

 '{fileName:"'+name+'"}'


问:
Typed Racket - dynamic function calls (string to procedure) revisited
About a year ago, @soegaard provided an answer to an interesting problem - how to take a string and return the procedure named in that string. The solution was simple and elegant.

Enter typed racket and a twist.

I can make it work in typed racket as long as it returns only functions with the same arity, for example (-> Number Number Number), but if I try to have it able to return functions with different arities, such as shown below, I cannot figure out how to make the require/typed call work.

Here is the modified file with my second function with a different arity.

```<code>#lang racket
(provide string->procedure add square)

(define (add x y)
  (+ x y))

(define (square x)
  (sqr x))

(define ns (variable-reference->namespace (#%variable-reference)))

(define (string->procedure s)
  (define sym (string->symbol s))
  (eval sym ns))

(string->procedure "add")

((string->procedure "add") 1 2)

((string->procedure "square") 5)
</code>```

And here is the call that only works with the "add" fuction or any other function that takes two numbers and returns one number.

```<code>#lang typed/racket

(require/typed "string-procedure.rkt"
               [string->procedure
                (-> String (-> Number Number Number))]
               [add (-> Number Number Number)]
               [square (-> Number Number)])
</code>```

I've tried using case-> and unions to no avail. Using case-> for the return type at least will run but then it fails all calls.

In case you think I'm nuts for trying this, what I'm trying to do is take the result of a database call, a string, and determine the correct procedure to call to access the appropriate data element in a struct. I can do it with a long case statement, but I was hoping for a more elegant solution.

Thank you.

答:
I don't think you want to use eval, or to solve this problem in quite this way. Specifically: what if the database contains a string that refers to a function that doesn't exist, or a function that you didn't want to have called? This is how security problems arise.

I would say that in this case, you'd probably be willing to specify the names of the procedures that are "legal", and you can probably do that easily with a macro that doesn't mangle hygiene too badly:

```<code>#lang typed/racket

;; defines the 'db-callable' syntax. Put this in a library file...
(define-syntax (db-callable stx)
  (syntax-case stx ()
    [(_ fun-name [id ...])
     (with-syntax ([(id-strs ...)
                    (for/list ([id-stx (in-list (syntax->list #'(id ...)))])
                      (symbol->string (syntax-e id-stx)))])
       #'(define (fun-name str)
           (match str
             [id-str id] ...)))]))

;; here are some functions we want the DB to be able to call
(define (f x) 3)
(define (g x) 4)

;; here's the list of functions we want the db to be able to call:
(db-callable getfun [f g])

((getfun "f") 9)
((getfun "g") 123)
</code>```

Body:
About a year ago, @soegaard provided an answer to an interesting problem - how to take a string and return the procedure named in that string. The solution was simple and elegant.

Enter typed racket and a twist.

I can make it work in typed racket as long as it returns only functions with the same arity, for example (-> Number Number Number), but if I try to have it able to return functions with different arities, such as shown below, I cannot figure out how to make the require/typed call work.

Here is the modified file with my second function with a different arity.

#lang racket
(provide string->procedure add square)

(define (add x y)
  (+ x y))

(define (square x)
  (sqr x))

(define ns (variable-reference->namespace (#%variable-reference)))

(define (string->procedure s)
  (define sym (string->symbol s))
  (eval sym ns))

(string->procedure "add")

((string->procedure "add") 1 2)

((string->procedure "square") 5)

And here is the call that only works with the "add" fuction or any other function that takes two numbers and returns one number.

#lang typed/racket

(require/typed "string-procedure.rkt"
               [string->procedure
                (-> String (-> Number Number Number))]
               [add (-> Number Number Number)]
               [square (-> Number Number)])

I've tried using case-> and unions to no avail. Using case-> for the return type at least will run but then it fails all calls.

In case you think I'm nuts for trying this, what I'm trying to do is take the result of a database call, a string, and determine the correct procedure to call to access the appropriate data element in a struct. I can do it with a long case statement, but I was hoping for a more elegant solution.

Thank you.

Body:
I don't think you want to use eval, or to solve this problem in quite this way. Specifically: what if the database contains a string that refers to a function that doesn't exist, or a function that you didn't want to have called? This is how security problems arise.

I would say that in this case, you'd probably be willing to specify the names of the procedures that are "legal", and you can probably do that easily with a macro that doesn't mangle hygiene too badly:

#lang typed/racket

;; defines the 'db-callable' syntax. Put this in a library file...
(define-syntax (db-callable stx)
  (syntax-case stx ()
    [(_ fun-name [id ...])
     (with-syntax ([(id-strs ...)
                    (for/list ([id-stx (in-list (syntax->list #'(id ...)))])
                      (symbol->string (syntax-e id-stx)))])
       #'(define (fun-name str)
           (match str
             [id-str id] ...)))]))

;; here are some functions we want the DB to be able to call
(define (f x) 3)
(define (g x) 4)

;; here's the list of functions we want the db to be able to call:
(db-callable getfun [f g])

((getfun "f") 9)
((getfun "g") 123)


问:
Problems normalizing and inserting data into Oracle music database
I'm working on a school project for a beginner SQL course where I've uploaded a portion of my music library's metadata into Oracle:

```<code>CREATE TABLE  "MUSIC"
   (    "ID" NUMBER,
    "TITLE" VARCHAR2(255),
    "ARTIST" VARCHAR2(30),
    "ALBUM" VARCHAR2(255),
    "TRACK" NUMBER,
    "YEAR" NUMBER,
    "GENRE" VARCHAR2(255),
    "FILENAME" VARCHAR2(255),
    "NAMEID" NUMBER,
     CONSTRAINT "MUSIC_PK" PRIMARY KEY ("ID") ENABLE
   )
/

CREATE OR REPLACE TRIGGER  "bi_MUSIC"
  before insert on "MUSIC"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;

/
ALTER TRIGGER  "bi_MUSIC" ENABLE
/

CREATE TABLE  "ALBUMS"
   (    "ID" NUMBER,
    "ARTISTID" NUMBER,
    "NAME" VARCHAR2(255),
    "RELEASEDATE" NUMBER,
    "GENREID" NUMBER,
    "GENRENAME" VARCHAR2(255),
     CONSTRAINT "ALBUMS_PK" PRIMARY KEY ("ID") ENABLE
   )
/
ALTER TABLE  "ALBUMS" ADD CONSTRAINT "ALBUMS_CON2" FOREIGN KEY ("ARTISTID")
      REFERENCES  "ARTIST" ("ID") ENABLE
/
ALTER TABLE  "ALBUMS" ADD CONSTRAINT "ALBUMS_CON3" FOREIGN KEY ("GENREID")
      REFERENCES  "GENRES" ("ID") ENABLE
/
CREATE TABLE  "ARTIST"
   (    "ID" NUMBER,
    "NAME" VARCHAR2(255),
     CONSTRAINT "ARTIST_PK" PRIMARY KEY ("ID") ENABLE
   )
/
CREATE TABLE  "GENRES"
   (    "ID" NUMBER,
    "NAME" VARCHAR2(255),
     CONSTRAINT "GENRES_PK" PRIMARY KEY ("ID") ENABLE
   )
/
CREATE TABLE  "TRACKS"
   (    "ID" NUMBER,
    "ALBUMID" NUMBER,
    "NAME" VARCHAR2(255),
    "NUMBER" NUMBER,
     CONSTRAINT "TRACKS_PK" PRIMARY KEY ("ID") ENABLE
   )
/
ALTER TABLE  "TRACKS" ADD CONSTRAINT "TRACKS_CON3" FOREIGN KEY ("ALBUMID")
      REFERENCES  "ALBUMS" ("ID") ENABLE
/
</code>```

The MUSIC table is not part of the actual hierarchy, it's only there to allow me to upload data into the database and then insert it into the ALBUMS, ARTIST, GENRES, and TRACKS tables. I've assigned primary and foreign keys between those 4 tables as described in the top answer for this question, and trimmed columns I don't have:
Music library MySQL database

I've successfully inserted some of the data already, but now I've run into issues with inserting data into the GENRENAME and GENREID columns in the ALBUMS table. Inserting the following:

```<code>insert into albums (genrename, genreid)
select name, id
from genres
</code>```

yields the following error message:

ORA-01400: cannot insert NULL into ("TIMOILONEN"."ALBUMS"."ID")`

I've already got two columns (ID and ARTISTID) with the identical values in this table which I am not even sure is permitted.

In addition, trying to insert missing data into the TRACKS table yields errors:

```<code>insert into tracks (name, number)
select title, track
from music`
</code>```

ORA-01747: invalid user.table.column, table.column, or column
  specification

Both the NAME and TITLE columns have data type VARCHAR2(255) while the NUMBER and TRACK columns have data type NUMBER.
I also have the ID and ALBUMID columns with identical data in this table, like in the ALBUMS table.

I greatly appreciate anyone willing to help me with filling the missing data and properly normalizing the tables. I was already due to present this earlier this week, but had to postpone my presentation to this coming Friday due to these problems.

--

Following advise given to me below, I created triggers for the ALBUMS and TRACKS tables for inserting values into the ID columns, copying the commands from the MUSIC table where inserting ID works correctly. However, I am still unsure as to what kind of command I am supposed to use to activate the trigger.

```<code>CREATE OR REPLACE TRIGGER  "bi_TRACKS"
  before insert on "TRACKS"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;

/
ALTER TRIGGER  "bi_TRACKS" ENABLE
/

CREATE OR REPLACE TRIGGER  "bi_ALBUMS"
  before insert on "ALBUMS"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;
/
ALTER TRIGGER  "bi_ALBUMS" ENABLE
/

insert into albums (genreid, genrename, id)
select id, name, 'NULL'
from genres
</code>```

ORA-01722: invalid number

答:
Inserting the following:

```<code>insert into albums (genrename, genreid)
select name, id
from genres
</code>```

yields the following error message:

ORA-01400: cannot insert NULL into ("TIMOILONEN"."ALBUMS"."ID")`

This is because the ID column in ALBUMS is not allowed to have NULL values in it.

When creating a table, you can specify any column in a table to be NOT NULL.  Oracle will then stop you from inserting NULL values into that column. However, if a column is the primary key (or part of the primary key) it will automatically be made NOT NULL.  This has happened to the ID column of ALBUMS.

If you want to insert an album into ALBUMS, you must give the database the ID of the album to create.  You could specify values for these IDs into the INSERT statement you use to put data into these tables.  Alternatively, you could use a sequence and a trigger to insert values into the ID column, as you are doing with the MUSIC table.  If you're using Oracle 12c you could also use identity columns.

In addition, trying to insert missing data into the TRACKS table
  yields errors:

```<code>insert into tracks (name, number)
select title, track
from music
</code>```

ORA-01747: invalid user.table.column, table.column, or column
    specification

This is a more unfortunate problem.  Oracle here is objecting to a column named number, because there is also a datatype named NUMBER and it can't tell the difference.  (With any database you are likely to run into problems if you have a column name the same as a keyword that the database recognises.)  You can get round this by either renaming the column to TRACK_NUMBER, say, or by putting the column name in double-quotes:

```<code>insert into tracks (name, "NUMBER")
select title, track
from music
</code>```

Either way, note however that you are then likely to see the error

ORA-01400: cannot insert NULL into ("TIMOILONEN"."TRACKS"."ID")

This however is just the first problem again.  The ID column in TRACKS needs a value and you are not giving it anything.

Body:
I'm working on a school project for a beginner SQL course where I've uploaded a portion of my music library's metadata into Oracle:

CREATE TABLE  "MUSIC"
   (    "ID" NUMBER,
    "TITLE" VARCHAR2(255),
    "ARTIST" VARCHAR2(30),
    "ALBUM" VARCHAR2(255),
    "TRACK" NUMBER,
    "YEAR" NUMBER,
    "GENRE" VARCHAR2(255),
    "FILENAME" VARCHAR2(255),
    "NAMEID" NUMBER,
     CONSTRAINT "MUSIC_PK" PRIMARY KEY ("ID") ENABLE
   )
/

CREATE OR REPLACE TRIGGER  "bi_MUSIC"
  before insert on "MUSIC"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;

/
ALTER TRIGGER  "bi_MUSIC" ENABLE
/

CREATE TABLE  "ALBUMS"
   (    "ID" NUMBER,
    "ARTISTID" NUMBER,
    "NAME" VARCHAR2(255),
    "RELEASEDATE" NUMBER,
    "GENREID" NUMBER,
    "GENRENAME" VARCHAR2(255),
     CONSTRAINT "ALBUMS_PK" PRIMARY KEY ("ID") ENABLE
   )
/
ALTER TABLE  "ALBUMS" ADD CONSTRAINT "ALBUMS_CON2" FOREIGN KEY ("ARTISTID")
      REFERENCES  "ARTIST" ("ID") ENABLE
/
ALTER TABLE  "ALBUMS" ADD CONSTRAINT "ALBUMS_CON3" FOREIGN KEY ("GENREID")
      REFERENCES  "GENRES" ("ID") ENABLE
/
CREATE TABLE  "ARTIST"
   (    "ID" NUMBER,
    "NAME" VARCHAR2(255),
     CONSTRAINT "ARTIST_PK" PRIMARY KEY ("ID") ENABLE
   )
/
CREATE TABLE  "GENRES"
   (    "ID" NUMBER,
    "NAME" VARCHAR2(255),
     CONSTRAINT "GENRES_PK" PRIMARY KEY ("ID") ENABLE
   )
/
CREATE TABLE  "TRACKS"
   (    "ID" NUMBER,
    "ALBUMID" NUMBER,
    "NAME" VARCHAR2(255),
    "NUMBER" NUMBER,
     CONSTRAINT "TRACKS_PK" PRIMARY KEY ("ID") ENABLE
   )
/
ALTER TABLE  "TRACKS" ADD CONSTRAINT "TRACKS_CON3" FOREIGN KEY ("ALBUMID")
      REFERENCES  "ALBUMS" ("ID") ENABLE
/

The MUSIC table is not part of the actual hierarchy, it's only there to allow me to upload data into the database and then insert it into the ALBUMS, ARTIST, GENRES, and TRACKS tables. I've assigned primary and foreign keys between those 4 tables as described in the top answer for this question, and trimmed columns I don't have:
Music library MySQL database

I've successfully inserted some of the data already, but now I've run into issues with inserting data into the GENRENAME and GENREID columns in the ALBUMS table. Inserting the following:

insert into albums (genrename, genreid)
select name, id
from genres

yields the following error message:

ORA-01400: cannot insert NULL into ("TIMOILONEN"."ALBUMS"."ID")`

I've already got two columns (ID and ARTISTID) with the identical values in this table which I am not even sure is permitted.

In addition, trying to insert missing data into the TRACKS table yields errors:

insert into tracks (name, number)
select title, track
from music`

ORA-01747: invalid user.table.column, table.column, or column
  specification

Both the NAME and TITLE columns have data type VARCHAR2(255) while the NUMBER and TRACK columns have data type NUMBER.
I also have the ID and ALBUMID columns with identical data in this table, like in the ALBUMS table.

I greatly appreciate anyone willing to help me with filling the missing data and properly normalizing the tables. I was already due to present this earlier this week, but had to postpone my presentation to this coming Friday due to these problems.

--

Following advise given to me below, I created triggers for the ALBUMS and TRACKS tables for inserting values into the ID columns, copying the commands from the MUSIC table where inserting ID works correctly. However, I am still unsure as to what kind of command I am supposed to use to activate the trigger.

CREATE OR REPLACE TRIGGER  "bi_TRACKS"
  before insert on "TRACKS"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;

/
ALTER TRIGGER  "bi_TRACKS" ENABLE
/

CREATE OR REPLACE TRIGGER  "bi_ALBUMS"
  before insert on "ALBUMS"
  for each row
begin
  if :new."ID" is null then
    select "MUSIC_SEQ".nextval into :new."ID" from sys.dual;
  end if;
end;
/
ALTER TRIGGER  "bi_ALBUMS" ENABLE
/

insert into albums (genreid, genrename, id)
select id, name, 'NULL'
from genres

ORA-01722: invalid number

Body:
Inserting the following:

insert into albums (genrename, genreid)
select name, id
from genres

yields the following error message:

ORA-01400: cannot insert NULL into ("TIMOILONEN"."ALBUMS"."ID")`

This is because the ID column in ALBUMS is not allowed to have NULL values in it.

When creating a table, you can specify any column in a table to be NOT NULL.  Oracle will then stop you from inserting NULL values into that column. However, if a column is the primary key (or part of the primary key) it will automatically be made NOT NULL.  This has happened to the ID column of ALBUMS.

If you want to insert an album into ALBUMS, you must give the database the ID of the album to create.  You could specify values for these IDs into the INSERT statement you use to put data into these tables.  Alternatively, you could use a sequence and a trigger to insert values into the ID column, as you are doing with the MUSIC table.  If you're using Oracle 12c you could also use identity columns.

In addition, trying to insert missing data into the TRACKS table
  yields errors:

insert into tracks (name, number)
select title, track
from music

ORA-01747: invalid user.table.column, table.column, or column
    specification

This is a more unfortunate problem.  Oracle here is objecting to a column named number, because there is also a datatype named NUMBER and it can't tell the difference.  (With any database you are likely to run into problems if you have a column name the same as a keyword that the database recognises.)  You can get round this by either renaming the column to TRACK_NUMBER, say, or by putting the column name in double-quotes:

insert into tracks (name, "NUMBER")
select title, track
from music

Either way, note however that you are then likely to see the error

ORA-01400: cannot insert NULL into ("TIMOILONEN"."TRACKS"."ID")

This however is just the first problem again.  The ID column in TRACKS needs a value and you are not giving it anything.


问:
Versioning of hard-to-diff files
Our department is currently planning to switch from SVN to Git and there are several issues to solve.

One of our products uses MFC for its user interface. The issue we would have when switching to Git would be that the UI code is hard to version control without a central locking mechanism like we have in SVN now.

We're using a ribbon bar in our UI. The layout of the ribbon bar is contained in a XML file. The problem is that this XML is a one liner and thus not easily diff-able (if this word even exists).

Another issue is that there are several resource files that contain IDs for the UI elements and thus are tightly coupled with the UI layout files.

With SVN we're using a locking mechanism to lock those files so that our developers don't interfere with each other.

Git doesn't support such mechanisms by its decentralized nature so I'm wondering how one could solve this issue?

The first and simplest idea would be to coordinate changes to these files with the other team members e.g. via chat. The big disadvantage with this approach is that it's easy to forget about this and it's rather tedious for the single developer who wants to get things done.

A second idea would be to agree upon some team members that are exclusively allowed to change those files. Those members would have to communicate among themselves.

Unfortunately I'm not (yet) a git expert so that I can't imagine any more advanced approaches to this problem.

I guess there are similiar problems out there that already got solved using git but I couldn't find anything so far.

I would like to know if this issue can be solved somehow?

答:
There is no One True General Solution.  Merging is the distributed equivalent of locking, though, for most distributed version control systems.

Quoting (with minor format changes) from my proto-book "concepts and history" chapter, "concurrency model" section (with VCS = version control system, with prefix C and D standing for Centralized and Distributed respectively):

Whether centralized or distributed,
any VCS that lets multiple users work independently of each other
must offer some method for dealing with potential conflicts.
As mentioned earlier, one method is locking:
before changing a file,
the user must obtain a lock,
which is then released upon committing the change.
This simple method has the obvious problem mentioned earlier
of prohibiting parallel work.
It's possible to make the locks finer-grained—Alice
might lock the top half of the file,
leaving the bottom half available for Bob to lock and change—but
this has scaling issues.
In addition, users and/or administrators
must have ways to break locks
since users will lock files but fail
or forget to unlock them (e.g., after deciding not to commit).

If the VCS provides a merge model,
two or more people may work on the same files,
and at defined rendezvous points—in a CVCS,
at check-in / commit time, for instance—they
are given a chance to reconcile their changes.
Merges are also needed when combining branches,
and in modern DVCSes,
the same methods are generally used for both of these.

Note that in a DVCS,
the rendezvous point (and hence any merging)
can occur after checkin.
Bob may be able to pick up Alice's work
before doing his own checking-in,
but because the system is distributed,
Bob does not have to wait for Alice
(nor vice versa).

\exercise{Consider
this deferred merge.  What advantages might it provide?
What disadvantages can you think of?}

\answer{One advantage
is that the check-in process is complete.
Since the merge is a separate step,
if anything goes wrong and the merge is deferred,
this does not hold up the actual check-in.
This might not seem all that important,
but in practice it makes a big difference.
CVCSes could potentially allow this too,
but not all of them do.
(CVS is particularly notorious here.)
One potential disadvantage
is that by the time the merge occurs,
the programmers involved—who are often
the best candidates for doing the merge—may
have moved to other projects,
or forgotten some details of why they made certain changes.}

The above does not get into merge drivers, but Git's have a small flaw.  You can write or select a merge driver that handles, or at least leaves-conflicted and therefore forces users to handle, complex and poorly-machine-managed merges (such as XML files).  This works pretty well in practice, except for one case: when merging commits X and Y with common base B, if only one of X or Y has modified some file with respect to B, the custom merge driver is never even consulted.  In some cases this produces the right answer, and in some it does not.

Title: Versioning of hard-to-diff files


问:
How can I clip the values returned by a layer in Keras?
How can I clip the values returned by the Lambda layer?

I tried using this:

```<code>from keras.backend.tensorflow_backend import clip
from keras.layers.core import Lambda

...
model.add(Dense(1))
model.add(Activation('linear'))
model.add(Lambda(lambda x: clip(x, min_value=200, max_value=1000)))
</code>```

But it does not matter where I put my Lambda+clip, it does not affect anything?

答:
It actually has to be implemented as loss, at the model.compile step.

```<code>from keras import backend as K

def clipped_mse(y_true, y_pred):
    return K.mean(K.square(K.clip(y_pred, 0., 1900.) - K.clip(y_true, 0., 1900.)), axis=-1)

model.compile(loss=clipped_mse)
</code>```

EDIT: Actually, now in hindsight I think that this might not be the right approach. This actually means we do not add penalty for going over too high of a values - it's in a way the opposite of what we want.

Body:
How can I clip the values returned by the Lambda layer?

I tried using this:

from keras.backend.tensorflow_backend import clip
from keras.layers.core import Lambda

...
model.add(Dense(1))
model.add(Activation('linear'))
model.add(Lambda(lambda x: clip(x, min_value=200, max_value=1000)))

But it does not matter where I put my Lambda+clip, it does not affect anything?

Body:
It actually has to be implemented as loss, at the model.compile step.

from keras import backend as K

def clipped_mse(y_true, y_pred):
    return K.mean(K.square(K.clip(y_pred, 0., 1900.) - K.clip(y_true, 0., 1900.)), axis=-1)

model.compile(loss=clipped_mse)

EDIT: Actually, now in hindsight I think that this might not be the right approach. This actually means we do not add penalty for going over too high of a values - it's in a way the opposite of what we want.