问:
DataTrigger does not change Text property
I'm attempting to use a data-trigger on a style to change a property.

In compliance with the "Minimal, Complete and Verifiable Example" requirements...

To reproduce, first create a WPF application in Visual Studio.

Within the App.xaml.cs :

```<code>using System.ComponentModel;
using System.Windows;

namespace Foo{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application, INotifyPropertyChanged {
        private bool _clicked;
        public bool Clicked {
            get { return this._clicked; }
            set {
                this._clicked = value;
                this.PropertyChanged?.Invoke(
                    this, new PropertyChangedEventArgs( "Clicked" ) );
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
</code>```

Within the MainWindow.xaml :

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:lib="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:Foo"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" x:Class="Foo.MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <lib:Boolean x:Key="True">True</lib:Boolean>
    </Window.Resources>
    <Grid>
        <Button x:Name="button" Click="button_Click">
            <Viewbox>
                <TextBlock Text="Unclicked">
                    <TextBlock.Style>
                        <Style TargetType="{x:Type TextBlock}">
                            <Style.Triggers>
                                <DataTrigger
                                        Binding="{Binding
                                            Clicked,
                                            Source={x:Static Application.Current}}"
                                            Value="{StaticResource True}">
                                    <Setter Property="Text" Value="Clicked" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
            </Viewbox>
        </Button>
    </Grid>
</Window>
</code>```

Within the MainWindow.xaml.cs -

```<code>using System.Windows;

namespace Foo{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
        public MainWindow( ) {
            InitializeComponent( );
        }

        private void button_Click( object sender, RoutedEventArgs e ) {
            ( Application.Current as App ).Clicked = !( Application.Current as App ).Clicked;
        }
    }
}
</code>```

As a side note - I tried setting the value of the data trigger to just "True", and that also did not work ( the trigger did not catch, and text did not change based on setting the property to a new value ).

So why is the data-trigger not catching or working here? ( Either with the static resource or the literal value )? Even more relevant - why am I getting this error? The "After a 'DataTrigger' is in use (sealed), it cannot be modified" error? And what is the proper method of accomplishing what I am trying to do here? ( Preferably still using a data-trigger and not a converter, since I do need to switch between two values ).

答:
The local value assigned to the TextBlock's Text property has higher precedence than the value provided by the Setter in the DataTrigger. See Dependency Property Value Precedence for details.

Set the initial Text value by another Setter:

```<code><TextBlock>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="Unclicked"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Clicked,
                                       Source={x:Static Application.Current}}"
                             Value="{StaticResource True}">
                    <Setter Property="Text" Value="Clicked" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
</code>```

The error message you see when you use the Boolean resource is just the XAML designer complaining. There is no error at runtime.

Body:
I'm attempting to use a data-trigger on a style to change a property.

In compliance with the "Minimal, Complete and Verifiable Example" requirements...

To reproduce, first create a WPF application in Visual Studio.

Within the App.xaml.cs :

using System.ComponentModel;
using System.Windows;

namespace Foo{
///
/// Interaction logic for App.xaml
///
public partial class App : Application, INotifyPropertyChanged {
        private bool _clicked;
        public bool Clicked {
            get { return this._clicked; }
            set {
                this._clicked = value;
                this.PropertyChanged?.Invoke(
                    this, new PropertyChangedEventArgs( "Clicked" ) );
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Within the MainWindow.xaml :

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:lib="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:Foo"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    mc:Ignorable="d" x:Class="Foo.MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <lib:Boolean x:Key="True">True</lib:Boolean>
    </Window.Resources>
    <Grid>
        <Button x:Name="button" Click="button_Click">
            <Viewbox>
                <TextBlock Text="Unclicked">
                    <TextBlock.Style>

                        </Style>
                    </TextBlock.Style>
                </TextBlock>
            </Viewbox>
        </Button>
    </Grid>
</Window>

Within the MainWindow.xaml.cs -

using System.Windows;

namespace Foo{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window {
        public MainWindow( ) {
            InitializeComponent( );
        }

        private void button_Click( object sender, RoutedEventArgs e ) {
            ( Application.Current as App ).Clicked = !( Application.Current as App ).Clicked;
        }
    }
}

As a side note - I tried setting the value of the data trigger to just "True", and that also did not work ( the trigger did not catch, and text did not change based on setting the property to a new value ).

So why is the data-trigger not catching or working here? ( Either with the static resource or the literal value )? Even more relevant - why am I getting this error? The "After a 'DataTrigger' is in use (sealed), it cannot be modified" error? And what is the proper method of accomplishing what I am trying to do here? ( Preferably still using a data-trigger and not a converter, since I do need to switch between two values ).

Body:
The local value assigned to the TextBlock's Text property has higher precedence than the value provided by the Setter in the DataTrigger. See Dependency Property Value Precedence for details.

Set the initial Text value by another Setter:

<TextBlock>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="Unclicked"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Clicked,
                                       Source={x:Static Application.Current}}"
                             Value="{StaticResource True}">
                    <Setter Property="Text" Value="Clicked" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

The error message you see when you use the Boolean resource is just the XAML designer complaining. There is no error at runtime.


来源: stackexchange

问:
GKE + WebSocket + NodePort 30s dropped connections
I have a golang service that implements a WebSocket client using gorilla that is exposed to a Google Container Engine (GKE)/k8s cluster via a NodePort (30002 in this case).

I've got a manually created load balancer (i.e. NOT at k8s ingress/load balancer) with HTTP/HTTPS frontends (i.e. 80/443) that forward traffic to nodes in my GKE/k8s cluster on port 30002.

I can get my JavaScript WebSocket implementation in the browser (Chrome 58.0.3029.110 on OSX) to connect, upgrade and send / receive messages.

I log ping/pongs in the golang WebSocket client and all looks good until 30s in. 30s after connection my golang WebSocket client gets an EOF / close 1006 (abnormal closure) and my JavaScript code gets a close event. As far as I can tell, neither my Golang or JavaScript code is initiating the WebSocket closure.

I don't particularly care about session affinity in this case AFAIK, but I have tried both IP and cookie based affinity in the load balancer with long lived cookies.

Additionally, this exact same set of k8s deployment/pod/service specs and golang service code works great on my KOPS based k8s cluster on AWS through AWS' ELBs.

Any ideas where the 30s forced closures might be coming from? Could that be a k8s default cluster setting specific to GKE or something on the GCE load balancer?

Thanks for reading!

-- UPDATE --

There is a backend configuration timeout setting on the load balancer which is for "How long to wait for the backend service to respond before considering it a failed request".

The WebSocket is not unresponsive. It is sending ping/pong and other messages right up until getting killed which I can verify by console.log's in the browser and logs in the golang service.

That said, if I bump the load balancer backend timeout setting to 30000 seconds, things "work".

Doesn't feel like a real fix though because the load balancer will continue to feed actual unresponsive services traffic inappropriately, never mind if the WebSocket does become unresponsive.

I've isolated the high timeout setting to a specific backend setting using a path map, but hoping to come up with a real fix to the problem.

答: Check out the following example: https://github.com/kubernetes/ingress-gce/tree/master/examples/websocket</p>

ContentLicense: CC BY-SA 3.0


问:
How can I display the test name *after* the test using pytest?
Most of the time when I'm using pytest, the output is very, very long. More than a hundred lines. And often times I want this output, I really do. --tb=short isn't really a very good approach. But I don't want to have to scroll back 200 lines in my tmux window to find my test output because that's also super annoying.

What I would love to have is something like this:

```<code>______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________
</code>```

Is there some flag or setting I can use in py.test to achieve this kind of output?

答:
You can add one fixture in your main/root conftest.py which would be called automatically before and after every test-case. Like

```<code>@pytest.fixture(scope='function', autouse=True)
def test_log(request):
    logging.info("Test '{}' STARTED".format(request.node.nodeid)) # Here logging is used, you can use whatever you want to use for logs
    def fin():
        logging.info("Test '{}' COMPLETED".format(request.node.nodeid))
    request.addfinalizer(fin)
</code>```

Here, request.node.nodeid gives you a name of your test.

Body:
Most of the time when I'm using pytest, the output is very, very long. More than a hundred lines. And often times I want this output, I really do. --tb=short isn't really a very good approach. But I don't want to have to scroll back 200 lines in my tmux window to find my test output because that's also super annoying.

What I would love to have is something like this:

______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________

Is there some flag or setting I can use in py.test to achieve this kind of output?

Body:
You can add one fixture in your main/root conftest.py which would be called automatically before and after every test-case. Like

@pytest.fixture(scope='function', autouse=True)
def test_log(request):
    logging.info("Test '{}' STARTED".format(request.node.nodeid)) # Here logging is used, you can use whatever you want to use for logs
    def fin():
        logging.info("Test '{}' COMPLETED".format(request.node.nodeid))
    request.addfinalizer(fin)

Here, request.node.nodeid gives you a name of your test.


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
It depends which version of C# you're using, from version 3.0 onwards you can use...</p>

```<code>List<string> nameslist = new List<string> { "one", "two", "three" };
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

Body:
It depends which version of C# you're using, from version 3.0 onwards you can use...

List<string> nameslist = new List<string> { "one", "two", "three" };

ContentLicense: CC BY-SA 2.5


问:
How to add two compiler flags in Xcode
I would like to add two compiler flags, one for ARC (-fno-objc-arc) and one for warning (-w). Anybody know how to add two compiler flags in the Xcode build phase for a particular file?</p>

答:
Select blue project file

Select "Build phases".

Disclose "Compile Sources".

Double click on file that you want to add flags.

Then set flags separated by space.

Title: How to add two compiler flags in Xcode


问:
Changing Deeply Nested Object Value
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

```<code>> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'
</code>```

```<code>> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'
</code>```

答:
You can use JSON.stringify(), JSON.parse(), String.prototype.replace(). You can also use a RegExp that only checks property name, instead of both property name and value.

var obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}

function updateObject(obj, key, val, value) {
  return JSON.parse(JSON.stringify(obj)
         .replace(new RegExp(`"${key}":"${val}"`), `"${key}":"${value}"`))
}

obj = updateObject(obj, "key5", "value", "changeme");

console.log(obj);```

Title: Changing Deeply Nested Object Value

Body:
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'

> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'


问:
Jquery AJAX Global Timeout (Entire Application) Im using $.get & $.post (can't use $.ajax)
I have created the spring web application with jquery. For every ajax call im using $.get or $.post (NOT $.ajax).

But I didn't handle any ajax timeouts or ajax error. Now my application is deployed in the server, I can't make any major changes.

Pls help me how to handle the AJAX Timeout for the entire web application and i should alert("Ajax Timeout") globally. additionally whatever the ajax error, i should alert the error message to the user.

I heard about $.ajaxSetup and $.ajaxError

But How to use them in my web application, Do i need to add it in document.ready ??

答:
You can use
$.ajaxSetup({timeout: 100});</p>


问:
How do I navigate from one xaml page to another, and pass values?
Somewhat related to this topic here:
Async XML Reading in Windows Phone 7

I'm developing a Windows Phone app, and I have a search function in my Search.xaml.cs file. It is called by clicking a button, it creates a search query and calls DownloadStringInBackground with it

```<code>    private void SearchQuery(object sender, EventArgs e)
    {
        string temp = "http://api.search.live.net/xml.aspx?Appid=myappid&query=randomqueryhere&sources=web";
        DownloadStringInBackground(temp);
    }

    public static void DownloadStringInBackground(string address)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri(address);

        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
        client.DownloadStringAsync(uri);
    }

    private static void DownloadStringCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // Fancy manipulation logic here

        finalResult = words;
    }
</code>```

finalResult has been stored as

```<code>public static string[] finalResult;
</code>```

in the Search class. My question is, where can I put the Navigate command (NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative));)? I tried doing it in the callback, but I get a nullobject exception due to the static keyword. How can I ensure that finalResult has been populated, and that I can navigate to Result.xaml and reference the data in finalResult on that page. Alternately, how can I pass Words or finalResult to Result.xaml?

Thanks for looking :)

答:
There is a walkthrough here on passing values between pages.

How to: Perform Page Navigation on Windows Phone

Body:
Somewhat related to this topic here:
Async XML Reading in Windows Phone 7

I'm developing a Windows Phone app, and I have a search function in my Search.xaml.cs file. It is called by clicking a button, it creates a search query and calls DownloadStringInBackground with it

    private void SearchQuery(object sender, EventArgs e)
    {
        string temp = "http://api.search.live.net/xml.aspx?Appid=myappid&query=randomqueryhere&sources=web";
        DownloadStringInBackground(temp);
    }

    public static void DownloadStringInBackground(string address)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri(address);

        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
        client.DownloadStringAsync(uri);
    }

    private static void DownloadStringCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // Fancy manipulation logic here

        finalResult = words;
    }

finalResult has been stored as

public static string[] finalResult;

in the Search class. My question is, where can I put the Navigate command (NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative));)? I tried doing it in the callback, but I get a nullobject exception due to the static keyword. How can I ensure that finalResult has been populated, and that I can navigate to Result.xaml and reference the data in finalResult on that page. Alternately, how can I pass Words or finalResult to Result.xaml?

Thanks for looking :)


问:
Azure minute/hourly metric collection issue using SDK
hi i'm trying to get the hourly/minute metrics using the sdk provided by azure but i'm confused ,i got the below result isn't Partition key the Time?
PartitionKey=20170605T1531 RowKey=system;All TimeStamp=Mon Jun 05 21:02:24 IST 2017
PartitionKey=20170605T1533 RowKey=system;All TimeStamp=Mon Jun 05 21:04:23 IST 2017
PartitionKey=20170605T1539 RowKey=system;All TimeStamp=Mon Jun 05 21:10:24 IST 2017
PartitionKey=20170605T1540 RowKey=system;All TimeStamp=Mon Jun 05 21:11:24 IST 2017
Please explain the concept /difference in PartitionKey and TimeStamp?</p>

答:
Please explain the concept /difference in PartitionKey and TimeStamp?

In Azure Table service, each entity has 3 system properties that specify a partition key, a row key, and a timestamp column that the Table service uses to track when the entity was last updated (this happens automatically and you cannot manually overwrite the timestamp with an arbitrary value).


问:
can i combine if else and with try catch python?
i have a code :

```<code>s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")
</code>```

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

答:
Try/catch is to handle exceptions, not to handle return values from methods. In your case, what you wrote would compile but is not what you want to do.

The easiest solution for you would be it use what already exists in python, ie. socket, which can nicely validate IP for you. If you still want to use the validate() method for other purpose, then you can write:

```<code>import socket

def validate(a):
  socket.inet_aton(s)

try:
    validate(s)
    # your code here
except socket.error:
    print("insert your ip correctly")
</code>```

In that case, the socket.inet_aton method will raise the exception socket.error, which you can then catch. If for some reason you do not want to use socket, then you can define your own exception, raise it from validate() and catch it outside validate().

For Python 3, you will be better served by ipaddress as socket is too permissive (for good reasons, see man inet(3)):

```<code>import ipaddress

def validate(a):
    ipaddress.ip_address(a)

try:
    validate(s)
    # your code here
except ValueError:
    print("insert your ip correctly")
</code>```

On a side note, I believe you want to return True as the last line of validate(), but that would not change the problem.

On a (second) side note, catching all exceptions (bare catch statement) is bad practice. In your code you handle a specific error (IP not valid) you should only catch exceptions related to this problem.

Body:
i have a code :

s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

Body:
Try/catch is to handle exceptions, not to handle return values from methods. In your case, what you wrote would compile but is not what you want to do.

The easiest solution for you would be it use what already exists in python, ie. socket, which can nicely validate IP for you. If you still want to use the validate() method for other purpose, then you can write:

import socket

def validate(a):
  socket.inet_aton(s)

try:
    validate(s)
    # your code here
except socket.error:
    print("insert your ip correctly")

In that case, the socket.inet_aton method will raise the exception socket.error, which you can then catch. If for some reason you do not want to use socket, then you can define your own exception, raise it from validate() and catch it outside validate().

For Python 3, you will be better served by ipaddress as socket is too permissive (for good reasons, see man inet(3)):

import ipaddress

def validate(a):
    ipaddress.ip_address(a)

try:
    validate(s)
    # your code here
except ValueError:
    print("insert your ip correctly")

On a side note, I believe you want to return True as the last line of validate(), but that would not change the problem.

On a (second) side note, catching all exceptions (bare catch statement) is bad practice. In your code you handle a specific error (IP not valid) you should only catch exceptions related to this problem.


问:
kafka how to implement exactly-once message delivery logic with topic/partition/offset
I manage to get the topic/partition/offset in method annotated with @KafkaListener,  but how can i use these data to implement a exactly-once consumer logic ?

I'm using ConcurrentKafkaListenerContainerFactory with setting of concurrenc=4, and set the  AckMode to MANUAL.
My current way is using redis to dedup:
I use topic:partition as redis key, offset as its value, then compare the coming offset with the value in redis, if the offset is newer(greater) than redis one, then go on the business logic, else I ignore the  message. finally commit the offset(ack.acknowledge())

but this way not work, for example, if the rebalance happen before ack.acknowledge() finish, then it came out this error :org.apache.kafka.clients.consumer.CommitFailedException,

and after rebalancing , the original partition is assigned to another thread, which cause the same message will be consume twice.

so in one word, how to design a logic that can make each kafka message delivery exactly-once ?

答: You have to write out the last offset processed atomically, along with the results of the processing, outside of Kafka. This can be to a database or file, just don't do two writes, make it a single atomic write of both data and offset. If your consumer crashes and it or another instance restarts or takes over, you need to make sure that first it reads the last offset stored with the last processing results and seek() to that position before you poll() for more messages. This is how many of the existing Kafka Sink Connectors can achieve EOS consumption today.</p>


问:
Nginx Redirect of HTTP to HTTPS partially working
My objective is to redirect my web site like this:

http://EXAMPLE.com/ to https://EXAMPLE.com/ (working)

http://www.EXAMPLE.com/ to https://EXAMPLE.com/ (not working). This one is currently redirecting to https://www.EXAMPLE.com/.

In addition, even though I didn't define api.EXAMPLE.com in the server section below, when I enter the URL as http://api.EXAMPLE.com/, it gets redirected to https://api.EXAMPLE.com/. I believe this has to do with the DNS record resolving to the same IP address. I would rather it show page not found instead of redirecting.

DNS Records:

```<code>Type  Name    Value           TTL
A     @       35.161.XX.XX    600 seconds
A     api     35.161.XX.XX    1 Hour
A     www     35.161.XX.XX    1 Hour
</code>```

And the Nginx configuration file:

```<code># For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    #keepalive_timeout  65;
    keepalive_timeout   15;

    types_hash_max_size 2048;

    # Enable HTTPS by default on all our websites
    #add_header Strict-Transport-Security "max-age=63072000; includeSubDomains";

    #php max upload limit cannot be larger than this
    client_max_body_size 40m;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    index   index.php index.html index.htm;

    # Upstream to abstract backend connection(s) for PHP.
    upstream php {
        #this should match value of "listen" directive in php-fpm pool
        server unix:/tmp/php-fpm.sock;
        #server 127.0.0.1:9000;
    }

    # Redirect unsecured port 80 traffic (http://) to port 443 (https://)
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  EXAMPLE.com www.EXAMPLE.com;
  #return 301 $scheme://EXAMPLE.com$request_uri;
        #return 301 https://$host$request_uri;
  return 301 https://EXAMPLE.com$request_uri;
    }

    #server {
    #    listen       80 default_server;
    #    listen       [::]:80 default_server;
        #server_name  localhost;
    #    server_name  EXAMPLE.com;
        #root         /usr/share/nginx/html;
    #    root         /var/www/nginx;

        # Load configuration files for the default server block.
    #    include /etc/nginx/default.d/*.conf;

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

    #}

    # Settings for a TLS enabled server.
    server {
        listen       443 ssl http2 default_server;
        listen       [::]:443 ssl http2 default_server;
        server_name  EXAMPLE.com;
        root         /var/www/nginx;

  #For Basic Auth
  auth_basic "Restricted";
  auth_basic_user_file /var/www/nginx/.htpasswd;

        #ssl_certificate "/etc/pki/tls/certs/EXAMPLE.crt";
        #ssl_certificate_key "/etc/pki/tls/private/EXAMPLE.key";
        ssl_certificate "/etc/letsencrypt/live/EXAMPLE.com/cert.pem";
        ssl_certificate_key "/etc/letsencrypt/live/EXAMPLE.com/privkey.pem";

        # It is *strongly* recommended to generate unique DH parameters
        # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048
        #ssl_dhparam "/etc/pki/nginx/dhparams.pem";
        ssl_dhparam "/etc/pki/tls/dhparams.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP;
        ssl_prefer_server_ciphers on;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    }

}
</code>```

答:
Based on the lead from Richard, here is how I erased the HTTP Strict Transport Security history from Chrome:

In the Query Domain section, I entered my domain and sub-domains: example.com, www.example.com, db.example.com, api.example.com to see if they were listed.

Then I entered those I found into the Delete Domain section and pressed Delete.

I entered http://www.example.com into the browswer's location field and pressed Enter. It redirected to https://example.com.

I also tried http://db.example.com and http://api.example.com and both were redirected to https://example.com. I'm curious why these got redirected since I didn't have a server section for them in nginx.conf. Is it because it resolved to the same IP?

Lastly, I tried http://what.example.com and got a "Can't reach this page" error; which is right.

chrome://net-internals/#hsts

Body:
My objective is to redirect my web site like this:

http://EXAMPLE.com/ to https://EXAMPLE.com/ (working)

http://www.EXAMPLE.com/ to https://EXAMPLE.com/ (not working). This one is currently redirecting to https://www.EXAMPLE.com/.

In addition, even though I didn't define api.EXAMPLE.com in the server section below, when I enter the URL as http://api.EXAMPLE.com/, it gets redirected to https://api.EXAMPLE.com/. I believe this has to do with the DNS record resolving to the same IP address. I would rather it show page not found instead of redirecting.

DNS Records:

Type  Name    Value           TTL
A     @       35.161.XX.XX    600 seconds
A     api     35.161.XX.XX    1 Hour
A     www     35.161.XX.XX    1 Hour

And the Nginx configuration file:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    #keepalive_timeout  65;
    keepalive_timeout   15;

    types_hash_max_size 2048;

    # Enable HTTPS by default on all our websites
    #add_header Strict-Transport-Security "max-age=63072000; includeSubDomains";

    #php max upload limit cannot be larger than this
    client_max_body_size 40m;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    index   index.php index.html index.htm;

    # Upstream to abstract backend connection(s) for PHP.
    upstream php {
        #this should match value of "listen" directive in php-fpm pool
        server unix:/tmp/php-fpm.sock;
        #server 127.0.0.1:9000;
    }

    # Redirect unsecured port 80 traffic (http://) to port 443 (https://)
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  EXAMPLE.com www.EXAMPLE.com;
  #return 301 $scheme://EXAMPLE.com$request_uri;
        #return 301 https://$host$request_uri;
  return 301 https://EXAMPLE.com$request_uri;
    }

    #server {
    #    listen       80 default_server;
    #    listen       [::]:80 default_server;
        #server_name  localhost;
    #    server_name  EXAMPLE.com;
        #root         /usr/share/nginx/html;
    #    root         /var/www/nginx;

        # Load configuration files for the default server block.
    #    include /etc/nginx/default.d/*.conf;

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

    #}

    # Settings for a TLS enabled server.
    server {
        listen       443 ssl http2 default_server;
        listen       [::]:443 ssl http2 default_server;
        server_name  EXAMPLE.com;
        root         /var/www/nginx;

  #For Basic Auth
  auth_basic "Restricted";
  auth_basic_user_file /var/www/nginx/.htpasswd;

        #ssl_certificate "/etc/pki/tls/certs/EXAMPLE.crt";
        #ssl_certificate_key "/etc/pki/tls/private/EXAMPLE.key";
        ssl_certificate "/etc/letsencrypt/live/EXAMPLE.com/cert.pem";
        ssl_certificate_key "/etc/letsencrypt/live/EXAMPLE.com/privkey.pem";

        # It is *strongly* recommended to generate unique DH parameters
        # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048
        #ssl_dhparam "/etc/pki/nginx/dhparams.pem";
        ssl_dhparam "/etc/pki/tls/dhparams.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP;
        ssl_prefer_server_ciphers on;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    }

}


问:
Partial matches with PostgreSQL full text search
Django's documentation for the PostgreSQL full text search uses the following example:

```<code>>>> Entry.objects.filter(body_text__search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
</code>```

I would like to use this, but to get the same results by searching for only part of the word. Currently this results in no results:

```<code>>>> Entry.objects.filter(body_text__search='Chee')
[]
</code>```

Basically I would like to get the same results that I would get using body_text__icontains. I would like to use full text search so that after I get this working I can take advantage of things such as reusable search vectors, weighting queries and ranking.

Is there some way to get results with partial word queries?

答:
The django.contrib.postgres.search module is implemented on PotgreSQL's full-text search engine.

Specifically, it turns the text values into PostgreSQL “tsvector” values, and turns your search term into a PostgreSQL “tsquery” value. So, if you're using this feature, you should learn about how to search using tsquery.

The example you give is illustrated in PostgreSQL like this:

=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Cheese'::tsquery;
 ?column?
----------
 t
(1 row)

=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Chees'::tsquery;
 ?column?
----------
 f
(1 row)
```

<p>So, a tsquery of <code>'Chees'</code> doesn't match the text. Django is telling you the right thing.</p>

<p>An example of a tsquery that <em>does</em> match is <code>'Chees:*'</code>:</p>

<pre class="lang-sql prettyprint-override"><code>=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Chees:*'::tsquery;
 ?column?
----------
 t
(1 row)
</code>```

The larger answer is: You'll need to learn about how to form full-text search queries the way PostgreSQL expects them, if you want to use this feature correctly :-)

Body:
Django's documentation for the PostgreSQL full text search uses the following example:

>>> Entry.objects.filter(body_text__search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]

I would like to use this, but to get the same results by searching for only part of the word. Currently this results in no results:

>>> Entry.objects.filter(body_text__search='Chee')
[]

Basically I would like to get the same results that I would get using body_text__icontains. I would like to use full text search so that after I get this working I can take advantage of things such as reusable search vectors, weighting queries and ranking.

Is there some way to get results with partial word queries?

Body:
The django.contrib.postgres.search module is implemented on PotgreSQL's full-text search engine.

Specifically, it turns the text values into PostgreSQL “tsvector” values, and turns your search term into a PostgreSQL “tsquery” value. So, if you're using this feature, you should learn about how to search using tsquery.

The example you give is illustrated in PostgreSQL like this:

=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Cheese'::tsquery;
 ?column?
----------
 t
(1 row)

=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Chees'::tsquery;
 ?column?
----------
 f
(1 row)

So, a tsquery of 'Chees' doesn't match the text. Django is telling you the right thing.

An example of a tsquery that does match is 'Chees:*':

=> SELECT 'Cheese on Toast recipes'::tsvector @@ 'Chees:*'::tsquery;
 ?column?
----------
 t
(1 row)

The larger answer is: You'll need to learn about how to form full-text search queries the way PostgreSQL expects them, if you want to use this feature correctly :-)


问:
How to get checkbox from ListView android?
Iam getting Checkbox from OnItemClickListener by using below snippet

```<code>onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Log.w("TAG","onItemClick clicked position :"+position);

        CheckBox cbx = (CheckBox)view.findViewById(R.id.c_checkbox);
        if(cbx.isChecked()){
            Toast.makeText(getApplicationContext(),
                    "Checked position " + shoppingList.get(position).getItem(),
                    Toast.LENGTH_SHORT).show();
        }
</code>```

I need to get all the positions to check which list item is checked.For that
I used below snippet

```<code>int firstPosition = list.getFirstVisiblePosition();
             for(int i=firstPosition;i<=list.getCount();i++){
             View v=list.getChildAt(i);
             cbx = (CheckBox)v.findViewById(R.id.c_checkbox);
             if(cbx.isChecked()){
            }
         }
</code>```

in below code cbx giving me null pointer exception.i used ViewHolder for the custom adapter.Please give me solution.why same thing is worked in OnItemClickListener?

Regards,
Rajendar

答:
it think it could be

```<code>for(int i=firstPosition;i< **=** list.getCount();i++)
</code>```

but that is just a wild guess.

why not use a checkable listview and then use this?

Body:
Iam getting Checkbox from OnItemClickListener by using below snippet

onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Log.w("TAG","onItemClick clicked position :"+position);

        CheckBox cbx = (CheckBox)view.findViewById(R.id.c_checkbox);
        if(cbx.isChecked()){
            Toast.makeText(getApplicationContext(),
                    "Checked position " + shoppingList.get(position).getItem(),
                    Toast.LENGTH_SHORT).show();
        }

I need to get all the positions to check which list item is checked.For that
I used below snippet

int firstPosition = list.getFirstVisiblePosition();
             for(int i=firstPosition;i<=list.getCount();i++){
             View v=list.getChildAt(i);
             cbx = (CheckBox)v.findViewById(R.id.c_checkbox);
             if(cbx.isChecked()){
            }
         }

in below code cbx giving me null pointer exception.i used ViewHolder for the custom adapter.Please give me solution.why same thing is worked in OnItemClickListener?

Regards,
Rajendar

Body:
it think it could be

for(int i=firstPosition;i< **=** list.getCount();i++)

but that is just a wild guess.

why not use a checkable listview and then use this?


问:
Use of finally in java
Consider the code

```<code>try{
    //code
} catch(Exception e) {
    // handle
} finally {
    // close open connections
}
</code>```

and this

```<code>try{
    //code
} catch(Exception e) {
    // handle
}
// close open connections
</code>```

since both are same what is the necessity of finally block?

答:
A finally block is much safer, as it's guaranteed to execute even if your try block throws an exception that isn't handled by the catch block or returns.

It also has the side effect of organizing all the "cleanup" code in an expected location, making the code (arguably) easier to maintain.

It's worth noting, by the way, that if you're using Java 7 or higher, and the resource you're handling is an AutoCloseable (such as a java.sql.Connection, for example), there's an even cleaner solution - the try-with-resource syntax, which saves you the hassle of explicitly closing the resource:

```<code>try (Connection con = /* something */) {
    // code
} catch (SomeException e) {
    // handle
    // If there's nothing intelligent to do, this entire clause can be omitted.
}
</code>```

Title: Use of finally in java

Body:
Consider the code

try{
    //code
} catch(Exception e) {
    // handle
} finally {
    // close open connections
}

and this

try{
    //code
} catch(Exception e) {
    // handle
}
// close open connections

since both are same what is the necessity of finally block?

Body:
A finally block is much safer, as it's guaranteed to execute even if your try block throws an exception that isn't handled by the catch block or returns.

It also has the side effect of organizing all the "cleanup" code in an expected location, making the code (arguably) easier to maintain.

It's worth noting, by the way, that if you're using Java 7 or higher, and the resource you're handling is an AutoCloseable (such as a java.sql.Connection, for example), there's an even cleaner solution - the try-with-resource syntax, which saves you the hassle of explicitly closing the resource:

try (Connection con = /* something */) {
    // code
} catch (SomeException e) {
    // handle
    // If there's nothing intelligent to do, this entire clause can be omitted.
}


问:
Is it possible to debug application wireless or without connecting USB cable in XCODE?
how to connect device in xcode without cable. it is tedious to connect the cable and my USB is lil bit loose, so it disconnects from PC.</p>

答:
It will be now possible with the latest update of Xcode 9.

Cut the Cord

Choose any of your iOS or tvOS devices on the local
network to install, run, and debug your apps – without a USB cord
plugged into your Mac. Simply click the ‘Connect via Network’ checkbox
the first time you use a new iOS device, and that device will be
available over the network from that point forward. Wireless
development also works in other apps, including Instruments,
Accessibility Inspector, Quicktime Player, and Console.

Check this for the latest updates.


问:
How to set cursor position in EditText?
There are two EditText,while loading the page a text is set in the first EditText, So now cursor will be in the starting place of EditText, I want to set cursor position in the second EditText which contains no data. How to do this?

答:
In kotlin, you could create an extension function like this:

```<code>fun EditText.placeCursorAtLast() {
    val string = this.text.toString()
    this.setSelection(string.length)
}
</code>```

and then simply call myEditText.placeCursorAtLast()

Title: How to set cursor position in EditText?

Body:
In kotlin, you could create an extension function like this:

fun EditText.placeCursorAtLast() {
    val string = this.text.toString()
    this.setSelection(string.length)
}

and then simply call myEditText.placeCursorAtLast()


答:
finally block is used to execute important code such as closing connection, stream etc. finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Java finally block is always executed whether exception is handled or not.

For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Title: Use of finally in java


问:
How do I remove these values in a list in Python?
```<code>x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]
</code>```

How do I remove the increasing values on every list?

If I removed the increasing in those lists, they should look like this:

```<code>x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]
</code>```

Body:
x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]

How do I remove the increasing values on every list?

If I removed the increasing in those lists, they should look like this:

x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]

Body:
This will remove any increasing elements:

Code:

def remove_increasing(a_list):
    return [a_list[0]] + \
           [y for x, y in zip(a_list, a_list[1:]) if x >= y] + \
           [a_list[-1]]

Test Code:

data = (
    [1, 2, 3, 4, 5, 6],
    [3, 5, 6, 8, 9],
    [2, 4, 5, 7, 13],
    [11, 22, 33, 24, 55, 66],
    [11, 7, 1, 2, 3, 4, 5, 6]
)

for d in data:
    print(remove_increasing(d))

Results:

[1, 6]
[3, 9]
[2, 13]
[11, 24, 66]
[11, 7, 1, 6]


问:
Basic Approach to Diagnostic Logging in SSIS
Given help from this microsoft link, I am aware of many tools related to SSIS diagnostics:

Event Handlers (in particular, "OnError")

Error Outputs

Operations Reports

SSISDB Views

Logging

Debug Dump Files

I just want to know what is the basic, "go to" approach for (non-production) diagnostics setup with SSIS.  I am a developer who WILL have access to the QA and UAT servers where I will be performing diagnostics.

In my first attempt to find the source of an error, I used SSMS to view operational reports.  All I saw was this:

I followed the instructions shown above, but all it did was lead me in a circle.  The overview allows me to see the details, but the details show the above message and ask me to go back to the overview.  In short, there is zero error information beyond telling me which task failed within the SSIS package.

I simply want to get to a point where I can at last see SOMETHING about the error(s).

If the answer is that I first need to configure an OnError event in my package, then my next question is: what would the basic, "go to" designer-flow look like for that OnError event?

FYI, this question is similar to "best way of logging in SSIS"

I also noticed an overall strategy for success with SSIS in this answer.  The author says:

Instrument your code - have it make log entries, possibly recording diagnostics such as check totals or counts. Without this, troubleshooting is next to impossible. Also, assertion checking is a good way to think of error handling for this (does row count in a equal row count in b, is A:B relationship really 1:1).

Sounds good!  But I'd like to have a more concrete example...particularly for feeding me the basics of what specific errors were generated.

I'm trying to avoid learning ALL the SSIS diagnostic approaches, just for the purpose of picking one good "all around" approach.

Update

Per Nick.McDermaid suggestion, in the SSISDB DB I run this:

```<code>SELECT * FROM [SSISDB].[catalog].[executions] ORDER BY start_time DESC
</code>```

This shows to me the packages that I manually executed.  The timestamps correctly reflect when I ran them.  If anything is unusual(?) it is that the reference_id, reference_type and environment_name columns are null. All the other columns have values.

Update #2

I discovered half the answer I'm looking for.  The reason no error information is available, is because by default the SSIS package execution logging level is "none".  I had to change the logging level.

Nick.McDermaid gave me the rest of the answering by explaining that I don't need to dive into OnError tooling or SSIS logging provider tooling.

答:
Adding to the excellent answer of @Nick.McDermaid.

I use SSIS Catalog error reporting. In most cases, it is sufficient and have the following functionality for error analysis. Emphasis is on the following:

Usually the first or second error message contains meaningful information on error. The latter is some error occurred in the dataflow....

If you look at the first/second error message at All Messages report at Error Messages section, you will see Error Context hyperlink. Invoking it will show you environment, connection managers and some variables at the moment of package crash.

Good error analysis is more an approach and practice than a mere tool selection. Here are my recommendations:

SSIS likes to report error code instead of meaningful explanation. So, Integration Services Error and Message Reference is your friend.

SSIS includes in error context (see above) dump those variables which have Include in ErrorDump property set to true.

I build SQL commands for SQL Task or DataFlow Source in variables. This allows to display SQL command executed at error in error context, when you set incude in Dump property on these variables.

Structure your variables well. If some variable is used only at some task - declare it on this task. Otherwise a mess of dumped variables will hurt you more than do any good.

Body:
Given help from this microsoft link, I am aware of many tools related to SSIS diagnostics:

Event Handlers (in particular, "OnError")

Error Outputs

Operations Reports

SSISDB Views

Logging

Debug Dump Files

I just want to know what is the basic, "go to" approach for (non-production) diagnostics setup with SSIS.  I am a developer who WILL have access to the QA and UAT servers where I will be performing diagnostics.

In my first attempt to find the source of an error, I used SSMS to view operational reports.  All I saw was this:

I followed the instructions shown above, but all it did was lead me in a circle.  The overview allows me to see the details, but the details show the above message and ask me to go back to the overview.  In short, there is zero error information beyond telling me which task failed within the SSIS package.

I simply want to get to a point where I can at last see SOMETHING about the error(s).

If the answer is that I first need to configure an OnError event in my package, then my next question is: what would the basic, "go to" designer-flow look like for that OnError event?

FYI, this question is similar to "best way of logging in SSIS"

I also noticed an overall strategy for success with SSIS in this answer.  The author says:

Instrument your code - have it make log entries, possibly recording diagnostics such as check totals or counts. Without this, troubleshooting is next to impossible. Also, assertion checking is a good way to think of error handling for this (does row count in a equal row count in b, is A:B relationship really 1:1).

Sounds good!  But I'd like to have a more concrete example...particularly for feeding me the basics of what specific errors were generated.

I'm trying to avoid learning ALL the SSIS diagnostic approaches, just for the purpose of picking one good "all around" approach.

Update

Per Nick.McDermaid suggestion, in the SSISDB DB I run this:

SELECT * FROM [SSISDB].[catalog].[executions] ORDER BY start_time DESC

This shows to me the packages that I manually executed.  The timestamps correctly reflect when I ran them.  If anything is unusual(?) it is that the reference_id, reference_type and environment_name columns are null. All the other columns have values.

Update #2

I discovered half the answer I'm looking for.  The reason no error information is available, is because by default the SSIS package execution logging level is "none".  I had to change the logging level.

Nick.McDermaid gave me the rest of the answering by explaining that I don't need to dive into OnError tooling or SSIS logging provider tooling.


问:
2D JTextField array setText using MouseClicked/MousePressed
So I have a JTextField array called fields and I have a string called value (the value of value is replaced when I click on a button). What I want is when I click on one of the JTextFields, I want to put the value in it (using setText, maybe).

```<code>private JTextField[][] fields;
fields = new JTextField[totalX][totalY];
</code>```

Is there a way to do this with a MouseClicked/MousePressed event. Any help is appreciated. Thank you.

答:
Use FocusListener instead of mouse listener. Example:

```<code>JTextField field = new JTextField();
        field.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                field.setText(value);
            }
        });
</code>```

Tutorial - https://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html

Body:
So I have a JTextField array called fields and I have a string called value (the value of value is replaced when I click on a button). What I want is when I click on one of the JTextFields, I want to put the value in it (using setText, maybe).

private JTextField[][] fields;
fields = new JTextField[totalX][totalY];

Is there a way to do this with a MouseClicked/MousePressed event. Any help is appreciated. Thank you.

Body:
Use FocusListener instead of mouse listener. Example:

JTextField field = new JTextField();
        field.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                field.setText(value);
            }
        });

Tutorial - https://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html


问:
Need to know the right way to scan infected website files
My website index.php and htaccess. file got infected and another PHP file of plugin and the website is down now. See the snapshot in this link [https://drive.google.com/open?id=0B6wLmLAtHwZCZnhmV0QzdDMyTW8][1]

could you tell my the way to scan these files? I have scanned with some free antivirus but it is not showing any virus infection. Help to solve this issue.

答:
If your admin panel is accessible, try adding this plugin! It will scan all the files for malware and provide you the full scan report.

Hope this will help!


问:
Click expand on html
I want to do Expand/collapse on click (See pic below).

When a person clicks on the PLUS(+) sign, it expands and the signs change itself to Minus(-) sign and when a person clicks on Minus Sign it Collapse and again changes to Plus Sign.

Here is the Image,

答:
Your image says you want something like JSON Tree.

you can do this by using several Jquery plugins. here is the one - github link, Z-Tree

Title: Click expand on html


问:
Firebase Query for Reference: true
I'm having trouble fetching data on firebase with complex structure.
I have a structure like this:

```<code>place1: {
 visits: {
  user1: true,
  user2: true,
  user3: true,
  user4: true
 }
},
place2: {
 visits: {
  user1: true,
  user3: true,
  user4: true
 }
},
place3: {
 visits: {
  user2: true,
  user3: true,
  user4: true
 }
}
</code>```

How do you query all the users that has been to all the places?

Thank you so much for your help!

答:
Your current data structure allows you to efficiently fine all users that have been to a specific place. It does not allow you to efficiently query all places that a specific user has been to.

To allow that second query, you should add a second data structure:

```<code>user1: {
  place1: true,
  place2: true
},
user2: {
  place1: true,
},
user3: {
  place1: true,
  place3: true
},
user4: {
  place1: true,
  place2: true,
  place3: true,
  place4: true
}
</code>```

With this additional structure (often called an inverted index) in place, you can find the places each user went to.

Since you now have two structures, you will need to ensure you add each visit to both places. A single multi-location update can accomplish that:

```<code>function recordVisitor(uid, placeid) {
  var updates = {};
  updates[`/userVisits/${uid}/${placeid}`] = true;
  updates[`placeVisitors/${placeid}/${uid}`] = true;
  firebase.database().ref().update(updates);
}
</code>```

Also see my answer for a related use-case (querying items in categories) that also requires an inverted index: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value

Title: Firebase Query for Reference: true

Body:
I'm having trouble fetching data on firebase with complex structure.
I have a structure like this:

place1: {
 visits: {
  user1: true,
  user2: true,
  user3: true,
  user4: true
 }
},
place2: {
 visits: {
  user1: true,
  user3: true,
  user4: true
 }
},
place3: {
 visits: {
  user2: true,
  user3: true,
  user4: true
 }
}

How do you query all the users that has been to all the places?

Thank you so much for your help!

Body:
Your current data structure allows you to efficiently fine all users that have been to a specific place. It does not allow you to efficiently query all places that a specific user has been to.

To allow that second query, you should add a second data structure:

user1: {
  place1: true,
  place2: true
},
user2: {
  place1: true,
},
user3: {
  place1: true,
  place3: true
},
user4: {
  place1: true,
  place2: true,
  place3: true,
  place4: true
}

With this additional structure (often called an inverted index) in place, you can find the places each user went to.

Since you now have two structures, you will need to ensure you add each visit to both places. A single multi-location update can accomplish that:

function recordVisitor(uid, placeid) {
  var updates = {};
  updates[`/userVisits/${uid}/${placeid}`] = true;
  updates[`placeVisitors/${placeid}/${uid}`] = true;
  firebase.database().ref().update(updates);
}

Also see my answer for a related use-case (querying items in categories) that also requires an inverted index: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value


问:
change bootstrap progress bar background (not the bar, but the bars Background)
Currently I am using a bootstrap progress bar

```<code><div class="progress">
 <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
60%
 </div>
</div>
</code>```

the default color of the bar is blue, I have managed to change this.

However, the default background of the not filled in part is white with  grey radients, how can i change this to my own colour?

答:
You just need to put background color on progress to surround the bar:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

60%

```

Body:
Currently I am using a bootstrap progress bar

60%

the default color of the bar is blue, I have managed to change this.

However, the default background of the not filled in part is white with  grey radients, how can i change this to my own colour?

Body:
You just need to put background color on progress to surround the bar:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="progress bg-warning">
 <div class="progress-bar bg-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
60%
 </div>
</div>


问:
Live Template not working in Kotlin
Hope you have worked with Live Templates which is given by Android by default.

Like:

```<code>Generate debug log statement: "logd"+TAB
Generate error log statement: "loge"+TAB
Generate info log statement: "logi"+TAB
Generate TAG declaration: "logt"+TAB
Generate parameter logging: "logm"+TAB
Generate method return log: "logr"+TAB
</code>```

Which it is not available in KOTLIN?

Is it not available in Android Studio 3.0 Canary Version?

答:
Yet not added log template in Kotlin Live templates section in Android Studio.

Settings -> Editor -> Live Templates -> Kotlin for kotlin templates.

Settings -> Editor -> Live Templates -> AndroidLog for AndroidLog  templates

.

So you can't get the same AndroidLog templates in Kotlin code.

So now Question is How to use same Log Functions using templates in Kotlin?

Ans: You can add same Log templates (AndroidLog Templates) in Kotlin Templates section in Android studio as below example.

Then It will be available in your Kotlin code!

I hope in this way you can get an advantage of Log functions templates in Kotlin.

Title: Live Template not working in Kotlin

Body:
Hope you have worked with Live Templates which is given by Android by default.

Like:

Generate debug log statement: "logd"+TAB
Generate error log statement: "loge"+TAB
Generate info log statement: "logi"+TAB
Generate TAG declaration: "logt"+TAB
Generate parameter logging: "logm"+TAB
Generate method return log: "logr"+TAB

Which it is not available in KOTLIN?

Is it not available in Android Studio 3.0 Canary Version?


问:
Blending semi-transparent bitmaps containing text with Graphics32
I'm trying to implement a layered painting system inside one of our internal components and I have problems blending bitmaps containing text.

Following code fragment shows the problem:

```<code>uses
  GR32;

procedure DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  bmp1.SaveToFile('c:\0\bmp1.bmp');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  bmp2.Font.Size := -16;
  bmp2.Font.Color := clBlack;
  bmp2.TextOut(2, 50, 'Red');

  bmp2.SaveToFile('c:\0\bmp2.bmp');

  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  bmp1.SaveToFile('c:\0\bmpcombined.bmp');

  bmp1.Free;
  bmp2.Free;
end;
</code>```

Resulting images:

bmp1:
bmp2:
bmpcombined:

As you can see, text is painted in black on bmp and bmp2, but appears white on bmpcombined.

I'm guessing the problem lies in TextOut which maps to Windows.ExtTextOut (via GR32_Backends_VCL.pas, TGDIBackend.Textout). That method doesn't handle transparency and paints text with alpha 00 (color is $000000 instead of $FF000000).

As a quick fix, setting bmp2.Font.Color to $FF000000 doesn't help.

```<code>bmp2.Font.Color := TColor(clBlack32);
</code>```

I am using fresh sources from GitHub

How should I paint a non-transparent text on a semi-transparent background so that I could blend this into a larger picture?

答:
As far as I remember the TextOut function was only meant as a direct way to add some text to the bitmap, lacking all the fixes you mentioned above.

In order to remain full control over transparency you might want to use

```<code>procedure TBitmap32.RenderText(X, Y: Integer; const Text: string; AALevel: Integer; Color: TColor32);
</code>```

instead.

It uses the techniques you mentioned in your own answer, but on a more sophisticated level. It also allows you to use anti-aliasing (based on oversampling), but today it's not actually recommended to use any other anti-aliasing technique other than what the font-engine outputs (to take full advantage of font-hinting).

As you are using the latest source code you could also consider to use VPR to render the text (see example 'TextVPR'). It converts the outline of the text as vectors and use the vector drawing capabilities of Graphics32 (by default the engine 'VPR' is used, hence the name) to render it onto the screen. There's also a stripped down engine of AGG included, which itself is based on the FreeType1 engine, which might be slightly faster for fonts.

Speaking of performance: Keep in mind that every other approach than TextOut will obviously decrease the performance. So if you aim for high performance might better cook your own code (based on TextOut).

Otherwise the TextVPR approach leaves you with more freedom, especially when it comes to filling the text (with a gradient for example) or transforming the text (to a curve or such).

Body:
I'm trying to implement a layered painting system inside one of our internal components and I have problems blending bitmaps containing text.

Following code fragment shows the problem:

uses
  GR32;

procedure DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  bmp1.SaveToFile('c:\0\bmp1.bmp');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  bmp2.Font.Size := -16;
  bmp2.Font.Color := clBlack;
  bmp2.TextOut(2, 50, 'Red');

  bmp2.SaveToFile('c:\0\bmp2.bmp');

  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  bmp1.SaveToFile('c:\0\bmpcombined.bmp');

  bmp1.Free;
  bmp2.Free;
end;

Resulting images:

bmp1:
bmp2:
bmpcombined:

As you can see, text is painted in black on bmp and bmp2, but appears white on bmpcombined.

I'm guessing the problem lies in TextOut which maps to Windows.ExtTextOut (via GR32_Backends_VCL.pas, TGDIBackend.Textout). That method doesn't handle transparency and paints text with alpha 00 (color is $000000 instead of $FF000000).

As a quick fix, setting bmp2.Font.Color to $FF000000 doesn't help.

bmp2.Font.Color := TColor(clBlack32);

I am using fresh sources from GitHub

How should I paint a non-transparent text on a semi-transparent background so that I could blend this into a larger picture?

Body:
As far as I remember the TextOut function was only meant as a direct way to add some text to the bitmap, lacking all the fixes you mentioned above.

In order to remain full control over transparency you might want to use

procedure TBitmap32.RenderText(X, Y: Integer; const Text: string; AALevel: Integer; Color: TColor32);

instead.

It uses the techniques you mentioned in your own answer, but on a more sophisticated level. It also allows you to use anti-aliasing (based on oversampling), but today it's not actually recommended to use any other anti-aliasing technique other than what the font-engine outputs (to take full advantage of font-hinting).

As you are using the latest source code you could also consider to use VPR to render the text (see example 'TextVPR'). It converts the outline of the text as vectors and use the vector drawing capabilities of Graphics32 (by default the engine 'VPR' is used, hence the name) to render it onto the screen. There's also a stripped down engine of AGG included, which itself is based on the FreeType1 engine, which might be slightly faster for fonts.

Speaking of performance: Keep in mind that every other approach than TextOut will obviously decrease the performance. So if you aim for high performance might better cook your own code (based on TextOut).

Otherwise the TextVPR approach leaves you with more freedom, especially when it comes to filling the text (with a gradient for example) or transforming the text (to a curve or such).


问:
Lodash - Retrieve an array of values for all object properties
I have something like

```<code>const payload = [{'name':'john doe', 'company': 'abc', 'age': 35},
                 {'name':'jane doe', 'company': 'def', 'age': 36}]

_.map(users, "name") => ['john doe', 'jane doe']
_.map(users, "company") => ['abc', 'def']
</code>```

I want to have one call to retrieve the name, company and age from the payload. I don't want to make 3 calls with the map function. How can I do this? Because my payload is huge with a lot of properties.

Thanks!

答:
Using lodash, you can map the objects to their values, and unzip the result:

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35}, {'name':'jane doe', 'company': 'def', 'age': 36}];

const result = _(payload)
  .map(_.values) // map to value arrays
  .unzip() // unzip the arrays
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

The same idea works without lodash by mapping the objects into value arrays, and then transposing the values using reduce:

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35}, {'name':'jane doe', 'company': 'def', 'age': 36}];

const result = payload
  .map(Object.values) // map to value arrays
  .reduce((t, arr) => { // transpose the arrays
    arr.forEach((v, i) => (t[i] || (t[i] = [])).push(v));

    return t;
  }, []);

console.log(result);```

Body:
I have something like

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35},
                 {'name':'jane doe', 'company': 'def', 'age': 36}]

_.map(users, "name") => ['john doe', 'jane doe']
_.map(users, "company") => ['abc', 'def']

I want to have one call to retrieve the name, company and age from the payload. I don't want to make 3 calls with the map function. How can I do this? Because my payload is huge with a lot of properties.

Thanks!

Body:
Using lodash, you can map the objects to their values, and unzip the result:

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35}, {'name':'jane doe', 'company': 'def', 'age': 36}];

const result = _(payload)
  .map(_.values) // map to value arrays
  .unzip() // unzip the arrays
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

The same idea works without lodash by mapping the objects into value arrays, and then transposing the values using reduce:

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35}, {'name':'jane doe', 'company': 'def', 'age': 36}];

const result = payload
  .map(Object.values) // map to value arrays
  .reduce((t, arr) => { // transpose the arrays
    arr.forEach((v, i) => (t[i] || (t[i] = [])).push(v));

    return t;
  }, []);

console.log(result);


问:
Differences between express.Router and app.get?
I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see when to use a route handler or when to use express.Router.

As I could see, if I want to show a page or something when the user hits /show for example I should use:

```<code>var express = require('express')
var app = express()
app.get("/show", someFunction)
</code>```

At the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?

If this is the way to do it in Express 4, what is express.Router used for?

I read almost the same example as above but using express.Router:

```<code>var express = require('express');
var router = express.Router();
router.get("/show", someFunction)
</code>```

So, what's the difference between both examples?

Which one should I use if I just want to do a simple testing website?

答: using app.js to write routes means that they are accessible to all the users as app.js is loaded on application start. However, putting routes in express.router() mini apps protect and restrict their accessibility.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see when to use a route handler or when to use express.Router.

As I could see, if I want to show a page or something when the user hits /show for example I should use:

var express = require('express')
var app = express()
app.get("/show", someFunction)

At the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?

If this is the way to do it in Express 4, what is express.Router used for?

I read almost the same example as above but using express.Router:

var express = require('express');
var router = express.Router();
router.get("/show", someFunction)

So, what's the difference between both examples?

Which one should I use if I just want to do a simple testing website?


问:
swagger-codegen client: How to include jackson annotations on models
I'm using swagger-codegen to generate a rest client, but I get a problem, the service I'm consuming returns a model with an inheritance, the API model looks like this:

```<code>public class Person
{
    private List<Book> books;
    ...
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typeClass")
@JsonSubTypes({ @JsonSubTypes.Type(value = Magazine.class) })
public class Book
{
    //some prop
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typeClass")
public class Magazine extends Book
{
    //some prop
}
</code>```

The API model is annotated with jackson annotations to deal with inheritance. The API works ok.
When I generate the client, the client models don't have the jackson annotations, so when I use the generated client to consume the API, it always deserializate using the Book class. It doesn't "see" the Magazine class. I think it's because the generated model does'nt have the jackson annotations to deal with inheritance.

How can I config the swagger-codegen to add the jackson annotations to the model.

Thanks a lot...

答:
Add the following line of code in your plugin configuration in pom.xml

<'library>$libraryValue<'/library>

$libraryValue can be based on which library you are using in your dependencies. Either jersey one if you are using Jersey 1.x.x or jersey2 if you are using Jersey 2.x.x.

Thanks https://stackoverflow.com/users/3695939/moondaisy for the headstart that you have provided.

Body:
I'm using swagger-codegen to generate a rest client, but I get a problem, the service I'm consuming returns a model with an inheritance, the API model looks like this:

public class Person
{
    private List<Book> books;
    ...
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typeClass")
@JsonSubTypes({ @JsonSubTypes.Type(value = Magazine.class) })
public class Book
{
    //some prop
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typeClass")
public class Magazine extends Book
{
    //some prop
}

The API model is annotated with jackson annotations to deal with inheritance. The API works ok.
When I generate the client, the client models don't have the jackson annotations, so when I use the generated client to consume the API, it always deserializate using the Book class. It doesn't "see" the Magazine class. I think it's because the generated model does'nt have the jackson annotations to deal with inheritance.

How can I config the swagger-codegen to add the jackson annotations to the model.

Thanks a lot...


问:
.NET application deployment Error in IIS
When I am trying to deploy a .net application in the IIS Server I am getting an error as Configuration settings do not match. Please help me with this.

答:
The error is specifically to do with 'client impersonation'. I had the error on one machine but not on another. By comparing settings I worked out the difference.

Start IIS Manager. Select the server in the left pane and double-click 'Authentication' under the IIS group in the central pane. Select ASP.NET Impersonation and select 'Disable' at the top of the right pane.


问:
AWS SQS Retry Multiple times
I am working on a requirement that asks me to call a specific endpoint after a successful to get some data. We achieved that using a SNS topic posted to a SQS queue which in turn calls an endpoint.
SNS -> SQS -> My Endpoint (Process Q Message) -> Calls External Endpoint to get data.

Now, we have found out that data is not available immediately after order is processed and now the requirement is to keep trying every 30 seconds for 5 times.

Is there any way we can achieve this?

Right now, I have made it such that My endpoint which process the message from Queue always returns an error so that the message is retried.

I have the visibility timeout set to 30 seconds so that the message is re-tried every 30 seconds for 5 times.

Is there a better way to achieve what I want with my existing setup?
Please help.

答:
Why not publish a message when said data is available, and then use that message only as the trigger? Then, the SQS message won't fail the first time.

If for some reason that isn't possible (shouldn't really be the case but YNK),
then yeah just throw an error as you did, and it will retry. It should work.

Title: AWS SQS Retry Multiple times


问:
GWT Cell Browser Selection
Does anybody know how to attach a selection model to a cell browser so that I can get the object being selected.

Thanks

答:
From the example of GWT showcase:

Create your selection model:

```<code>final MultiSelectionModel<YourKeyProvider> selectionModel = new MultiSelectionModel<YourKeyProvider>(fKeyProvider);
</code>```

Add it to the browser:

```<code>CellBrowser cellBrowser = new CellBrowser(new ContactTreeViewModel(selectionModel), null);
</code>```

Use getSelectedSet() to retrieve the current selected items.

Title: GWT Cell Browser Selection

Body:
From the example of GWT showcase:

Create your selection model:

final MultiSelectionModel<YourKeyProvider> selectionModel = new MultiSelectionModel<YourKeyProvider>(fKeyProvider);

Add it to the browser:

CellBrowser cellBrowser = new CellBrowser(new ContactTreeViewModel(selectionModel), null);

Use getSelectedSet() to retrieve the current selected items.


问:
How can I transform a matrix so that I can plot using ggplot
I have a matrix in R that I can plot using matplot however it is hard to customize the plot. I would like to plot using the R package ggplot however it will not work using a matrix. I am not sure what transformations are required of the matrix to allow the data to work with ggplot.

Thanks for any help.

答:
you need to convert the matrix to a data frame</p>

```<code>    mat  = cbind(index = seq(1:10), price=7+rnorm(10))
    df = as.data.frame(mat)
    library(ggplot2)
    ggplot(df) + geom_line(aes(x = index, y = price))
</code>```

Body:
you need to convert the matrix to a data frame

    mat  = cbind(index = seq(1:10), price=7+rnorm(10))
    df = as.data.frame(mat)
    library(ggplot2)
    ggplot(df) + geom_line(aes(x = index, y = price))


问:
Regex for a random set of chars and digits
I am looking for a regex that matches only when it sees a string that is randomly filled by digits and chars.

For example, adfak332arg3 is allowed but 332352 and fagaaah are not allowed. .*[^\\s] looks fine for strings with only chars but how to fix it to accepts the desired strings and refuses the other two types?

答:
If you need just a mixed string of characters A-Z, a-z and 0-9 you can use:

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])$
</code>```

If you want to force the string to have a minimum number of characters in your string you can use (e.g. minimum 8 in the string):

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$
</code>```

If you want to have a string length from min-length to max-length then use (e.g. string of at least 5 characters and max 20 characters):

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{5,20}$
</code>```

Body:
If you need just a mixed string of characters A-Z, a-z and 0-9 you can use:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])$

If you want to force the string to have a minimum number of characters in your string you can use (e.g. minimum 8 in the string):

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$

If you want to have a string length from min-length to max-length then use (e.g. string of at least 5 characters and max 20 characters):

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{5,20}$


问:
how to insert data from sql server to power bi graph after publish on web
i am using power bi report in my project but i need my graph be change according to SQL server data. it means when we will insert new data in SQL server it effect my graph.</p>

答:
You can use the on-premises Gateway to refresh data in a published Power BI data set with on-premise data like SQL Server data. Take a look at https://powerbi.microsoft.com/en-us/gateway/

The gateway is free, there is a personal and an enterprise flavor and it should run on a machine that is always on, so you can schedule data refresh to occur automatically.


问:
Replication not working for CouchDB database containing audio/video files
We are using CouchDB 2.0 for storing files (.txt, .doc, .xls, .pdf, .mp3, .mp4, .zip). Files are uploaded and stored on CouchDB from our web application. Maximum upload size for a file being uploaded is 500 MB.

We want to backup CouchDB on regular basis from production server to backup server machine having CouchDB installed. We are using replication technique supported by CouchDB for backing up the data.

Following curl command works for replicating database:

```<code>curl -H "Content-Type: application/json" -X POST "http://localhost:5984/_replicate" -d {"source":"http://user:password@targetIP:5984/dbname","target":"sampledb","continuous":true}
</code>```

Above command works well for replicating database that has all documents with text file attachments. But it does not work for database having documents with video or audio or pdf files as attachments.

Here are details about this problem - If a text file upto 500MB size is uploaded on CouchDB, it gets stored with compressed size much lesser than 500MB. And if CouchDB has only text files stored,  replication works well without any problem. But if any media file, pdf or zip file is uploaded on CouchDB, it gets stored but without any compression, and CouchDB with these files does not replicate successfully. This typically happens when media files with more than 5mb are uploaded.

As a work around, we added  video/*  in compressible_types option from default.ini file. But still replicating db with documents having media attachment doesn't work.

Does anyone know about how to replicate CouchDB in such a case?

Any help is really appreciable.

Thanking you,

Jaqen H'ghar

答:
This issue is solved by adding following option in local.ini settings file for couchDB. This file is present at location CouchDB\etc.</p>

<p>[fabric]
request_timeout = infinity </p>

Body:
We are using CouchDB 2.0 for storing files (.txt, .doc, .xls, .pdf, .mp3, .mp4, .zip). Files are uploaded and stored on CouchDB from our web application. Maximum upload size for a file being uploaded is 500 MB.

We want to backup CouchDB on regular basis from production server to backup server machine having CouchDB installed. We are using replication technique supported by CouchDB for backing up the data.

Following curl command works for replicating database:

curl -H "Content-Type: application/json" -X POST "http://localhost:5984/_replicate" -d {"source":"http://user:password@targetIP:5984/dbname","target":"sampledb","continuous":true}

Above command works well for replicating database that has all documents with text file attachments. But it does not work for database having documents with video or audio or pdf files as attachments.

Here are details about this problem - If a text file upto 500MB size is uploaded on CouchDB, it gets stored with compressed size much lesser than 500MB. And if CouchDB has only text files stored,  replication works well without any problem. But if any media file, pdf or zip file is uploaded on CouchDB, it gets stored but without any compression, and CouchDB with these files does not replicate successfully. This typically happens when media files with more than 5mb are uploaded.

As a work around, we added  video/*  in compressible_types option from default.ini file. But still replicating db with documents having media attachment doesn't work.

Does anyone know about how to replicate CouchDB in such a case?

Any help is really appreciable.

Thanking you,

Jaqen H'ghar

Body:
This issue is solved by adding following option in local.ini settings file for couchDB. This file is present at location CouchDB\etc.

[fabric]
request_timeout = infinity


问:
Behavior when trying to change values of global and local const in C++
I'm learning C++ from past few days and when learning about the const qualifier tried the below:

```<code>const int m = 10;

int main()
{
    int* lptr;
    int* gptr;
    const int i = 20;
    lptr = (int *)&i;
    *lptr = 40; //line 1
    cout<<i<<endl;
    cout<<*lptr<<endl;

    *gptr = (int*)&m;
    *gptr = 50; //line 2
    cout<<m<<endl;
    cout<<*gptr<<endl;
}
</code>```

Here, since I'm casting the const int* to int* explicitly, the code compilation is perfectly alright. In line 1, I'm surprised to see that there is no run time error(access violation). But in line 2 there is a run time error saying write access violation (which is expected as const variables are placed in ro memory). But here why the local const variable is allowed to be modified through lptr. Is there nothing like a read only memory on the stack also? (and if it doesn't then how safe is using const local variables as it can be modified with a pointer)

*I'm using MSVC++ 14.0 *

I know that const variables are not meant to be modified, but since I'm leaning from basics I'm exploring the different ways

答: Just because you can cast away const and then write to a const variable through a pointer to non-const does not make it legal. In fact it is undefined behaviour and your program is ill formed and has no meaning. The compiler is free to generate whatever code it feels like in that case.

Body:
I'm learning C++ from past few days and when learning about the const qualifier tried the below:

const int m = 10;

int main()
{
    int* lptr;
    int* gptr;
    const int i = 20;
    lptr = (int *)&i;
    *lptr = 40; //line 1
    cout<<i<<endl;
    cout<<*lptr<<endl;

    *gptr = (int*)&m;
    *gptr = 50; //line 2
    cout<<m<<endl;
    cout<<*gptr<<endl;
}

Here, since I'm casting the const int* to int* explicitly, the code compilation is perfectly alright. In line 1, I'm surprised to see that there is no run time error(access violation). But in line 2 there is a run time error saying write access violation (which is expected as const variables are placed in ro memory). But here why the local const variable is allowed to be modified through lptr. Is there nothing like a read only memory on the stack also? (and if it doesn't then how safe is using const local variables as it can be modified with a pointer)

*I'm using MSVC++ 14.0 *

I know that const variables are not meant to be modified, but since I'm leaning from basics I'm exploring the different ways


问:
White Screen when switching between Swing frames under Linux
I'm porting a Java Swing application from Windows to Linux.
On Linux - when the application switches between JFrames, a blink of white screen appears for a split of a second.
This doesn't happen with the same application on Windows.
I believe that the white screen appears while the new frame is repainted.
Any idea how to fix it?

Here's the code that switches between frames (pages):

```<code>public void goToPage(int page) {
    screens[page].bringToFront(true);
    if (page != currentFrame) {
        screens[page].setVisibility(true);
        screens[currentFrame].setVisibility(false);
        currentFrame = page;
    }
}
</code>```

答: Try a CardLayout instead.  </p>

Body:
I'm porting a Java Swing application from Windows to Linux.
On Linux - when the application switches between JFrames, a blink of white screen appears for a split of a second.
This doesn't happen with the same application on Windows.
I believe that the white screen appears while the new frame is repainted.
Any idea how to fix it?

Here's the code that switches between frames (pages):

public void goToPage(int page) {
    screens[page].bringToFront(true);
    if (page != currentFrame) {
        screens[page].setVisibility(true);
        screens[currentFrame].setVisibility(false);
        currentFrame = page;
    }
}

Body: Try a CardLayout instead.


问:
Migration from GCM to FCM needed?
Google just announced that Google Cloud Messaging is now Firebase Cloud Messaging.  What does this mean for existing users of GCM and what migration (if any) are needed?</p>

答:
Google have expanded GCM to send messages to multiple platforms beyond Android: iOS and Chrome. Firebase is known for being cross platform, so FCM now makes a natural fit in the Firebase suite of features designed for Android, iOS, and mobile web.

FCM

it is advance/improved version of GCM but with new brandname Firebase

very easy/Simplified client development

Server-less console where anyone can send notifications to specific device

Notification payload: 4KB, Message payload: 2KB. Note that the notification includes device and app information too.

Stores 100 notification/messages per device if the device is offline.

Title: Migration from GCM to FCM needed?


问:
NSIS – Error MySql with Redirection using nsEXEC::ExecToStack --- Why is ExecToLog vs ExecToStack different errors
I have search forums over too many days the test results can be repeated.
[QUESTION]
What causes the MySQL failure and/or the CMD parsing error of directory name?
[NSIS Script follows]

```<code>importdbs:
DetailPrint "IMPORT SQL files to db=$dbname User=$login Pswd=$password"
StrCpy $1 "$folder\bin\mysql.exe"
StrCpy $2 "$srcepath$srcescript"

DetailPrint "MySqlDir: $1 input: $2"
ClearErrors

nsExec::ExecToStack /OEM '"$SYSDIR\cmd.exe" /C "$1" -u$root -p -v -D $dbname < "$2" > "c:\_temp-c\ckprnout.txt"'

Pop $3  # Get Results

StrCmp "error" $3 +1 +2
DetailPrint "IMPORT return-error: $3"
DetailPrint "IMPORT return-OK: $3"
</code>```

[RESULTS (test01) from nsis log panel]:

IMPORT SQL files to db=demo User=root Pswd=
…. Password entered ….
MySqlDir: c:\PROGRA~1\MySQL\MySQL Server 5.7\bin\mysql.exe
         input: c:_temp-c\dumps\dump-20170604-demo.sql

IMPORT return-OK: 1 <=error

[NOTE:]
changing nsExec::ExecToStack .... to nscExec::ExecToLog ....
Yields different Error

[RESULTS (test02) from nsis log panel]:

IMPORT SQL files to db=demo User=root Pswd=
…. Password entered ….
MySqlDir: c:\PROGRA~1\MySQL\MySQL Server 5.7\bin\mysql.exe
         input: c:_temp-c\dumps\dump-20170604-demo.sql

'c:\PROGRA~1\MySQL\MySQL' is not recognized as an internal or external command, operable program or batch file.

答:
Maybe this will help. Hope it works for you.</p>

```<code>importdbs:
DetailPrint "IMPORT SQL files to db=$dbname User=$login Pswd=$password"
StrCpy $1 "$folder\bin\mysql.exe"
StrCpy $2 "$srcepath$srcescript"

System::Call 'kernel32::GetLongPathName(t r1, t .r3, i ${NSIS_MAX_STRLEN}) i .r4'
StrCmp $4 error +2
StrCpy $1 $3

DetailPrint "MySqlDir: $1 input: $2"
ClearErrors

ReadEnvStr $R0 COMSPEC
ExecDos::Exec /TOSTACK `"$R0" /c "$1" -u$root -p -v -D $dbname < "$2" > "c:\_temp-c\ckprnout.txt"`

Pop $5  # Get Results

StrCmp "error" $5 +1 +2
DetailPrint "IMPORT return-error: $5"
DetailPrint "IMPORT return-OK: $5"
</code>```

Body:
I have search forums over too many days the test results can be repeated.
[QUESTION]
What causes the MySQL failure and/or the CMD parsing error of directory name?
[NSIS Script follows]

importdbs:
DetailPrint "IMPORT SQL files to db=$dbname User=$login Pswd=$password"
StrCpy $1 "$folder\bin\mysql.exe"
StrCpy $2 "$srcepath$srcescript"

DetailPrint "MySqlDir: $1 input: $2"
ClearErrors

nsExec::ExecToStack /OEM '"$SYSDIR\cmd.exe" /C "$1" -u$root -p -v -D $dbname < "$2" > "c:\_temp-c\ckprnout.txt"'

Pop $3  # Get Results

StrCmp "error" $3 +1 +2
DetailPrint "IMPORT return-error: $3"
DetailPrint "IMPORT return-OK: $3"

[RESULTS (test01) from nsis log panel]:

IMPORT SQL files to db=demo User=root Pswd=
…. Password entered ….
MySqlDir: c:\PROGRA~1\MySQL\MySQL Server 5.7\bin\mysql.exe
         input: c:_temp-c\dumps\dump-20170604-demo.sql

IMPORT return-OK: 1 <=error

[NOTE:]
changing nsExec::ExecToStack .... to nscExec::ExecToLog ....
Yields different Error

[RESULTS (test02) from nsis log panel]:

IMPORT SQL files to db=demo User=root Pswd=
…. Password entered ….
MySqlDir: c:\PROGRA~1\MySQL\MySQL Server 5.7\bin\mysql.exe
         input: c:_temp-c\dumps\dump-20170604-demo.sql

'c:\PROGRA~1\MySQL\MySQL' is not recognized as an internal or external command, operable program or batch file.

Body:
Maybe this will help. Hope it works for you.

importdbs:
DetailPrint "IMPORT SQL files to db=$dbname User=$login Pswd=$password"
StrCpy $1 "$folder\bin\mysql.exe"
StrCpy $2 "$srcepath$srcescript"

System::Call 'kernel32::GetLongPathName(t r1, t .r3, i ${NSIS_MAX_STRLEN}) i .r4'
StrCmp $4 error +2
StrCpy $1 $3

DetailPrint "MySqlDir: $1 input: $2"
ClearErrors

ReadEnvStr $R0 COMSPEC
ExecDos::Exec /TOSTACK `"$R0" /c "$1" -u$root -p -v -D $dbname < "$2" > "c:\_temp-c\ckprnout.txt"`

Pop $5  # Get Results

StrCmp "error" $5 +1 +2
DetailPrint "IMPORT return-error: $5"
DetailPrint "IMPORT return-OK: $5"