问:
Hide code in Jupyter Notebook presentation
I have a jupyter notebook that is a mixture of markdown and code.  In the end I want to render it out as a pdf report and hide the code.  I still want to see the output of the code, the plots and tables, I just don't want to see the code in the final report.  I found the post below that has the code below, which if added to the notebook creates a toggle button that can be used to hide or display the input code.  The problem with that is I wind up with a toggle button at the top of my report.  Does anyone know how to do this?

Post:

http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/

Code:

```<code><script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>
</code>```

答:
If you don't fancy writing your own template, and you're not bothered about outputs, you could use the hide_input_all nbextension, which is provided as part of the jupyter contrib nbextensions package. This provides buttons to hide the inputs (though not outputs) of all code cells, as well as setting metadata items that allow you to export with hidden inputs to html, latex or pdf using templates provided by the package:</p>

```<code>jupyter nbconvert --template=nbextensions --to=html my_notebook.ipynb
</code>```

Body:
I have a jupyter notebook that is a mixture of markdown and code.  In the end I want to render it out as a pdf report and hide the code.  I still want to see the output of the code, the plots and tables, I just don't want to see the code in the final report.  I found the post below that has the code below, which if added to the notebook creates a toggle button that can be used to hide or display the input code.  The problem with that is I wind up with a toggle button at the top of my report.  Does anyone know how to do this?

Post:

http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/

Code:

<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>

Body:
If you don't fancy writing your own template, and you're not bothered about outputs, you could use the hide_input_all nbextension, which is provided as part of the jupyter contrib nbextensions package. This provides buttons to hide the inputs (though not outputs) of all code cells, as well as setting metadata items that allow you to export with hidden inputs to html, latex or pdf using templates provided by the package:

jupyter nbconvert --template=nbextensions --to=html my_notebook.ipynb


来源: stackexchange

问:
How to configure Redis 3.4 and above in master/slave config to resolve error Sentinel running on protected mode?
I am working with Redis 3.2 and while connecting to the sentinel from a differnt machine I get the following error:

```<code>Trying X.X.X.X...
Connected to X.X.X.X.
Escape character is '^]'.
-DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
Connection closed by foreign host.
</code>```

Can somene help me resolve this?

答:
For testing, you can try

```<code>redis-server --protected-mode no
</code>```

This will set Redis protected mode to no.

As from documentation suggested steps.

1) Just disable protected mode sending the command 'CONFIG SET
  protected-mode no' from the loopback interface by connecting to Redis
  from the same host the server is running, however MAKE SURE Redis is
  not publicly accessible from internet if you do so. Use CONFIG REWRITE
  to make this change permanent.

2) Alternatively you can just disable the protected mode by editing
  the Redis configuration file, and setting the protected mode option to
  'no', and then restarting the server.

3) If you started the server manually just for testing, restart it
  with the '--protected-mode no' option.

4) Setup a bind address or an authentication password. NOTE: You only
  need to do one of the above things in order for the server to start
  accepting connections from the outside.

ContentLicense: CC BY-SA 4.0

Body:
I am working with Redis 3.2 and while connecting to the sentinel from a differnt machine I get the following error:

Trying X.X.X.X...
Connected to X.X.X.X.
Escape character is '^]'.
-DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
Connection closed by foreign host.

Can somene help me resolve this?

Body:
For testing, you can try

redis-server --protected-mode no

This will set Redis protected mode to no.

As from documentation suggested steps.

1) Just disable protected mode sending the command 'CONFIG SET
  protected-mode no' from the loopback interface by connecting to Redis
  from the same host the server is running, however MAKE SURE Redis is
  not publicly accessible from internet if you do so. Use CONFIG REWRITE
  to make this change permanent.

2) Alternatively you can just disable the protected mode by editing
  the Redis configuration file, and setting the protected mode option to
  'no', and then restarting the server.

3) If you started the server manually just for testing, restart it
  with the '--protected-mode no' option.

4) Setup a bind address or an authentication password. NOTE: You only
  need to do one of the above things in order for the server to start
  accepting connections from the outside.

ContentLicense: CC BY-SA 3.0


问:
Remote server not sending response headers, local server does
I have a php file that should be sending response headers, but it isn't. Here is the networking tab of both the local server and the remote server. As you can see, the local server is sending many different headers, but the remote server isn't sending any.

I sent all the response headers using php header(), but since this works perfectly on the local server, im guessing it's a server configuration issue? If anyone has had this issue before, please share an answer - i've been pulling my hair out over this for 3 days now -_-

EDIT thought the php code might help:

```<code><?php
error_reporting(E_ALL);
//disable browser caching !!IMPORTANT
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Random");
header("Access-Control-Expose-Headers: Random");
header("Access-Control-Request-Headers: Random");
</code>```

theres no whitespace before this php code. Also if there was an issue with this code, surely it wouldnt work on my local server?

Thanks,
Josh

答:
Same problem is here;</p>

```<code>Try to use ob_start(); just after <?php and use ob_end_flush(); at the end of your document.
</code>```

Body:
I have a php file that should be sending response headers, but it isn't. Here is the networking tab of both the local server and the remote server. As you can see, the local server is sending many different headers, but the remote server isn't sending any.

I sent all the response headers using php header(), but since this works perfectly on the local server, im guessing it's a server configuration issue? If anyone has had this issue before, please share an answer - i've been pulling my hair out over this for 3 days now -_-

EDIT thought the php code might help:

<?php
error_reporting(E_ALL);
//disable browser caching !!IMPORTANT
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Random");
header("Access-Control-Expose-Headers: Random");
header("Access-Control-Request-Headers: Random");

theres no whitespace before this php code. Also if there was an issue with this code, surely it wouldnt work on my local server?

Thanks,
Josh

Body:
Same problem is here;

Try to use ob_start(); just after <?php and use ob_end_flush(); at the end of your document.


问:
Spring Boot, static resources and mime type configuration
I'm facing a Spring Boot configuration issue I can't deal with...
I'm trying to build an HelloWorld example for HbbTV with Spring Boot, so I need to serve my "index.html" page with mime-type="application/vnd.hbbtv.xhtml+xml"

my index.html will be accessed as a static page, for instance http://myserver.com/index.html?param=value.

with the following code, no matter how hard I try, I get a text/html content type.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//HbbTV//1.1.1//EN" "http://www.hbbtv.org/dtd/HbbTV-1.1.1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>MyApp HBBTV</title>
    <meta http-equiv="content-type" content="Content-Type: application/vnd.hbbtv.xhtml+xml; charset=UTF-8" />
</head>
<body>
...
</body>
</html>
</code>```

So I tried to add a "home()" endpoint into a @Controller to force the correct mime-type, and that works.

```<code>@RestController
public class HbbTVController {

    @RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
    String home() {
        return "someText";
    }
...
}
</code>```

"That works" mean the jetty server serves me a html file with the correct content-type containing the test someText.

My next try were to replace the @RestController by @Controller (same produce config), and replace "someText" by index.html

```<code>@Controller
public class HbbTVController {

    @RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
    String home() {
        return "index.html";
    }
...
}
</code>```

Well, it serves my index.html correctly, but the Content-Type is wrong : text/html instead of application/vnd.hbbtv.xhtml+xml.
Furthermore, I don't want to access to myserver.com/hbbtv to get index.html, but directly to myserver.com/index.html.

How could I do that ?

Thanks...

答:
Well, finally, I found the "Spring boot compliant solution". It's the same as Jamie Birch suggested, but realized with Spring mechanisms.

Spring Boot 1:

```<code>@Configuration
public class HbbtvMimeMapping implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        container.setMimeMappings(mappings);
    }

}
</code>```

Spring Boot 2:

```<code>@Configuration
public class HbbtvMimeMapping implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        factory.setMimeMappings(mappings);
    }
}
</code>```

Body:
I'm facing a Spring Boot configuration issue I can't deal with...
I'm trying to build an HelloWorld example for HbbTV with Spring Boot, so I need to serve my "index.html" page with mime-type="application/vnd.hbbtv.xhtml+xml"

my index.html will be accessed as a static page, for instance http://myserver.com/index.html?param=value.

with the following code, no matter how hard I try, I get a text/html content type.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//HbbTV//1.1.1//EN" "http://www.hbbtv.org/dtd/HbbTV-1.1.1.dtd">

    <title>MyApp HBBTV</title>
    <meta http-equiv="content-type" content="Content-Type: application/vnd.hbbtv.xhtml+xml; charset=UTF-8" />

...

So I tried to add a "home()" endpoint into a @Controller to force the correct mime-type, and that works.

@RestController
public class HbbTVController {

    @RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
    String home() {
        return "someText";
    }
...
}

"That works" mean the jetty server serves me a html file with the correct content-type containing the test someText.

My next try were to replace the @RestController by @Controller (same produce config), and replace "someText" by index.html

@Controller
public class HbbTVController {

    @RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
    String home() {
        return "index.html";
    }
...
}

Well, it serves my index.html correctly, but the Content-Type is wrong : text/html instead of application/vnd.hbbtv.xhtml+xml.
Furthermore, I don't want to access to myserver.com/hbbtv to get index.html, but directly to myserver.com/index.html.

How could I do that ?

Thanks...

Body:
Well, finally, I found the "Spring boot compliant solution". It's the same as Jamie Birch suggested, but realized with Spring mechanisms.

Spring Boot 1:

@Configuration
public class HbbtvMimeMapping implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        container.setMimeMappings(mappings);
    }

}

Spring Boot 2:

@Configuration
public class HbbtvMimeMapping implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
        factory.setMimeMappings(mappings);
    }
}


问:
.net SQL Server stored procs wrapper class structure
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

```<code>void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}
</code>```

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

答: The Microsoft Enterprise Library Data Access Application Block can help to reduce redundant code like that, if you're sticking to pure ADO.NET for your data layer. See http://msdn.microsoft.com/en-us/library/ff664408(v=PandP.50).aspx. There are lots of code samples online and in the download as well, i.e. http://msdn.microsoft.com/en-us/library/ff664702(v=PandP.50).aspx. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?


问:
MethodError: no method matching reduce_sum(::TensorFlow.Tensor{Float32}; reduction_indices=[2])
I am learning TensorFlow from the example at: MNIST Tutorial - Julia.jl

unlike their tutorial, I am using my own custom images(32 X 32 (RGB) ) format asimular to cifar-10. Each row in the csv is 3073 columns the last one being the label. And I have 300 rows out of which I used array slicing to select the first 240 rows for training and the remaining for testing.
So in a nut shell I have 4 arrays:
images_train = 240 X 3072 labels_train = 240 X 1 images_test = 60 X 3072 labels_test = 60 X 1
Below is the error:
THE ERROR

The code:

```<code>using TensorFlow
using Distributions
include("loader.jl")
session = Session(Graph())
function weight_variable(shape)
    initial = map(Float32, rand(Normal(0, .001), shape...))
    return Variable(initial)
end

function bias_variable(shape)
    initial = fill(Float32(.1), shape...)
    return Variable(initial)
end

function conv2d(x, W)
    nn.conv2d(x, W, [1, 1, 1, 1], "SAME")
end

function max_pool_2x2(x)
    nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], "SAME")
end

x = placeholder(Float32)
y_ = placeholder(Float32)

W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])

x_image = reshape(x, [-1, 32, 32, 3])

h_conv1 = nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = reshape(h_pool2, [-1, 7*7*64])
h_fc1 = nn.relu(h_pool2_flat * W_fc1 + b_fc1)

keep_prob = placeholder(Float32)
h_fc1_drop = nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 9])
b_fc2 = bias_variable([9])

y_conv = nn.softmax(h_fc1_drop * W_fc2 + b_fc2)

cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), reduction_indices=[2]))

train_step = train.minimize(train.AdamOptimizer(1e-4), cross_entropy)

correct_prediction = indmax(y_conv, 2) .== indmax(y_, 2)

accuracy = reduce_mean(cast(correct_prediction, Float32))

run(session, initialize_all_variables())

for i in 1:40
    images_train,labels_train = next_batch(16) # randomly generate batches from training dataset
    if i%4 == 1
        train_accuracy = run(session, accuracy, Dict(x=>images_train, y_=>labels_train, keep_prob=>1.0))
        info("step $i, training accuracy $train_accuracy")
    end
    run(session, train_step, Dict(x=>images_train, y_=>labels_train, keep_prob=>.5))
end

images_test, labels_test = load_test_set() # 60 X 3072, 60 X 1 Arrays

test_accuracy = run(session, accuracy, Dict(x=>images_test, y_=>labels_test, keep_prob=>1.0))
info("test accuracy $test_accuracy")
</code>```

Thank you

答:
There is no argument reduction_indices in reduce_sum you should change it to axis, like:

```<code>cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), axis=[2]))
</code>```

Body:
I am learning TensorFlow from the example at: MNIST Tutorial - Julia.jl

unlike their tutorial, I am using my own custom images(32 X 32 (RGB) ) format asimular to cifar-10. Each row in the csv is 3073 columns the last one being the label. And I have 300 rows out of which I used array slicing to select the first 240 rows for training and the remaining for testing.
So in a nut shell I have 4 arrays:
images_train = 240 X 3072 labels_train = 240 X 1 images_test = 60 X 3072 labels_test = 60 X 1
Below is the error:
THE ERROR

The code:

using TensorFlow
using Distributions
include("loader.jl")
session = Session(Graph())
function weight_variable(shape)
    initial = map(Float32, rand(Normal(0, .001), shape...))
    return Variable(initial)
end

function bias_variable(shape)
    initial = fill(Float32(.1), shape...)
    return Variable(initial)
end

function conv2d(x, W)
    nn.conv2d(x, W, [1, 1, 1, 1], "SAME")
end

function max_pool_2x2(x)
    nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], "SAME")
end

x = placeholder(Float32)
y_ = placeholder(Float32)

W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])

x_image = reshape(x, [-1, 32, 32, 3])

h_conv1 = nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = reshape(h_pool2, [-1, 7*7*64])
h_fc1 = nn.relu(h_pool2_flat * W_fc1 + b_fc1)

keep_prob = placeholder(Float32)
h_fc1_drop = nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 9])
b_fc2 = bias_variable([9])

y_conv = nn.softmax(h_fc1_drop * W_fc2 + b_fc2)

cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), reduction_indices=[2]))

train_step = train.minimize(train.AdamOptimizer(1e-4), cross_entropy)

correct_prediction = indmax(y_conv, 2) .== indmax(y_, 2)

accuracy = reduce_mean(cast(correct_prediction, Float32))

run(session, initialize_all_variables())

for i in 1:40
    images_train,labels_train = next_batch(16) # randomly generate batches from training dataset
    if i%4 == 1
        train_accuracy = run(session, accuracy, Dict(x=>images_train, y_=>labels_train, keep_prob=>1.0))
        info("step $i, training accuracy $train_accuracy")
    end
    run(session, train_step, Dict(x=>images_train, y_=>labels_train, keep_prob=>.5))
end

images_test, labels_test = load_test_set() # 60 X 3072, 60 X 1 Arrays

test_accuracy = run(session, accuracy, Dict(x=>images_test, y_=>labels_test, keep_prob=>1.0))
info("test accuracy $test_accuracy")

Thank you

Body:
There is no argument reduction_indices in reduce_sum you should change it to axis, like:

cross_entropy = reduce_mean(-reduce_sum((y_ .* log(y_conv)), axis=[2]))


问:
Run Function in Laravel after a certain time and show this time as a countdown
So I have a function and I want this function to run after(like 10 min) user selects it. While timer(10 min) is counting down to run this function, I want timer to be shown to user in a spesific view. I have all functions and views set up for this aim just I dont know how to put timer and show it to user.

https://www.w3schools.com/howto/howto_js_countdown.asp

I checked this but I cant properly put PHP values into Javascript so I cant make it. I also thought about cron jobs but I am not sure how I can do it there.

1) I want a function to run after a spesific time.

2) Additionally I would really like to show this time as a countdown to user.

答:
If you want function that will run after certain time at serverside - check laravel.com/docs/5.5/scheduling. It's really easy to setup.

You can create Laravel's with your function that will repeat every ten minutes or whatever you want. That job would get date from database and check if function should be executed - if so, mark database record with date as executed and call your function.

For timer, in my opinion best approach is to make AJAX call to some API which would return your date for timer, then all need to be done is assign it to a javascript's variable.
Another way is to render view template also with date, make it invisible with CSS display: none and then retrieve it from DOM for your JS timer.

You would need make some changes to timer at w3schools. Add some conditionals to check how much time left, and if it's =< 10 minutes, append timer to the DOM.


问:
Why should I NOT use the /optimize switch to compile my C# code?
In Visual Studio 2008 there is an option "Optimize Code" that probably corresponds to the /optimize option. It is never enabled, not even when in "Release" mode.

Why should I not want this option to be enabled at all times?

答:
Code optimisation has gotten pretty good in C#3 - it does lots of clever performance tweaks that change your code quite a lot more in the IL than you might expect.

Some obfuscation tools (and some other IL tools like ILMerge) can sometimes break the assembly with optimisation on. The more IL tools you use the more likely you are to get serious issues with optimisation.

Also as @Brian Rasmussen already said (+1) - you want it off for debugging, on for releases.

OwnerDisplayName: boris callens

OwnerDisplayName: Keith


问:
Is reference lost?
First a bit of code:

var mc:MovieClip = new MovieClip();
mc.graphics.lineStyle(2, 0x000000);
mc.graphics.beginFill(0xFF00000)
mc.graphics.drawRect(10, 10, 100, 100);
var array:Array = [mc];

this.addChild(array[0]);

mc = new MovieClip();

this.removeChild(array[0]);
this.addChild(array[0]);

I would expect it to update reference held in array and add empty MovieClip to the stage. Is that wrong assumption then?

Thanks

答: Yes.  Changing which movie clip mc refers to does not change which movie clip array[0] refers to.  It still refers to the old one.  Instead, change the last line to this.addChild(mc); or add another line which says array[0] = mc; between the removeChild and the addChild which follows it.

Title: Is reference lost?


问:
J2EE - multiple database connections for different databases in JPA
I have an application which uses many databases in different geographical locations. All the databases contains same tables and only the database name is different according to the location. I have to create some statistic and monitoring charts in my application which uses data from each database.

What would be the proper way to create those database connection from a WEB java application with JSF and JPA.

答:
You can define more persistence units in your persistence.xml file:

```<code><persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>

<persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>
</code>```

Now it depend if you are using full application server like TomEE or container (Tomcat).

```<code>@PersistenceContext(unitName = "pu1")
private EntityManager em;

@PersistenceContext(unitName = "pu2")
private EntityManager em2;
</code>```

Otherwise:

```<code> Persistence.createEntityManagerFactory("pu1");
 Persistence.createEntityManagerFactory("pu2");
</code>```

Body:
You can define more persistence units in your persistence.xml file:

<persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>

<persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value=""/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value="/>
</properties>
</persistence-unit>

Now it depend if you are using full application server like TomEE or container (Tomcat).

@PersistenceContext(unitName = "pu1")
private EntityManager em;

@PersistenceContext(unitName = "pu2")
private EntityManager em2;

Otherwise:

 Persistence.createEntityManagerFactory("pu1");
 Persistence.createEntityManagerFactory("pu2");


问:
flex box button element not getting 50% of width

div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <button>Button one</button>
   <button>Button two</button>
</div></code>```

答:
Should be this.

div {
  display: flex;
  border: 1px solid red;
}

div button {
  flex: 0 0 50%;
  border: 1px solid gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <button>Button one</button>
   <button>Button two</button>
</div></code>```

Body:
div{
  display:flex;
  border:1px solid red;
}

div button{
  flex:0 0 1;
  border:1px solid gray;
}

   <button>Button one</button>
   <button>Button two</button>

Body:
Should be this.

div {
  display: flex;
  border: 1px solid red;
}

div button {
  flex: 0 0 50%;
  border: 1px solid gray;
}

<div>
   <button>Button one</button>
   <button>Button two</button>
</div>


问:
Embedding LinkedIn company updates / feeds
We have created a SharePoint 2010 web part where we display our company feed from https://www.linkedin.com/company/"Name of Company"/.

End-users need to login the first time (that is ok). But even though they login using their personal LinkedIn profile, they cannot see our company-feed. Why is that?

If the users are set as LinkedIn Designated Admins they can see the feed, otherwise they cannot.

We are using

```<code><script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: "The key"
lang: da_DK
authorize: true
onLoad: onLinkedInLoad
</script>
</code>```

I hope someone can share their knowledge.

答:
Some light on this issue over here:

As ahmeij said, Linkedin doesnt provide anymore an easy way of embedding your company/personal profile timeline anywhere. However, there is an alternative way of implementing this.

You will make use of the RSS feed of the profile. The url will be something like this:

```<code>https://www.linkedin.com/biz/[PROFILE ID]/feed?start=0&v2=true
</code>```

You can find out the numeric ID in you profile/company page.

Read the full source here: https://www.glintech.com/blog/confluence-embed-linkedin-company-feed.html

Body:
We have created a SharePoint 2010 web part where we display our company feed from https://www.linkedin.com/company/"Name of Company"/.

End-users need to login the first time (that is ok). But even though they login using their personal LinkedIn profile, they cannot see our company-feed. Why is that?

If the users are set as LinkedIn Designated Admins they can see the feed, otherwise they cannot.

We are using

I hope someone can share their knowledge.

Body:
Some light on this issue over here:

As ahmeij said, Linkedin doesnt provide anymore an easy way of embedding your company/personal profile timeline anywhere. However, there is an alternative way of implementing this.

You will make use of the RSS feed of the profile. The url will be something like this:

https://www.linkedin.com/biz/[PROFILE ID]/feed?start=0&v2=true

You can find out the numeric ID in you profile/company page.

Read the full source here: https://www.glintech.com/blog/confluence-embed-linkedin-company-feed.html


问:
Are there any drawback of using output buffer on do_action function?
I have a function where I need to use apply_filter and couple of action in between. Are there any drawbacks of using this approach? Are there alternatives?</p>

```<code>$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    ob_start();
    do_action( 'before_choice', $form_id, $choice );
    $content .= ob_get_clean();

    $content .='<div class="choice-container">'. $choice .'</div>';

    ob_start();
    do_action( 'after_choice', $form_id, $choice );
    $content .= ob_get_clean();

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;
</code>```

答:
I found that a better solution would be to use it like this:</p>

```<code>$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    if ( has_filter( 'wwob_after_product_item_price') ){
        $content .= apply_filters( 'wwob_after_product_item_price', $form_id, $choice );
    }

    $content .='<div class="choice-container">'. $choice .'</div>';

    if ( has_filter( 'after_choice') ){
        $content .= apply_filters( 'after_choice', $form_id, $choice );
    }

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;
</code>```

Body:
I have a function where I need to use apply_filter and couple of action in between. Are there any drawbacks of using this approach? Are there alternatives?

$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    ob_start();
    do_action( 'before_choice', $form_id, $choice );
    $content .= ob_get_clean();

    $content .='
'. $choice .'
';

    ob_start();
    do_action( 'after_choice', $form_id, $choice );
    $content .= ob_get_clean();

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;

Body:
I found that a better solution would be to use it like this:

$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    if ( has_filter( 'wwob_after_product_item_price') ){
        $content .= apply_filters( 'wwob_after_product_item_price', $form_id, $choice );
    }

    $content .='<div class="choice-container">'. $choice .'</div>';

    if ( has_filter( 'after_choice') ){
        $content .= apply_filters( 'after_choice', $form_id, $choice );
    }

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;


问:
print last line from the variable output in python
I am looking to get the last line produced from the line variable

```<code>bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line
</code>```

output i am getting is as follows ..

```<code>-122.1058
-123.1050
-125.10584323
</code>```

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

```<code>bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)
</code>```

this yeilds teh desired as folows..

```<code>bash-4.1$ ./file2_dup.py
-125.10584323
</code>```

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

答:
Edit:

you can use enumerate() to get the lines indexed in a loop:

```<code>with open("file1.txt", "rt") as f:
    lines = f.readlines()
    for line, content in enumerate(lines):
        # apply your logic to line and/or content here
        # by adding ifs to select the lines you want...
        print line, content.strip() # do your thing
</code>```

will output (just to illustrate because I didn't specify any conditions in code above):

```<code>0 -122.1058
1 -123.1050
2 -125.10584323
3
</code>```

or in alternative select your specific line with a condition in a listcomp
by using this code instead:

```<code>with open("file1.txt", "rt") as f:
    lines = f.readlines()
    result = [ content.strip() for line, content in enumerate(lines)
         if line == len(lines) - 2] # creates a list with
                                    # only the last line
    print result[0]
</code>```

that will output:

```<code>-125.10584323
</code>```

Body:
I am looking to get the last line produced from the line variable

bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line

output i am getting is as follows ..

-122.1058
-123.1050
-125.10584323

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)

this yeilds teh desired as folows..

bash-4.1$ ./file2_dup.py
-125.10584323

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

Body:
Edit:

you can use enumerate() to get the lines indexed in a loop:

with open("file1.txt", "rt") as f:
    lines = f.readlines()
    for line, content in enumerate(lines):
        # apply your logic to line and/or content here
        # by adding ifs to select the lines you want...
        print line, content.strip() # do your thing

will output (just to illustrate because I didn't specify any conditions in code above):

0 -122.1058
1 -123.1050
2 -125.10584323
3

or in alternative select your specific line with a condition in a listcomp
by using this code instead:

with open("file1.txt", "rt") as f:
    lines = f.readlines()
    result = [ content.strip() for line, content in enumerate(lines)
         if line == len(lines) - 2] # creates a list with
                                    # only the last line
    print result[0]

that will output:

-125.10584323


问:
Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?
This morning, upon upgrading my Firefox browser to the latest version (from 22 to 23), some of the key aspects of my back office (website) stopped working.

Looking at the Firebug log, the following errors were being reported:

```<code>Blocked loading mixed active content "http://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
Blocked loading mixed active content "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"`
</code>```

among other errors caused by the latter of the two above not being loaded.

What does the above mean and how do I resolve it?

答:
I have facing same problem when my site goes from http to https. We have added rule for all request to redirect http to https.

You needs to add the redirection rule for inter site request, but you have to remove the redirection rule for external js/css.

Body:
This morning, upon upgrading my Firefox browser to the latest version (from 22 to 23), some of the key aspects of my back office (website) stopped working.

Looking at the Firebug log, the following errors were being reported:

Blocked loading mixed active content "http://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
Blocked loading mixed active content "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"`

among other errors caused by the latter of the two above not being loaded.

What does the above mean and how do I resolve it?


问:
Mongoose connect throwing a warning
I am writing a mongodb connected app and while connecting to the server like bellow getting a warning like this:

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

My codes are like bellow

```<code>import mongoose from 'mongoose';
import config from './config';
mongoose.connect(config.db.uri);
</code>```

at config.js

```<code>const config = {
    name: 'API',
    version: '0.0.1',
    env: process.env.NODE_ENV || 'development',
    port: process.env.PORT || 3000,
    base_url: process.env.BASE_URL || 'http://localhost:3000',
    db: {
        uri: 'mongodb://admin:harry123@127.0.0.1:27017/ai?authSource=admin',
    },
}

export default config;
</code>```

I am using Node v8.0.0 and mongoose 4.10.5

答:
```<code>Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
</code>```

Yes, this is a harmless warning and a known mongoose issue. as said by @
Phu Ngo

So, you can get away with this issue by updating to the latest version of mongoose which is above 4.11.1.

After upgrading the version, this warning may appear if you have used options for connections.

```<code>he server/replset/mongos options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,reconnectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,promoteValues,promoteBuffers,promoteLongs,domainsEnabled,keepAliveInitialDelay,checkServerIdentity,validateOptions,appname,auth]
</code>```

According to the error message;

```<code>the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object
</code>```

so, the solution to the problem is simply moving the setting options from the server, replset, socketOptions, mongos and any other hierarchy options up to the top level of the object.

Solution with examples

Title: Mongoose connect throwing a warning

Body:
I am writing a mongodb connected app and while connecting to the server like bellow getting a warning like this:

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

My codes are like bellow

import mongoose from 'mongoose';
import config from './config';
mongoose.connect(config.db.uri);

at config.js

const config = {
    name: 'API',
    version: '0.0.1',
    env: process.env.NODE_ENV || 'development',
    port: process.env.PORT || 3000,
    base_url: process.env.BASE_URL || 'http://localhost:3000',
    db: {
        uri: 'mongodb://admin:harry123@127.0.0.1:27017/ai?authSource=admin',
    },
}

export default config;

I am using Node v8.0.0 and mongoose 4.10.5

Body:
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

Yes, this is a harmless warning and a known mongoose issue. as said by @
Phu Ngo

So, you can get away with this issue by updating to the latest version of mongoose which is above 4.11.1.

After upgrading the version, this warning may appear if you have used options for connections.

he server/replset/mongos options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,reconnectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,promoteValues,promoteBuffers,promoteLongs,domainsEnabled,keepAliveInitialDelay,checkServerIdentity,validateOptions,appname,auth]

According to the error message;

the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object

so, the solution to the problem is simply moving the setting options from the server, replset, socketOptions, mongos and any other hierarchy options up to the top level of the object.

Solution with examples


问:
C#: How to filter/get value of the specific column in html-table with Regex. Get value between two strings
I want to filter these items that contain "941d3c8a-8d5d-42aa-943e-a07ccaba1629" and get the value inside the  of each filtered item. For the first filtered item, the value is "  " and for the second the value is "ROBO7 ".

I used regex in C# like below,but it seemed it can't get the correct value.
Any help is appreciated.

```<code>    Regex regex = new Regex(
      "(<TD[^>]*?>^941d3c8a-8d5d-42aa-943e-a07ccaba1629$<\\/TD>)",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );
MatchCollection ms = regex.Matches(InputText);
int index = 1;
foreach (Match match in ms)
{
 if (match.Groups[2].Value.StartsWith(Search))
   return index;
  index++;
}
return 0;
</code>```

G1S1990706
G1:一般支払
R1:QRなし

RobotAgent1
2017/09/20
ＲＯＢＯ７

2017/11/07

G1S1990716
G1:一般支払
01:スキャン済

RobotAgent2
2017/09/20
ＲＯＢＯ７

2017/11/13
ＲＯＢＯ７

```

答:
The regex you need for that is this

```<code>(?<=941d3c8a-8d5d-42aa-943e-a07ccaba1629">)(.*)(?=<\/TD>)
</code>```

I will post you C# solution in a bit ;) (updating)

if you need to test the Regex do it here to see validity of conditions. It matches everything in between two strings as per your condition.

here is the simple code example (I'm just printing but you can do whatever you like with it)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

namespace test3
{
    class Program
    {

        static void Main(string[] args)
        {

            string createText = System.IO.File.ReadAllText(@"C:\PATH_TO_THE FILE_I_USED\data.txt");

            Regex regex = new Regex("(?<=941d3c8a-8d5d-42aa-943e-a07ccaba1629\" >)(.*)(?=<\\/ TD >)",
                RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
                );

            MatchCollection ms = regex.Matches(createText);

            foreach (Match match in ms)
            {
                Console.WriteLine(match);
            }

            Console.ReadLine();
        }

    }
}
</code>```

Body:
I want to filter these items that contain "941d3c8a-8d5d-42aa-943e-a07ccaba1629" and get the value inside the  of each filtered item. For the first filtered item, the value is "  " and for the second the value is "ROBO7 ".

I used regex in C# like below,but it seemed it can't get the correct value.
Any help is appreciated.

    Regex regex = new Regex(
      "(]*?>^941d3c8a-8d5d-42aa-943e-a07ccaba1629$<\\/TD>)",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );
MatchCollection ms = regex.Matches(InputText);
int index = 1;
foreach (Match match in ms)
{
 if (match.Groups[2].Value.StartsWith(Search))
   return index;
  index++;
}
return 0;

G1S1990706
G1:一般支払
R1:QRなし

RobotAgent1
2017/09/20
ＲＯＢＯ７

2017/11/07

G1S1990716
G1:一般支払
01:スキャン済

RobotAgent2
2017/09/20
ＲＯＢＯ７

2017/11/13
ＲＯＢＯ７

Body:
The regex you need for that is this

(?<=941d3c8a-8d5d-42aa-943e-a07ccaba1629">)(.*)(?=<\/TD>)

I will post you C# solution in a bit ;) (updating)

if you need to test the Regex do it here to see validity of conditions. It matches everything in between two strings as per your condition.

here is the simple code example (I'm just printing but you can do whatever you like with it)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

namespace test3
{
    class Program
    {

        static void Main(string[] args)
        {

            string createText = System.IO.File.ReadAllText(@"C:\PATH_TO_THE FILE_I_USED\data.txt");

            Regex regex = new Regex("(?<=941d3c8a-8d5d-42aa-943e-a07ccaba1629\" >)(.*)(?=<\\/ TD >)",
                RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
                );

            MatchCollection ms = regex.Matches(createText);

            foreach (Match match in ms)
            {
                Console.WriteLine(match);
            }

            Console.ReadLine();
        }

    }
}


问:
Transfer bkpf into tab delimented file in background
I want to extract all bkpf's fields into a tab delimited file in the background.
How can we do it?

Thanks in advance
Elias

PS: The code of the program that the Perform exec_in_bckgr doesn't understand the change of the Checkbox in SUBMIT WITH p_bckgr = space.

```<code>REPORT  zfor_get_bkrf_bseg4.
TABLES: bkpf.
DATA: it_bkpf TYPE STANDARD TABLE OF bkpf,
      ls_bkpf TYPE bkpf,
      i_filename LIKE rlgrap-filename.
FIELD-SYMBOLS: <fs_field>.

SELECTION-SCREEN BEGIN OF BLOCK selection WITH FRAME TITLE text-s01.
SELECT-OPTIONS: so_bukrs FOR bkpf-bukrs,
                so_budat FOR bkpf-budat OBLIGATORY.

SELECTION-SCREEN SKIP 1.
SELECTION-SCREEN ULINE.
PARAMETERS: p_bkgrd AS CHECKBOX USER-COMMAND check DEFAULT 'X'.
" File Path on Application Server or on Local PC according to p_bkgrd
PARAMETERS: p_paths TYPE btcxpgpar DEFAULT '/tmp' MODIF ID sg1.
SELECTION-SCREEN END OF BLOCK selection.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_paths.
  DATA: c_fnh_mask TYPE dxfields-filemask VALUE '*',
        search_dir TYPE dxfields-longpath .

  CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE'
    EXPORTING
      directory        = search_dir
      filemask         = c_fnh_mask
    IMPORTING
      serverfile       = p_paths
    EXCEPTIONS
      canceled_by_user = 1
      OTHERS           = 2.
  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ENDIF.

START-OF-SELECTION.
  IF p_bkgrd = 'X'.
    PERFORM exec_in_bckgr.
  ELSE.
    PERFORM get_data.
    PERFORM download_tables_paths.
  ENDIF.

END-OF-SELECTION.
  WRITE: i_filename , ' is created' .

FORM get_data .

  SELECT * INTO TABLE it_bkpf
    FROM bkpf
    WHERE bukrs IN so_bukrs AND
          budat IN so_budat.

ENDFORM.                    " GET_DATA

FORM download_tables_paths .

  DATA:lv_line(4096) TYPE c,
       lv_field_type(10) TYPE c,
       lv_field_text(10) TYPE c.

  " Build FineName
  CONCATENATE p_paths '/' 'BKPF' sy-datum sy-uzeit '.txt'
                                                  INTO i_filename.
  REPLACE ALL OCCURRENCES OF '//' IN i_filename WITH '/'.

* Process further only if found some data
  IF NOT it_bkpf[] IS INITIAL.
    " Open file for Output
    OPEN DATASET  i_filename  FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
    IF sy-subrc NE 0 .
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
       WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ELSE.
      LOOP AT it_bkpf INTO ls_bkpf.
        DO.
          ASSIGN COMPONENT sy-index OF STRUCTURE ls_bkpf TO <fs_field>.
          IF sy-subrc <> 0.
            EXIT.
          ENDIF.
          IF lv_line IS INITIAL.
            lv_line = <fs_field>.
          ELSE.
            DESCRIBE FIELD <fs_field> TYPE lv_field_type.
            IF lv_field_type = 'P' OR lv_field_type = 'I'.
              lv_field_text = <fs_field>.
              CONDENSE lv_field_text NO-GAPS.
              CONCATENATE lv_line '|' lv_field_text INTO lv_line.
            ELSE.
              CONCATENATE lv_line '|' <fs_field> INTO lv_line.
            ENDIF.
          ENDIF.
        ENDDO.
        TRANSFER lv_line TO i_filename.
        CLEAR: lv_line.
      ENDLOOP.
    ENDIF.

    CLOSE DATASET i_filename.
  ENDIF.
ENDFORM.

FORM exec_in_bckgr .
  DATA: jobname1 TYPE tbtcjob-jobname,
        jobcount1 TYPE tbtcjob-jobcount.

  jobname1 = 'ZFOR_GET_BKRF_BSEG2'.

  CALL FUNCTION 'JOB_OPEN'
    EXPORTING
      jobname          = jobname1
    IMPORTING
      jobcount         = jobcount1
    EXCEPTIONS
      cant_create_job  = 1
      invalid_job_data = 2
      jobname_missing  = 3
      OTHERS           = 4.

  IF sy-subrc NE 0.
    MESSAGE s368(00) WITH 'Error Creating Job'
    sy-subrc.
    EXIT.
  ENDIF.

  SUBMIT zfor_get_bkrf_bseg2
    WITH so_bukrs IN so_bukrs
    WITH so_budat IN so_budat
    WITH p_bckgr = space
    WITH p_paths = p_paths
   VIA JOB jobname1 NUMBER jobcount1
    AND RETURN.

  CALL FUNCTION 'JOB_CLOSE'
    EXPORTING
      jobcount          = jobcount1
      jobname           = jobname1
*      sdlstrtdt         = sdate
*      sdlstrttm         = stime
*      strtimmed         = 'X' " Start immediately
    EXCEPTIONS
      invalid_startdate = 1
      jobname_missing   = 2
      job_close_failed  = 3
      job_nosteps       = 4
      job_notex         = 5
      lock_failed       = 6
      OTHERS            = 7.

  IF sy-subrc > 0.
    MESSAGE s368(00) WITH 'Closing Job Failed'
    sy-subrc.
    EXIT.
  ENDIF.
ENDFORM.
</code>```

The program is too simple and I do not understand why the site is asking me to add more comments.
OK, if I enable the  strtimmed  = 'X'  in CALL FUNCTION 'JOB_CLOSE', then the program is creating jobs continuously and I have to kill it through SM50.
If I disable the STRTIMED then it create a job as SCHEDULE. I run it as Immediate and it creates and run a job without creating a file while in foreground the program is working perfect.

So my question is: Is this code OK for SAP ECC6?

Thanks in advance
Elias

答:
Finally someone told me what was wrong in my code. I missed a D in WITH p_bckgr = space.
I thought that if it is wrong the SAP will display an error, but this was a wrong thought.
So the correct is WITH p_bkgrd = space.

Thanks all

Body:
I want to extract all bkpf's fields into a tab delimited file in the background.
How can we do it?

Thanks in advance
Elias

PS: The code of the program that the Perform exec_in_bckgr doesn't understand the change of the Checkbox in SUBMIT WITH p_bckgr = space.

REPORT  zfor_get_bkrf_bseg4.
TABLES: bkpf.
DATA: it_bkpf TYPE STANDARD TABLE OF bkpf,
      ls_bkpf TYPE bkpf,
      i_filename LIKE rlgrap-filename.
FIELD-SYMBOLS: <fs_field>.

SELECTION-SCREEN BEGIN OF BLOCK selection WITH FRAME TITLE text-s01.
SELECT-OPTIONS: so_bukrs FOR bkpf-bukrs,
                so_budat FOR bkpf-budat OBLIGATORY.

SELECTION-SCREEN SKIP 1.
SELECTION-SCREEN ULINE.
PARAMETERS: p_bkgrd AS CHECKBOX USER-COMMAND check DEFAULT 'X'.
" File Path on Application Server or on Local PC according to p_bkgrd
PARAMETERS: p_paths TYPE btcxpgpar DEFAULT '/tmp' MODIF ID sg1.
SELECTION-SCREEN END OF BLOCK selection.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_paths.
  DATA: c_fnh_mask TYPE dxfields-filemask VALUE '*',
        search_dir TYPE dxfields-longpath .

  CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE'
    EXPORTING
      directory        = search_dir
      filemask         = c_fnh_mask
    IMPORTING
      serverfile       = p_paths
    EXCEPTIONS
      canceled_by_user = 1
      OTHERS           = 2.
  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ENDIF.

START-OF-SELECTION.
  IF p_bkgrd = 'X'.
    PERFORM exec_in_bckgr.
  ELSE.
    PERFORM get_data.
    PERFORM download_tables_paths.
  ENDIF.

END-OF-SELECTION.
  WRITE: i_filename , ' is created' .

FORM get_data .

  SELECT * INTO TABLE it_bkpf
    FROM bkpf
    WHERE bukrs IN so_bukrs AND
          budat IN so_budat.

ENDFORM.                    " GET_DATA

FORM download_tables_paths .

  DATA:lv_line(4096) TYPE c,
       lv_field_type(10) TYPE c,
       lv_field_text(10) TYPE c.

  " Build FineName
  CONCATENATE p_paths '/' 'BKPF' sy-datum sy-uzeit '.txt'
                                                  INTO i_filename.
  REPLACE ALL OCCURRENCES OF '//' IN i_filename WITH '/'.

* Process further only if found some data
  IF NOT it_bkpf[] IS INITIAL.
    " Open file for Output
    OPEN DATASET  i_filename  FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
    IF sy-subrc NE 0 .
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
       WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ELSE.
      LOOP AT it_bkpf INTO ls_bkpf.
        DO.
          ASSIGN COMPONENT sy-index OF STRUCTURE ls_bkpf TO <fs_field>.
          IF sy-subrc <> 0.
            EXIT.
          ENDIF.
          IF lv_line IS INITIAL.
            lv_line = <fs_field>.
          ELSE.
            DESCRIBE FIELD <fs_field> TYPE lv_field_type.
            IF lv_field_type = 'P' OR lv_field_type = 'I'.
              lv_field_text = <fs_field>.
              CONDENSE lv_field_text NO-GAPS.
              CONCATENATE lv_line '|' lv_field_text INTO lv_line.
            ELSE.
              CONCATENATE lv_line '|' <fs_field> INTO lv_line.
            ENDIF.
          ENDIF.
        ENDDO.
        TRANSFER lv_line TO i_filename.
        CLEAR: lv_line.
      ENDLOOP.
    ENDIF.

    CLOSE DATASET i_filename.
  ENDIF.
ENDFORM.

FORM exec_in_bckgr .
  DATA: jobname1 TYPE tbtcjob-jobname,
        jobcount1 TYPE tbtcjob-jobcount.

  jobname1 = 'ZFOR_GET_BKRF_BSEG2'.

  CALL FUNCTION 'JOB_OPEN'
    EXPORTING
      jobname          = jobname1
    IMPORTING
      jobcount         = jobcount1
    EXCEPTIONS
      cant_create_job  = 1
      invalid_job_data = 2
      jobname_missing  = 3
      OTHERS           = 4.

  IF sy-subrc NE 0.
    MESSAGE s368(00) WITH 'Error Creating Job'
    sy-subrc.
    EXIT.
  ENDIF.

  SUBMIT zfor_get_bkrf_bseg2
    WITH so_bukrs IN so_bukrs
    WITH so_budat IN so_budat
    WITH p_bckgr = space
    WITH p_paths = p_paths
   VIA JOB jobname1 NUMBER jobcount1
    AND RETURN.

  CALL FUNCTION 'JOB_CLOSE'
    EXPORTING
      jobcount          = jobcount1
      jobname           = jobname1
*      sdlstrtdt         = sdate
*      sdlstrttm         = stime
*      strtimmed         = 'X' " Start immediately
    EXCEPTIONS
      invalid_startdate = 1
      jobname_missing   = 2
      job_close_failed  = 3
      job_nosteps       = 4
      job_notex         = 5
      lock_failed       = 6
      OTHERS            = 7.

  IF sy-subrc > 0.
    MESSAGE s368(00) WITH 'Closing Job Failed'
    sy-subrc.
    EXIT.
  ENDIF.
ENDFORM.

The program is too simple and I do not understand why the site is asking me to add more comments.
OK, if I enable the  strtimmed  = 'X'  in CALL FUNCTION 'JOB_CLOSE', then the program is creating jobs continuously and I have to kill it through SM50.
If I disable the STRTIMED then it create a job as SCHEDULE. I run it as Immediate and it creates and run a job without creating a file while in foreground the program is working perfect.

So my question is: Is this code OK for SAP ECC6?

Thanks in advance
Elias


问:
Dependency Injection in WPF and Asp.Net Core
I am using Asp.Net Core to write API Layer for one of my legacy application developed using WPF (.Net Framework 4.5). I have used https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/ in Business layer which I want to access from WPF application. The version of this DI is not supported by .Net Framework 4.5 so I am unable to use it from WPF. Any suggestions how should I go with this ? The other approach is to use anyother DI container supported by .Net framework 4.5 and Asp.Net Core</p>

答: I have upgraded my WPF project to .Net Framework 4.6 and rest of the layers are created using .Net Standard Library 2.0.</p>


问:
Fill first available column based on a string in R
Happy Monday -

I've used grep to create df2, subsetting df1 to return only those rows with a specific string.

What I'm after is a way to fill only the first available column (from A, B or C) with the value from the string (in this case 3).

```<code>df2 <- df1[grep("DW 3*", df1$D), ]
</code>```

df2:

```<code>ID A B C D
1  3 3   DW 3*
2  4     DW 3*
3  4 3   DW 3*
4  3     DW 3*
</code>```

So I end up with

```<code>ID A B C  D
 1  3 3 3  DW 3*
 2  4 3    DW 3*
 3  4 3 3  DW 3*
 4  3 3    DW 3*
</code>```

I hope that is clear - feel free to ask for clarification, and thanks in advance.

答:
You can use a for loop to find the first NA value and then replace it with the value you require:

(I couldn't work out where you're getting your value from, so I just hard coded 3 as the replacement value)

Set up data:

```<code>df2 = data.frame(ID=c(1,2,3,4),A=c(3,4,4,3), B=c(3,NA,NA,3),C= c(NA,NA,NA,NA),
D=rep("DW 3*",4))
</code>```

For loop, checking for which rows are NA, and selecting that column name to then be used for replacement:

```<code>for(i in 1:nrow(df2)){
  df2[i,colnames(df2)[which(is.na(df2[i,]))][1]]=3
  }
</code>```

Body:
Happy Monday -

I've used grep to create df2, subsetting df1 to return only those rows with a specific string.

What I'm after is a way to fill only the first available column (from A, B or C) with the value from the string (in this case 3).

df2 <- df1[grep("DW 3*", df1$D), ]

df2:

ID A B C D
1  3 3   DW 3*
2  4     DW 3*
3  4 3   DW 3*
4  3     DW 3*

So I end up with

ID A B C  D
 1  3 3 3  DW 3*
 2  4 3    DW 3*
 3  4 3 3  DW 3*
 4  3 3    DW 3*

I hope that is clear - feel free to ask for clarification, and thanks in advance.

Body:
You can use a for loop to find the first NA value and then replace it with the value you require:

(I couldn't work out where you're getting your value from, so I just hard coded 3 as the replacement value)

Set up data:

df2 = data.frame(ID=c(1,2,3,4),A=c(3,4,4,3), B=c(3,NA,NA,3),C= c(NA,NA,NA,NA),
D=rep("DW 3*",4))

For loop, checking for which rows are NA, and selecting that column name to then be used for replacement:

for(i in 1:nrow(df2)){
  df2[i,colnames(df2)[which(is.na(df2[i,]))][1]]=3
  }


问:
MariaDB server version for the right syntax to use near '' at line 9 You have an error in your SQL syntax
Help me to solve this.

500 - An error has occurred.

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 9 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY a.id desc LIMIT 20' at line 11 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 9

答:
You should provide us text version of SQL query so that we can help you.

But i think your query has syntax error before "ORDER BY"


问:
Is it possible to have a QWidget without a display?
I have a console-only win32 application (which can be launched as a windows service) where I want to create QWidget objects and interact with them.

These QWidget will not be rendered locally (because there is no display) but I need to access painting operations (to create screenshot of them for example) and I need to intercept mouse and keyboard operations.

The aim of the service is to provide a display of the widget to a remote application. So the image, mouse and keyboard are meant to be redirected over the network.

Is it possible to have QWidget objects in a console application? What is the preferred method to intercept painting, mouse and keyboard operations in that case?

If this is possible, is it still possible with QAxWidget objects?

答:
Have a peek at Qt for embedded Linux.. Qt is designed so you can do this, but it is non-trivial.

I do suspect you're not on the right track, though, if you have a console-mode service that needs a keyboard, mouse and a graphical UI. The need to interact with a user tells me that it should not be a service, and the need for a mouse suggests that it shouldn't be a console app either.


问:
Cannot remove OneNote from Greenshot
Something pretty strange is happening.

In %appdata%\greenshot\Greenshot.ini

I have :

```<code>ExcludeDestinations=OneNote
</code>```

and OneNote still shows on the list?

I also tried with a
 C:\Program Files\Greenshot\greenshot-fixed.ini

containing this line, nothing works. OneNote always shows. It's crucial for me to disable it since it doesn't work at the moment even with latest Greenshot release (1.2.9.129 or new 1.2.10.3-RC1)

If i add for example :

```<code>ExcludeDestinations=OneNote,Outlook,Word
</code>```

Outlook and Word disappear from the destination list but OneNote still shows...however i'm clearly using the proper name as listed here :

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/

Thank you for you time!

答:
To remove the OneNote I can recommend excluding plugins as well.
Just came across the same issue and this line solved my problem:

```<code>ExcludePlugins=Office Plugin
</code>```

You can try as well other plugins that are listed in the link you found as well:

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/

Title: Cannot remove OneNote from Greenshot

Body:
Something pretty strange is happening.

In %appdata%\greenshot\Greenshot.ini

I have :

ExcludeDestinations=OneNote

and OneNote still shows on the list?

I also tried with a
 C:\Program Files\Greenshot\greenshot-fixed.ini

containing this line, nothing works. OneNote always shows. It's crucial for me to disable it since it doesn't work at the moment even with latest Greenshot release (1.2.9.129 or new 1.2.10.3-RC1)

If i add for example :

ExcludeDestinations=OneNote,Outlook,Word

Outlook and Word disappear from the destination list but OneNote still shows...however i'm clearly using the proper name as listed here :

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/

Thank you for you time!

Body:
To remove the OneNote I can recommend excluding plugins as well.
Just came across the same issue and this line solved my problem:

ExcludePlugins=Office Plugin

You can try as well other plugins that are listed in the link you found as well:

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/


问:
how to update the number component in a list of strings
I have a list:

```<code>['a1', 'a2', 'a3']
</code>```

I want to update it so that each number component is incremented by 1:

```<code>['a2', 'a3', 'a4']
</code>```

What would be the most efficient way to do it?

答:
I think your best bet would be to use a '2d-list' (I don't know if this is the correct term in Python):

```<code>myList = [['a',1],['a',2],['a',3]...]
</code>```

you would print the elements with print(myList[n][0] + str(myList[n][1])) where n = the element you want to print. To increment the 'number component' you would use myList[n][1] += 1 if you want to increment it by 1.

Body:
I have a list:

['a1', 'a2', 'a3']

I want to update it so that each number component is incremented by 1:

['a2', 'a3', 'a4']

What would be the most efficient way to do it?

Body:
I think your best bet would be to use a '2d-list' (I don't know if this is the correct term in Python):

myList = [['a',1],['a',2],['a',3]...]

you would print the elements with print(myList[n][0] + str(myList[n][1])) where n = the element you want to print. To increment the 'number component' you would use myList[n][1] += 1 if you want to increment it by 1.


问:
6 decimal places being rounded up to 4 in MS-Access
I've got a textbox which allows the user to enter up to 6 decimal places. This is working, however, when saving (code below), the value is rounded up to 4 decimal places instead and this is how it is saved.

```<code>sqlupdate = "UPDATE [Products] SET [Product_Description] = @desc , " & _
            "[Unit_Type] = @ut , " & _
            "[RegularPrice] = @pr, " & _
            "[Product_Category_ID] = @catid, " & _
            "[CostPrice] = @costpc, " & _
            "[defVol] = @defvol, [size] = @size " & _
             "WHERE [Base_Code] = @basecode"

 cmd = New OleDbCommand(sqlupdate, con, trans)

 Dim decSize As Decimal = Convert.ToDecimal(txt_size.Text)

 cmd.Parameters.AddWithValue("@catid", categoryID)
 cmd.Parameters.AddWithValue("@costpc", costPc)
 cmd.Parameters.AddWithValue("@defvol", volume)
 cmd.Parameters.Add("@size", OleDbType.Decimal).Value = decSize
 cmd.Parameters.AddWithValue("@basecode", txtCode.Text)
</code>```

I've even tried setting the database field to 6 decimal places, but it's not worked. I'm working with Access 1997.

Also, the database is already in a live environment, so if a database change is required, it needs to be done programatically, rather than by going into the database.

These are the field types I'm able to set it to in the database.

答:
The data type of that field seems to be Currency, as it is the only data type of the JET database V3.5 (that used by Access 97) that will round to four decimals.

So double-check the table's field type.

Body:
I've got a textbox which allows the user to enter up to 6 decimal places. This is working, however, when saving (code below), the value is rounded up to 4 decimal places instead and this is how it is saved.

sqlupdate = "UPDATE [Products] SET [Product_Description] = @desc , " & _
            "[Unit_Type] = @ut , " & _
            "[RegularPrice] = @pr, " & _
            "[Product_Category_ID] = @catid, " & _
            "[CostPrice] = @costpc, " & _
            "[defVol] = @defvol, [size] = @size " & _
             "WHERE [Base_Code] = @basecode"

 cmd = New OleDbCommand(sqlupdate, con, trans)

 Dim decSize As Decimal = Convert.ToDecimal(txt_size.Text)

 cmd.Parameters.AddWithValue("@catid", categoryID)
 cmd.Parameters.AddWithValue("@costpc", costPc)
 cmd.Parameters.AddWithValue("@defvol", volume)
 cmd.Parameters.Add("@size", OleDbType.Decimal).Value = decSize
 cmd.Parameters.AddWithValue("@basecode", txtCode.Text)

I've even tried setting the database field to 6 decimal places, but it's not worked. I'm working with Access 1997.

Also, the database is already in a live environment, so if a database change is required, it needs to be done programatically, rather than by going into the database.

These are the field types I'm able to set it to in the database.


问:
babel-polyfill vs babel-plugins
I am a bit lost in the Babel options / config. I want to use recent js features and compile (with webpack) to browser code.

What is the difference between babel-polyfill and babel plugins with babel-preset-env?

Are they intended to work together?

答:
babel-preset-env is a Babel preset meant to automatically set up babel plugins and include the necessary babel polyfills based on a set of target environments checked against a feature compatibility table.

In order to make a fully working ES2015+ environment run on a non-ES2015+ client, simple code transpilation is sometimes not enough:

ES generators are enabled using regenerator library (provided by babel-polyfill)

Missing ES2015+ methods (like Promise, Map, Object.assign...) are polyfilled with core-js (provided by babel-polyfill, too)

Any other transpilable feature is generated by standard babel plugins, often used trough pre-configured babel-presets

So, back to your question, it's babel-preset-env that makes use of babel-polyfill and babel plugins.

Title: babel-polyfill vs babel-plugins


问:
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

```<code>$ myapp -n 3,4,5,6
</code>```

or

```<code>$ myapp -n 3-6
</code>```

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

```<code>$ myapp -n 22-27, 51-64
</code>```

答:
You can define your argument and use optparse callback to process your input before saving it :

```<code>from optparse import OptionParser

parser = OptionParser()

def create_range_callback(option, opt, value, parser):
    i, j = map(int, value.split('-'))
    setattr(parser.values, option.dest, range(i, j+1))

parser.add_option("-r", "--range", action="callback",
                  callback=create_range_callback,
                  type="string", dest='list')

(options, args) = parser.parse_args()

print options.list
</code>```

doing now :

```<code>python2.7 test.py -r 1-5
</code>```

Output:

```<code>[1, 2, 3, 4, 5]
</code>```

Title: Parsing command line input for numbers

Body:
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64

Body:
You can define your argument and use optparse callback to process your input before saving it :

from optparse import OptionParser

parser = OptionParser()

def create_range_callback(option, opt, value, parser):
    i, j = map(int, value.split('-'))
    setattr(parser.values, option.dest, range(i, j+1))

parser.add_option("-r", "--range", action="callback",
                  callback=create_range_callback,
                  type="string", dest='list')

(options, args) = parser.parse_args()

print options.list

doing now :

python2.7 test.py -r 1-5

Output:

[1, 2, 3, 4, 5]


问:
How to create a partition without Windows assigning a drive letter?
I am trying to initialize and partition an attached virtual hard disk through the Windows API. I have been successful using DeviceIoControl() to do so, however whenever I apply the desired drive layout Windows is automatically assigning a drive letter to the partition and popping up an annoying "Would you like to format?" dialog.

My intent is to handle the formatting and mounting of this partition later in the program, but I'm not sure how to stop this behavior. I have tried setting RecognizedPartition to FALSE, but this seems to have no effect.

Relevant code:

```<code>Layout.PartitionStyle = PARTITION_STYLE_MBR;
Layout.PartitionCount = 4;
Layout.Mbr.Signature = MY_DISK_MBR_SIGNATURE;
Layout.PartitionEntry[0].PartitionStyle = PARTITION_STYLE_MBR;
Layout.PartitionEntry[0].PartitionNumber = 1;
Layout.PartitionEntry[0].StartingOffset.QuadPart = MY_DISK_OFFSET;
Layout.PartitionEntry[0].PartitionLength.QuadPart =
   (Geom.DiskSize.QuadPart - MY_DISK_OFFSET);
Layout.PartitionEntry[0].Mbr.PartitionType = PARTITION_IFS;
Layout.PartitionEntry[0].Mbr.BootIndicator = FALSE;
Layout.PartitionEntry[0].Mbr.RecognizedPartition = FALSE;
Layout.PartitionEntry[0].Mbr.HiddenSectors =
   (MY_DISK_OFFSET / Geom.Geometry.BytesPerSector);

for (int i = 0; i < 4; i++)
{
    Layout.PartitionEntry[i].RewritePartition = TRUE;
}

if (!DeviceIoControl(hDisk, IOCTL_DISK_SET_DRIVE_LAYOUT_EX,
                     Layout, dwLayoutSz, NULL, 0, &dwReturn, NULL))
{
    // Handle error
}
DeviceIoControl(hDisk, IOCTL_DISK_UPDATE_PROPERTIES,
                NULL, 0, NULL, 0, &dwReturn, NULL);
</code>```

What can I do to prevent automatic drive letter assignment?

答:
Rufus has an interesting workaround: it installs a window event hook that detects the "do you want to format this drive?" prompts and immediately closes them. See source code here.

It then goes on to arrange to mount only the partitions it cares about, but that's orthogonal.

Body:
I am trying to initialize and partition an attached virtual hard disk through the Windows API. I have been successful using DeviceIoControl() to do so, however whenever I apply the desired drive layout Windows is automatically assigning a drive letter to the partition and popping up an annoying "Would you like to format?" dialog.

My intent is to handle the formatting and mounting of this partition later in the program, but I'm not sure how to stop this behavior. I have tried setting RecognizedPartition to FALSE, but this seems to have no effect.

Relevant code:

Layout.PartitionStyle = PARTITION_STYLE_MBR;
Layout.PartitionCount = 4;
Layout.Mbr.Signature = MY_DISK_MBR_SIGNATURE;
Layout.PartitionEntry[0].PartitionStyle = PARTITION_STYLE_MBR;
Layout.PartitionEntry[0].PartitionNumber = 1;
Layout.PartitionEntry[0].StartingOffset.QuadPart = MY_DISK_OFFSET;
Layout.PartitionEntry[0].PartitionLength.QuadPart =
   (Geom.DiskSize.QuadPart - MY_DISK_OFFSET);
Layout.PartitionEntry[0].Mbr.PartitionType = PARTITION_IFS;
Layout.PartitionEntry[0].Mbr.BootIndicator = FALSE;
Layout.PartitionEntry[0].Mbr.RecognizedPartition = FALSE;
Layout.PartitionEntry[0].Mbr.HiddenSectors =
   (MY_DISK_OFFSET / Geom.Geometry.BytesPerSector);

for (int i = 0; i < 4; i++)
{
    Layout.PartitionEntry[i].RewritePartition = TRUE;
}

if (!DeviceIoControl(hDisk, IOCTL_DISK_SET_DRIVE_LAYOUT_EX,
                     Layout, dwLayoutSz, NULL, 0, &dwReturn, NULL))
{
    // Handle error
}
DeviceIoControl(hDisk, IOCTL_DISK_UPDATE_PROPERTIES,
                NULL, 0, NULL, 0, &dwReturn, NULL);

What can I do to prevent automatic drive letter assignment?


问:
Auto Format Phone Number in Jquery
I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.

I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.

```<code>$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    while (val.length > 3) {
      newVal += val.substr(0, 3) + '-';
      val = val.substr(3);
    }
    newVal += val;
    this.value = newVal;
});
</code>```

http://jsfiddle.net/ssthil/nY2QT/

答:
$('#ssn').keyup(function() {
        var val = this.value.replace(/\D/g, '');
        var newVal = '';
        for(i=0;i<2;i++){
         if (val.length > 3) {
          newVal += val.substr(0, 3) + '-';
          val = val.substr(3);
        }
        }
        newVal += val;
        this.value = newVal;
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ssn" maxlength="10"/></code>```

Title: Auto Format Phone Number in Jquery

Body:
I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.

I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.

$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    while (val.length > 3) {
      newVal += val.substr(0, 3) + '-';
      val = val.substr(3);
    }
    newVal += val;
    this.value = newVal;
});

http://jsfiddle.net/ssthil/nY2QT/

Body:
$('#ssn').keyup(function() {
        var val = this.value.replace(/\D/g, '');
        var newVal = '';
        for(i=0;i<2;i++){
         if (val.length > 3) {
          newVal += val.substr(0, 3) + '-';
          val = val.substr(3);
        }
        }
        newVal += val;
        this.value = newVal;
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ssn" maxlength="10"/>


问:
How to call oracle function which return sys_refcursor using java + hibernate
I am having a problem while calling oracle function,
the function look like bellow

CREATE OR REPLACE FUNCTION get_port_out_select
  (pi_id_pout_order IN PORT_OUT_ORDER.ID_POUT_ORDER % TYPE)
RETURN sys_refcursor
IS
lc_cursor sys_refcursor;
BEGIN

OPEN lc_cursor FOR
SELECT ID_POUT_ORDER, ID_LEC_USER, ID_POUT_LEC, ID_SERVICE_REC, POUT_TN, ID_IPTN, POUT_LEC_OCN, POUT_LEC_SPID, POUT_ALI_CODE,
LEC_CONTACT_FNAME, LEC_CONTACT_LNAME, LEC_CONTACT_TN, LEC_CONTACT_EMAIL,
DL_LEC_OCN, CUST_ACCT, CUST_F_NAME, CUST_L_NAME,
SVC_ADDR_STR, SVC_ADDR_NUM, SVC_ADDR_CITY, SVC_ADDR_STATE, SVC_ADDR_ZIP,
POUT_LOA_DATE, POUT_DDD, POUT_FOC, E_MAIL_SENT_DATE, V_MAIL_SENT_DATE, ID_POUT_STATUS, CUSTOMER_TYPE, AUTHORIZATION_NAME, ID_MASTER_POUT_ORDER
FROM PORT_OUT_ORDER
WHERE ID_POUT_ORDER = pi_id_pout_order
AND ID_POUT_STATUS < 95;

RETURN lc_cursor;
END;```
</div>
</div>
</p>

<p>it return the value as cursor
Bellow is the result when i execute the query in DB.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{<
ID_POUT_ORDER=2004,
ID_LEC_USER=39,
ID_POUT_LEC=36,
ID_SERVICE_REC=20277159,
POUT_TN=7186846814,
ID_IPTN=3990,
POUT_LEC_OCN=9147,
POUT_LEC_SPID=9147,
POUT_ALI_CODE=9147,
LEC_CONTACT_FNAME=unique,
LEC_CONTACT_LNAME=user,
LEC_CONTACT_TN=5165551234,
LEC_CONTACT_EMAIL=michael21474@gmail.com,
DL_LEC_OCN=9147,
CUST_ACCT=0785852664101,
CUST_F_NAME=YYYYYYY,
CUST_L_NAME=ZZZZZZ,
SVC_ADDR_STR=10thav,
SVC_ADDR_NUM=812,
SVC_ADDR_CITY=levittown,
SVC_ADDR_STATE=NY,
SVC_ADDR_ZIP=11756,
POUT_LOA_DATE=11-APR-07,
POUT_DDD=11-APR-07,
POUT_FOC=11-APR-07,
E_MAIL_SENT_DATE=10-APR-07,
V_MAIL_SENT_DATE=null,
ID_POUT_STATUS=1,
CUSTOMER_TYPE=Residential,
AUTHORIZATION_NAME=unique user,
ID_MASTER_POUT_ORDER=null
>,
}</code>```

I am using this to call the function

Query query = this.em.createNativeQuery("SELECT get_port_out_select(2004) FROM DUAL");
query.getSingleResult();```
</div>
</div>
</p>

<p>I am having a problem in getting the result.
I have checked the connectivity to database all is fine.
How do I handle this</p>

<p>Update 1:</p>

<p>Created the entity class</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@NamedNativeQueries(value = {
        @NamedNativeQuery(
                name = "functionCall",
                query = "{ SELECT get_port_out_select(2004) FROM DUAL }",
                resultClass = PortOutSelectCursor.class)

})

@Entity
public class PortOutSelectCursor{
 @Id
 @Column(name="ID_POUT_ORDER")
 private int ID_POUT_ORDER;

 @Column(name="ID_LEC_USER")
 private int ID_LEC_USER;

 @Column(name="ID_SERVICE_REC")
 private int ID_SERVICE_REC;

 @Column(name="POUT_TN")
 private String POUT_TN;

 @Column(name="ID_IPTN")
 private int ID_IPTN;

  // added all the attribute
  // added default constructor
  // added setter and getter
  }
 </code>```

Added the mapping in persistence.xml

<persistence-unit name="XOSS_PDB_PROCEDURE_PERSISTENCE_UNIT_1"
  transaction-type="JTA">
  <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
  <jta-data-source>myDataSource</jta-data-source>
  <mapping-file>META-INF/procedure.xml</mapping-file>
   <class>com.amdocs.oss.alt.procedure.response.PortOutSelectCursor</class>
  <properties>
   <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
   <property name="hibernate.show_sql" value="true" />
   <property name="hibernate.format_sql" value="true" />
   <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
   <property name="hibernate.hbm2ddl.auto" value="none" />
   <property name="hibernate.transaction.jta.platform"
    value="org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform" />
   <property name="hibernate.proc.param_null_passing" value="true" />
   <property name="alt.procedure_names" value="insertEquipReturn,getPortOutSelect" />
    <property name="hibernate.archive.autodetection" value="class"/>
  </properties>
 </persistence-unit>```
</div>
</div>
</p>

<p>Dao class look like this </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public void getPortOutSelect() {
  try {
    List < Object[] > a = this.em.createNamedQuery("functionCall").getResultList();

    Object[] r = a.get(0);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}</code>```

Still struggling to solve the problem. please help

答:
This is how to get the result in a Java class (hopefully you can port it to Hibernate using this question as an exemplar):

Oracle Setup:

```<code>CREATE FUNCTION get_ref_cursor RETURN SYS_REFCURSOR
IS
  out_cursor SYS_REFCURSOR;
BEGIN
  OPEN out_cursor FOR
    SELECT 123 AS col1 FROM DUAL UNION ALL
    SELECT 456 FROM DUAL UNION ALL
    SELECT 789 FROM DUAL;

  RETURN out_cursor;
END;
/
</code>```

Java:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;

public class GetRefCursorFromFunction
{
  public static void main( final String[] args ){
    try{
      Class.forName( "oracle.jdbc.OracleDriver" );

      Connection con = DriverManager.getConnection(
          "jdbc:oracle:thin:@localhost:1521:orcl",
          "USERNAME",
          "PASSWORD"
      );

      OracleCallableStatement st =
        (OracleCallableStatement) con.prepareCall( "BEGIN :1 := get_Ref_Cursor(); END;" );
      st.registerOutParameter( 1, OracleTypes.CURSOR );
      System.out.println( st.execute() );
      ResultSet rs = st.getCursor( 1 );
      while ( rs.next() )
      {
        System.out.println( rs.getInt( 1 ) );
      }

      st.close();
      con.close();
    } catch (ClassNotFoundException | SQLException ex) {
      System.out.println( ex.getMessage() );
      ex.printStackTrace();
    }
  }
}
</code>```

(Note: this assumes you are using Oracle's driver to connect to the database.)

Output:

```<code>123
456
789
</code>```

Body:
I am having a problem while calling oracle function,
the function look like bellow

CREATE OR REPLACE FUNCTION get_port_out_select
  (pi_id_pout_order IN PORT_OUT_ORDER.ID_POUT_ORDER % TYPE)
RETURN sys_refcursor
IS
lc_cursor sys_refcursor;
BEGIN

OPEN lc_cursor FOR
SELECT ID_POUT_ORDER, ID_LEC_USER, ID_POUT_LEC, ID_SERVICE_REC, POUT_TN, ID_IPTN, POUT_LEC_OCN, POUT_LEC_SPID, POUT_ALI_CODE,
LEC_CONTACT_FNAME, LEC_CONTACT_LNAME, LEC_CONTACT_TN, LEC_CONTACT_EMAIL,
DL_LEC_OCN, CUST_ACCT, CUST_F_NAME, CUST_L_NAME,
SVC_ADDR_STR, SVC_ADDR_NUM, SVC_ADDR_CITY, SVC_ADDR_STATE, SVC_ADDR_ZIP,
POUT_LOA_DATE, POUT_DDD, POUT_FOC, E_MAIL_SENT_DATE, V_MAIL_SENT_DATE, ID_POUT_STATUS, CUSTOMER_TYPE, AUTHORIZATION_NAME, ID_MASTER_POUT_ORDER
FROM PORT_OUT_ORDER
WHERE ID_POUT_ORDER = pi_id_pout_order
AND ID_POUT_STATUS < 95;

RETURN lc_cursor;
END;

it return the value as cursor
Bellow is the result when i execute the query in DB.

{<
ID_POUT_ORDER=2004,
ID_LEC_USER=39,
ID_POUT_LEC=36,
ID_SERVICE_REC=20277159,
POUT_TN=7186846814,
ID_IPTN=3990,
POUT_LEC_OCN=9147,
POUT_LEC_SPID=9147,
POUT_ALI_CODE=9147,
LEC_CONTACT_FNAME=unique,
LEC_CONTACT_LNAME=user,
LEC_CONTACT_TN=5165551234,
LEC_CONTACT_EMAIL=michael21474@gmail.com,
DL_LEC_OCN=9147,
CUST_ACCT=0785852664101,
CUST_F_NAME=YYYYYYY,
CUST_L_NAME=ZZZZZZ,
SVC_ADDR_STR=10thav,
SVC_ADDR_NUM=812,
SVC_ADDR_CITY=levittown,
SVC_ADDR_STATE=NY,
SVC_ADDR_ZIP=11756,
POUT_LOA_DATE=11-APR-07,
POUT_DDD=11-APR-07,
POUT_FOC=11-APR-07,
E_MAIL_SENT_DATE=10-APR-07,
V_MAIL_SENT_DATE=null,
ID_POUT_STATUS=1,
CUSTOMER_TYPE=Residential,
AUTHORIZATION_NAME=unique user,
ID_MASTER_POUT_ORDER=null
>,
}

I am using this to call the function

Query query = this.em.createNativeQuery("SELECT get_port_out_select(2004) FROM DUAL");
query.getSingleResult();

I am having a problem in getting the result.
I have checked the connectivity to database all is fine.
How do I handle this

Update 1:

Created the entity class

@NamedNativeQueries(value = {
        @NamedNativeQuery(
                name = "functionCall",
                query = "{ SELECT get_port_out_select(2004) FROM DUAL }",
                resultClass = PortOutSelectCursor.class)

})

@Entity
public class PortOutSelectCursor{
 @Id
 @Column(name="ID_POUT_ORDER")
 private int ID_POUT_ORDER;

 @Column(name="ID_LEC_USER")
 private int ID_LEC_USER;

 @Column(name="ID_SERVICE_REC")
 private int ID_SERVICE_REC;

 @Column(name="POUT_TN")
 private String POUT_TN;

 @Column(name="ID_IPTN")
 private int ID_IPTN;

  // added all the attribute
  // added default constructor
  // added setter and getter
  }

Added the mapping in persistence.xml

<persistence-unit name="XOSS_PDB_PROCEDURE_PERSISTENCE_UNIT_1"
  transaction-type="JTA">
  <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
  <jta-data-source>myDataSource</jta-data-source>
  <mapping-file>META-INF/procedure.xml</mapping-file>
   <class>com.amdocs.oss.alt.procedure.response.PortOutSelectCursor</class>
  <properties>
   <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
   <property name="hibernate.show_sql" value="true" />
   <property name="hibernate.format_sql" value="true" />
   <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
   <property name="hibernate.hbm2ddl.auto" value="none" />
   <property name="hibernate.transaction.jta.platform"
    value="org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform" />
   <property name="hibernate.proc.param_null_passing" value="true" />
   <property name="alt.procedure_names" value="insertEquipReturn,getPortOutSelect" />
    <property name="hibernate.archive.autodetection" value="class"/>
  </properties>
 </persistence-unit>

Dao class look like this

public void getPortOutSelect() {
  try {
    List < Object[] > a = this.em.createNamedQuery("functionCall").getResultList();

    Object[] r = a.get(0);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}

Still struggling to solve the problem. please help

Body:
This is how to get the result in a Java class (hopefully you can port it to Hibernate using this question as an exemplar):

Oracle Setup:

CREATE FUNCTION get_ref_cursor RETURN SYS_REFCURSOR
IS
  out_cursor SYS_REFCURSOR;
BEGIN
  OPEN out_cursor FOR
    SELECT 123 AS col1 FROM DUAL UNION ALL
    SELECT 456 FROM DUAL UNION ALL
    SELECT 789 FROM DUAL;

  RETURN out_cursor;
END;
/

Java:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;

public class GetRefCursorFromFunction
{
  public static void main( final String[] args ){
    try{
      Class.forName( "oracle.jdbc.OracleDriver" );

      Connection con = DriverManager.getConnection(
          "jdbc:oracle:thin:@localhost:1521:orcl",
          "USERNAME",
          "PASSWORD"
      );

      OracleCallableStatement st =
        (OracleCallableStatement) con.prepareCall( "BEGIN :1 := get_Ref_Cursor(); END;" );
      st.registerOutParameter( 1, OracleTypes.CURSOR );
      System.out.println( st.execute() );
      ResultSet rs = st.getCursor( 1 );
      while ( rs.next() )
      {
        System.out.println( rs.getInt( 1 ) );
      }

      st.close();
      con.close();
    } catch (ClassNotFoundException | SQLException ex) {
      System.out.println( ex.getMessage() );
      ex.printStackTrace();
    }
  }
}

(Note: this assumes you are using Oracle's driver to connect to the database.)

Output:

123
456
789