问:
Having 'certificate verify failed' error when registering a model on Azure
Today, I got an error when I wanted to register a new model on Azure work space. This error wasn't happening before! The only change that I have is the model itself but the code is the same:

```<code>from azureml.core import Workspace
from azureml.core.compute import AksCompute, ComputeTarget
from azureml.core.webservice import Webservice, AksWebservice
from azureml.core.image import Image
from azureml.core.model import Model
import azureml.core
from azureml.core.workspace import Workspace
from azureml.core.model import Model
ws = Workspace.from_config()
model_reg = Model.register(model_path = "./outputs/model_final",
                       model_name = "ModelX",
                       tags = {'area': "XXX", 'type': "deep"},
                       description = "Model 1",
                       workspace = ws)
</code>```

And here is the error that I got:

```<code>raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='xxx
.blob.core.windows.net', port=443): Max retries exceeded with url: /azureml/Loca
lUpload/190530T093046-fc5a89ca/tfModel.tar.gz?sv=2018-03-28&sr=b&sig=9FFnsaefR9w
PkR%2FvsMlnQYrA2wlnJG7Cu%2BP9%2FePPZEY%3D&st=2019-05-30T08%3A20%3A46Z&se=2019-05
-31T08%3A30%3A46Z&sp=rcw&comp=block&blockid=TURBd01EQXdNREF3TURBd01EQXdNREF3TURB
d01EQXdNREF3TURBd01EQSUzRA%3D%3D (Caused by SSLError(SSLError("bad handshake: Er
ror([('SSL routines', 'tls_process_server_certificate', 'certificate verify fail
ed')],)",),))
</code>```

I tried to update all the python packages and even creating a new conda env with fresh installation of all packages, but still getting this error.

Any help or similar experience?

答:
Just as reference, there may be two reasons cause this issue.

Network issue. The network environment for running this Python script changed. May now the script run through a proxy like Fiddler which not support or enable SSL/TLS feature, or some IP restrictions in your network cause it like the SO thread SSL Certificate error while doing a request via python.

The target site upgraded SSL version. You can follow the SO thread answer Django paypalrestsdk error - OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] to check.

Hope it helps.

Body:
Today, I got an error when I wanted to register a new model on Azure work space. This error wasn't happening before! The only change that I have is the model itself but the code is the same:

from azureml.core import Workspace
from azureml.core.compute import AksCompute, ComputeTarget
from azureml.core.webservice import Webservice, AksWebservice
from azureml.core.image import Image
from azureml.core.model import Model
import azureml.core
from azureml.core.workspace import Workspace
from azureml.core.model import Model
ws = Workspace.from_config()
model_reg = Model.register(model_path = "./outputs/model_final",
                       model_name = "ModelX",
                       tags = {'area': "XXX", 'type': "deep"},
                       description = "Model 1",
                       workspace = ws)

And here is the error that I got:

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='xxx
.blob.core.windows.net', port=443): Max retries exceeded with url: /azureml/Loca
lUpload/190530T093046-fc5a89ca/tfModel.tar.gz?sv=2018-03-28&sr=b&sig=9FFnsaefR9w
PkR%2FvsMlnQYrA2wlnJG7Cu%2BP9%2FePPZEY%3D&st=2019-05-30T08%3A20%3A46Z&se=2019-05
-31T08%3A30%3A46Z&sp=rcw&comp=block&blockid=TURBd01EQXdNREF3TURBd01EQXdNREF3TURB
d01EQXdNREF3TURBd01EQSUzRA%3D%3D (Caused by SSLError(SSLError("bad handshake: Er
ror([('SSL routines', 'tls_process_server_certificate', 'certificate verify fail
ed')],)",),))

I tried to update all the python packages and even creating a new conda env with fresh installation of all packages, but still getting this error.

Any help or similar experience?


来源: stackexchange

问:
Pyspark replace string from column based on pattern from another column
I have a dataframe with a text column and a name column. I would like to check if the name exists in the text column and if it does to replace it with some value.
I was hoping that the following would work:

```<code>df = df.withColumn("new_text",regex_replace(col("text),col("name"),"NAME"))
</code>```

but Column is not iterable so it does not work. Do I have to write a udf to do that? How would that look like?

答:
You are almost close. Here is detailed example with withColumn and selectExpr options:

Sample df

```<code>df = spark.createDataFrame([('This is','This'),
('That is','That'),
('That is','There')],
['text','name'])

#+-------+-----+
#|   text| name|
#+-------+-----+
#|This is| This|
#|That is| That|
#|That is|There|
#+-------+-----+
</code>```

Option 1: withColumn using expr function

```<code>from pyspark.sql.functions import expr, regexp_replace

df.withColumn("new_col1",expr("regexp_replace(text,name,'NAME')")).show()

#+-------+-----+--------+
#|   text| name|new_col1|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+
</code>```

Option 2: selectExpr using regexp_replace

```<code> from pyspark.sql.functions import regexp_replace

df.selectExpr("*",
          "regexp_replace(text,name,'NAME') AS new_text").show()

#+-------+-----+--------+
#|   text| name|new_text|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with a text column and a name column. I would like to check if the name exists in the text column and if it does to replace it with some value.
I was hoping that the following would work:

df = df.withColumn("new_text",regex_replace(col("text),col("name"),"NAME"))

but Column is not iterable so it does not work. Do I have to write a udf to do that? How would that look like?

Body:
You are almost close. Here is detailed example with withColumn and selectExpr options:

Sample df

df = spark.createDataFrame([('This is','This'),
('That is','That'),
('That is','There')],
['text','name'])

#+-------+-----+
#|   text| name|
#+-------+-----+
#|This is| This|
#|That is| That|
#|That is|There|
#+-------+-----+

Option 1: withColumn using expr function

from pyspark.sql.functions import expr, regexp_replace

df.withColumn("new_col1",expr("regexp_replace(text,name,'NAME')")).show()

#+-------+-----+--------+
#|   text| name|new_col1|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+

Option 2: selectExpr using regexp_replace

 from pyspark.sql.functions import regexp_replace

df.selectExpr("*",
          "regexp_replace(text,name,'NAME') AS new_text").show()

#+-------+-----+--------+
#|   text| name|new_text|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+


问:
how to instantiate the imported class in angular
i am working on a angualr weather app.
for which i have created weather class

```<code> export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }
</code>```

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

```<code>weather:Weather;
getWeather():void{
               this.weatherserv.getWeather().subscribe(data=>{
                   this.weather.city=data.location.name;
                  this.weather.condition=data.condition.text;
                   this.weather.condition=data.condition.icon;
                   this.weather.temp=data.current.temp_c;
               })
             }
</code>```

Error i am getting is:

```<code>Error: Cannot set property 'city' of undefined
</code>```

答:
you should try:

```<code>weather= new Weather();
</code>```

or in your case, it's better to use interfaces:

```<code> export interface Weather{
          city?: string;
          condition?: string;
          icon?: string;
          temp?: number;
        }
weather:Weather = {};
</code>```

here i explained why it's better to use interfaces in your case.

Body:
i am working on a angualr weather app.
for which i have created weather class

 export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

weather:Weather;
getWeather():void{
               this.weatherserv.getWeather().subscribe(data=>{
                   this.weather.city=data.location.name;
                  this.weather.condition=data.condition.text;
                   this.weather.condition=data.condition.icon;
                   this.weather.temp=data.current.temp_c;
               })
             }

Error i am getting is:

Error: Cannot set property 'city' of undefined

Body:
you should try:

weather= new Weather();

or in your case, it's better to use interfaces:

 export interface Weather{
          city?: string;
          condition?: string;
          icon?: string;
          temp?: number;
        }
weather:Weather = {};

here i explained why it's better to use interfaces in your case.


问:
ERROR: Could not get unknown property 'appcompat' for project ':app' of type org.gradle.api.Project
Error rising while Building Gradle of a code I found online.

```<code>    implement "com.android.support:appcompat-v7:$project.appcompat"
    implement "com.android.support:cardview-v7:$project.appcompat"
    implement "com.android.support:recyclerview-v7:$project.appcompat"
    implement "android.arch.lifecycle:runtime:$project.arch"
    implement "android.arch.lifecycle:extensions:$project.arch"
    implement "com.squareup.retrofit2:retrofit:$project.retrofit"
    implement "com.squareup.retrofit2:converter-gson:$project.retrofit"
    annotationProcessor "android.arch.lifecycle:compiler:$project.arch"
    implement "com.android.support.constraint:constraint-layout:$project.constraintLayout"
    implement "com.android.support:support-v4:$project.appcompat"
</code>```

P.S. Problem is solves as i understood how to use a variable in gradle file

答:
You are just missing this field here $project.appcompat. Go find what's the current version and place it there. I believe this will help.

So your code transforms from implement "com.android.support:appcompat-v7:$project.appcompat" to implement "com.android.support:appcompat-v7:1.0.0<or current version>"

Body:
Error rising while Building Gradle of a code I found online.

    implement "com.android.support:appcompat-v7:$project.appcompat"
    implement "com.android.support:cardview-v7:$project.appcompat"
    implement "com.android.support:recyclerview-v7:$project.appcompat"
    implement "android.arch.lifecycle:runtime:$project.arch"
    implement "android.arch.lifecycle:extensions:$project.arch"
    implement "com.squareup.retrofit2:retrofit:$project.retrofit"
    implement "com.squareup.retrofit2:converter-gson:$project.retrofit"
    annotationProcessor "android.arch.lifecycle:compiler:$project.arch"
    implement "com.android.support.constraint:constraint-layout:$project.constraintLayout"
    implement "com.android.support:support-v4:$project.appcompat"

P.S. Problem is solves as i understood how to use a variable in gradle file


问:
Multiple values with a name in custom variable
How can i associate multiple values with a name in custom variable??

value—The value for the custom variable. Required. This is a string that is paired with a name. You can pair a number of values with a custom variable name. The value appears in the table list of the UI for a selected variable name. Typically, you will have two or more values for a given name. For example, you might define a custom variable name gender and supply male and female as two possible values.

This is what i read from google analytics.
I want to ask that if i can do something like this

```<code> _gaq.push(['_setCustomVar',1,'gender','male',2]);
  _gaq.push(['_setCustomVar',1,'gender','female',2]);
</code>```

If this is not the right way to achieve what google analytics says then how will achieve my goal to assign more than one value to a name.

答: Only way to do it is to assign the custom variable and trigger an event or page view for each value. </p>

ContentLicense: CC BY-SA 3.0

Body:
How can i associate multiple values with a name in custom variable??

value—The value for the custom variable. Required. This is a string that is paired with a name. You can pair a number of values with a custom variable name. The value appears in the table list of the UI for a selected variable name. Typically, you will have two or more values for a given name. For example, you might define a custom variable name gender and supply male and female as two possible values.

This is what i read from google analytics.
I want to ask that if i can do something like this

 _gaq.push(['_setCustomVar',1,'gender','male',2]);
  _gaq.push(['_setCustomVar',1,'gender','female',2]);

If this is not the right way to achieve what google analytics says then how will achieve my goal to assign more than one value to a name.


问:
Pass multiple parameters to concurrent.futures.Executor.map?
The concurrent.futures.Executor.map takes a variable number of iterables from which the function given is called. How should I call it if I have a generator that produces tuples that are normally unpacked in place?

The following doesn't work because each of the generated tuples is given as a different argument to map:

```<code>args = ((a, b) for (a, b) in c)
for result in executor.map(f, *args):
    pass
</code>```

Without the generator, the desired arguments to map might look like this:

```<code>executor.map(
    f,
    (i[0] for i in args),
    (i[1] for i in args),
    ...,
    (i[N] for i in args),
)
</code>```

答:
For ProcessPoolExecutor.map():

Similar to map(func, *iterables) except:

the iterables are collected immediately rather than lazily;

func is executed asynchronously and several calls to func may be made
concurrently.

Therefore, the usage of ProcessPoolExecutor.map() is the same as that of Python's build-in map(). Here is the docs:

Return an iterator that applies function to every item of iterable,
yielding the results. If additional iterable arguments are passed,
function must take that many arguments and is applied to the items
from all iterables in parallel.

Conclusion: pass the several parameters to map().

Try running the following snippet under python 3, and you will be quite clear:

```<code>from concurrent.futures import ProcessPoolExecutor

def f(a, b):
    print(a+b)

with ProcessPoolExecutor() as pool:
    pool.map(f, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2))

# 0, 2, 4

array = [(i, i) for i in range(3)]
with ProcessPoolExecutor() as pool:
    pool.map(f, *zip(*array))

# 0, 2, 4
</code>```

Body:
The concurrent.futures.Executor.map takes a variable number of iterables from which the function given is called. How should I call it if I have a generator that produces tuples that are normally unpacked in place?

The following doesn't work because each of the generated tuples is given as a different argument to map:

args = ((a, b) for (a, b) in c)
for result in executor.map(f, *args):
    pass

Without the generator, the desired arguments to map might look like this:

executor.map(
    f,
    (i[0] for i in args),
    (i[1] for i in args),
    ...,
    (i[N] for i in args),
)

Body:
For ProcessPoolExecutor.map():

Similar to map(func, *iterables) except:

the iterables are collected immediately rather than lazily;

func is executed asynchronously and several calls to func may be made
concurrently.

Therefore, the usage of ProcessPoolExecutor.map() is the same as that of Python's build-in map(). Here is the docs:

Return an iterator that applies function to every item of iterable,
yielding the results. If additional iterable arguments are passed,
function must take that many arguments and is applied to the items
from all iterables in parallel.

Conclusion: pass the several parameters to map().

Try running the following snippet under python 3, and you will be quite clear:

from concurrent.futures import ProcessPoolExecutor

def f(a, b):
    print(a+b)

with ProcessPoolExecutor() as pool:
    pool.map(f, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2))

# 0, 2, 4

array = [(i, i) for i in range(3)]
with ProcessPoolExecutor() as pool:
    pool.map(f, *zip(*array))

# 0, 2, 4


问:
Toast in OnPostExecute() once the fragment changes
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

```<code>private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}
</code>```

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

答:
Try this way
Declare a boolean in Fragment_A

```<code>private boolean isFragmentVisible=false;
</code>```

In Fragment_A class

Make this boolean true in onCreateView() of this Fragment_A

```<code>  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.lyourlayout, container, false);
    isFragmentVisible = true;
    return view;
}
</code>```

And make this boolean false in onDestroyView() of this fragment A

```<code>@Override
    public void onDestroyView() {
        super.onDestroyView();
        isFragmentVisible = false;
    }
</code>```

Finally use it in Asyntask of Fragment_A like this

```<code>private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
// swipe layout will not be shown if fragment is not visible or destroyed
        if(isFragmentVisible){
              swipeRefreshLayout.setRefreshing(false);
            }
// toast will be shown no matter what fragment is visible
         Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }

    @Override
    protected void onCancelled() {
       if(isFragmentVisible){
              swipeRefreshLayout.setRefreshing(false);
            }
        //Some stuff
    }
}
</code>```

Body:
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

Body:
Try this way
Declare a boolean in Fragment_A

private boolean isFragmentVisible=false;

In Fragment_A class

Make this boolean true in onCreateView() of this Fragment_A

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.lyourlayout, container, false);
    isFragmentVisible = true;
    return view;
}

And make this boolean false in onDestroyView() of this fragment A

@Override
    public void onDestroyView() {
        super.onDestroyView();
        isFragmentVisible = false;
    }

Finally use it in Asyntask of Fragment_A like this

private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
// swipe layout will not be shown if fragment is not visible or destroyed
        if(isFragmentVisible){
              swipeRefreshLayout.setRefreshing(false);
            }
// toast will be shown no matter what fragment is visible
         Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }

    @Override
    protected void onCancelled() {
       if(isFragmentVisible){
              swipeRefreshLayout.setRefreshing(false);
            }
        //Some stuff
    }
}


问:
How to Draw the Gaussian Blur Effect?
I need to draw the blur effect on the UIView using Objective C.

Here is my design

```<code>    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle: UIBlurEffectStyleExtraLight];

    UIVisualEffectView *contentView = [[UIVisualEffectView alloc] initWithEffect: blurEffect];

    contentView.layer.cornerRadius = 18.0;

    contentView.layer.masksToBounds = YES;

    contentView.backgroundColor = [UIColor whiteColor];

    contentView.userInteractionEnabled = NO;

    contentView.layer.shadowRadius = 10;

    contentView.layer.shadowOpacity = 0.2f;

    contentView.layer.shadowColor = [UIColor whiteColor].CGColor;

    contentView.layer.shadowOffset =  CGSizeZero;

    [contentView setFrame: annotationFrame];

    [contentView setTranslatesAutoresizingMaskIntoConstraints: YES];

    self.contentView = contentView;
</code>```

below screenshot was current output using the above code

I have tried the above code. , but I didn't get the exact blur effect
kindly suggest me to draw this design.

I have updated the below code

```<code>- (void)drawRect:(CGRect)rect {

    [super drawRect: rect]; //i doubt we need a super drarRect here…

    [self drawMarker: self.markerView fillColor: [UIColor whiteColor]];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor slateColor].CGColor);

    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor slateColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }

}
</code>```

I need the blur effect behind my view , kindly advice the me regarding this.

Thank you.

答:
Translating my previous answer from swift to Objective-C we have this

```<code>@implementation UICustomBackgroundButton

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor blueColor].CGColor);
    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor blueColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }
}

@end
</code>```

Result

Title: How to Draw the Gaussian Blur Effect?

Body:
I need to draw the blur effect on the UIView using Objective C.

Here is my design

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle: UIBlurEffectStyleExtraLight];

    UIVisualEffectView *contentView = [[UIVisualEffectView alloc] initWithEffect: blurEffect];

    contentView.layer.cornerRadius = 18.0;

    contentView.layer.masksToBounds = YES;

    contentView.backgroundColor = [UIColor whiteColor];

    contentView.userInteractionEnabled = NO;

    contentView.layer.shadowRadius = 10;

    contentView.layer.shadowOpacity = 0.2f;

    contentView.layer.shadowColor = [UIColor whiteColor].CGColor;

    contentView.layer.shadowOffset =  CGSizeZero;

    [contentView setFrame: annotationFrame];

    [contentView setTranslatesAutoresizingMaskIntoConstraints: YES];

    self.contentView = contentView;

below screenshot was current output using the above code

I have tried the above code. , but I didn't get the exact blur effect
kindly suggest me to draw this design.

I have updated the below code

- (void)drawRect:(CGRect)rect {

    [super drawRect: rect]; //i doubt we need a super drarRect here…

    [self drawMarker: self.markerView fillColor: [UIColor whiteColor]];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor slateColor].CGColor);

    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor slateColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }

}

I need the blur effect behind my view , kindly advice the me regarding this.

Thank you.

Body:
Translating my previous answer from swift to Objective-C we have this

@implementation UICustomBackgroundButton

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor blueColor].CGColor);
    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor blueColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }
}

@end

Result


问:
R Reshape data frame from long to wide format?
What's the best way to convert the data frame below from long to wide format? I tried to use reshape but didn't get the desired results.

```<code>2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90
</code>```

答:
For the sake of completeness, here is a solution which uses data.table's convenient rowid() function.

The crucial point of the question is that the reshaping solely depends on the row position of value within each (year, product) group. rowid(year, product) numbers the rows within each group. So, reshaping essentially becomes a one-liner:

```<code>library(data.table)
dcast(setDT(df1), year + product ~ rowid(year, product, prefix = "col_"))
</code>```

```<code>   year product col_1  col_2 col_3 col_4 col_5
1: 2015  PROD A test1   blue    50    66    66
2: 2018  PROD A test3    red    55    88    90
3: 2018  PROD B test2 yellow    70  88.8  88.8
</code>```

Note that rowid() takes a prefix parameter to ensure that the resulting column names are syntactically correct.

Caveat: This solution assumes that year and product form a unique key for each group.

Data

The data are read as posted by th OP without any modifications to the data. However, this requires a few lines of post-processing:

```<code>library(data.table)
df1 <- fread("
2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90",
      header = FALSE, col.names = c("year", "product", "value"), drop = 2L)[
        , product := paste("PROD", product)][]
</code>```

Body:
What's the best way to convert the data frame below from long to wide format? I tried to use reshape but didn't get the desired results.

2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90

Body:
For the sake of completeness, here is a solution which uses data.table's convenient rowid() function.

The crucial point of the question is that the reshaping solely depends on the row position of value within each (year, product) group. rowid(year, product) numbers the rows within each group. So, reshaping essentially becomes a one-liner:

library(data.table)
dcast(setDT(df1), year + product ~ rowid(year, product, prefix = "col_"))

   year product col_1  col_2 col_3 col_4 col_5
1: 2015  PROD A test1   blue    50    66    66
2: 2018  PROD A test3    red    55    88    90
3: 2018  PROD B test2 yellow    70  88.8  88.8

Note that rowid() takes a prefix parameter to ensure that the resulting column names are syntactically correct.

Caveat: This solution assumes that year and product form a unique key for each group.

Data

The data are read as posted by th OP without any modifications to the data. However, this requires a few lines of post-processing:

library(data.table)
df1 <- fread("
2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90",
      header = FALSE, col.names = c("year", "product", "value"), drop = 2L)[
        , product := paste("PROD", product)][]


问:
Web-scraping articles from WSJ using Beautifulsoup in python 3.7?
I am trying to scrape articles from the Wall Street Journal using Beautifulsoup in Python. However, the code which I am running is executing without any error (exit code 0) but no results. I don't understand what is happening? Why this code is not giving expected results.

I even have paid a subscription.

I know that something is not right but I can't locate the problem.

```<code>import time

import requests

from bs4 import BeautifulSoup

url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31' \
  '&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page={}'

pages = 32
for page in range(1, pages+1):
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select(".items.hedSumm li > a"):
        resp = requests.get(item.get("href"))
        _href = item.get("href")

        try:
            resp = requests.get(_href)
        except Exception as e:
            try:
            resp = requests.get("https://www.wsj.com" + _href)
        except Exception as e:
            continue
    sauce = BeautifulSoup(resp.text,"lxml")
    date = sauce.select("time.timestamp.article__timestamp.flexbox__flex--1")
    date = date[0].text
    tag = sauce.select("li.article-breadCrumb span").text
    title = sauce.select_one("h1.wsj-article-headline").text
    content = [elem.text for elem in sauce.select("p.article-content")]
    print(f'{date}\n {tag}\n {title}\n {content}\n')

    time.sleep(3)
</code>```

As I wrote in the code, I am trying to scrape date, title, tag, and content of all the articles. It would be helpful if I can get suggestions about my mistakes, what should I do to get the desired results.

答:
Replace your code :

```<code>resp = requests.get(item.get("href"))
</code>```

To:

```<code>_href = item.get("href")

try:
    resp = requests.get(_href)
except Exception as e:
    try:
        resp = requests.get("https://www.wsj.com"+_href)
    except Exception as e:
        continue
</code>```

Because most of item.get("href") is not providing proper website url for eg you are getting url like this.

```<code>/news/types/national-security
/public/page/news-financial-markets-stock.html
https://www.wsj.com/news/world
</code>```

Only https://www.wsj.com/news/world is a valid website URL. so you need to concate base URL with _href.

Update:

```<code>import time
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag

url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31' \
  '&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page={}'

pages = 32

for page in range(1, pages+1):
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")

    for item in soup.find_all("a",{"class":"headline-image"},href=True):
        _href = item.get("href")
        try:
            resp = requests.get(_href)
        except Exception as e:
            try:
                resp = requests.get("https://www.wsj.com"+_href)
            except Exception as e:
                continue

        sauce = BeautifulSoup(resp.text,"lxml")
        dateTag = sauce.find("time",{"class":"timestamp article__timestamp flexbox__flex--1"})
        tag = sauce.find("li",{"class":"article-breadCrumb"})
        titleTag = sauce.find("h1",{"class":"wsj-article-headline"})
        contentTag = sauce.find("div",{"class":"wsj-snippet-body"})

        date = None
        tagName = None
        title = None
        content = None

        if isinstance(dateTag,Tag):
            date = dateTag.get_text().strip()

        if isinstance(tag,Tag):
            tagName = tag.get_text().strip()

        if isinstance(titleTag,Tag):
            title = titleTag.get_text().strip()

        if isinstance(contentTag,Tag):
            content = contentTag.get_text().strip()

        print(f'{date}\n {tagName}\n {title}\n {content}\n')
        time.sleep(3)
</code>```

O/P:

```<code>March 31, 2019 10:00 a.m. ET
 Tech
 Care.com Removes Tens of Thousands of Unverified Listings
 The online child-care marketplace Care.com scrubbed its site of tens of thousands of unverified day-care center listings just before a Wall Street Journal investigation published March 8, an analysis shows. Care.com, the largest site in the U.S. for finding caregivers, removed about 72% of day-care centers, or about 46,594 businesses, listed on its site, a Journal review of the website shows. Those businesses were listed on the site as recently as March 1....

Updated March 29, 2019 6:08 p.m. ET
 Politics
 FBI, Retooling Once Again, Sets Sights on Expanding Cyber Threats
 The FBI has launched its biggest transformation since the 2001 terror attacks to retrain and refocus special agents to combat cyber criminals, whose threats to lives, property and critical infrastructure have outstripped U.S. efforts to thwart them. The push comes as federal investigators grapple with an expanding range of cyber attacks sponsored by foreign adversaries against businesses or national interests, including Russian election interference and Chinese cyber thefts from American companies, senior bureau executives...
</code>```

Body:
I am trying to scrape articles from the Wall Street Journal using Beautifulsoup in Python. However, the code which I am running is executing without any error (exit code 0) but no results. I don't understand what is happening? Why this code is not giving expected results.

I even have paid a subscription.

I know that something is not right but I can't locate the problem.

import time

import requests

from bs4 import BeautifulSoup

url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31' \
  '&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page={}'

pages = 32
for page in range(1, pages+1):
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select(".items.hedSumm li > a"):
        resp = requests.get(item.get("href"))
        _href = item.get("href")

        try:
            resp = requests.get(_href)
        except Exception as e:
            try:
            resp = requests.get("https://www.wsj.com" + _href)
        except Exception as e:
            continue
    sauce = BeautifulSoup(resp.text,"lxml")
    date = sauce.select("time.timestamp.article__timestamp.flexbox__flex--1")
    date = date[0].text
    tag = sauce.select("li.article-breadCrumb span").text
    title = sauce.select_one("h1.wsj-article-headline").text
    content = [elem.text for elem in sauce.select("p.article-content")]
    print(f'{date}\n {tag}\n {title}\n {content}\n')

    time.sleep(3)

As I wrote in the code, I am trying to scrape date, title, tag, and content of all the articles. It would be helpful if I can get suggestions about my mistakes, what should I do to get the desired results.

Body:
Replace your code :

resp = requests.get(item.get("href"))

To:

_href = item.get("href")

try:
    resp = requests.get(_href)
except Exception as e:
    try:
        resp = requests.get("https://www.wsj.com"+_href)
    except Exception as e:
        continue

Because most of item.get("href") is not providing proper website url for eg you are getting url like this.

/news/types/national-security
/public/page/news-financial-markets-stock.html
https://www.wsj.com/news/world

Only https://www.wsj.com/news/world is a valid website URL. so you need to concate base URL with _href.

Update:

import time
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag

url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31' \
  '&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page={}'

pages = 32

for page in range(1, pages+1):
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")

    for item in soup.find_all("a",{"class":"headline-image"},href=True):
        _href = item.get("href")
        try:
            resp = requests.get(_href)
        except Exception as e:
            try:
                resp = requests.get("https://www.wsj.com"+_href)
            except Exception as e:
                continue

        sauce = BeautifulSoup(resp.text,"lxml")
        dateTag = sauce.find("time",{"class":"timestamp article__timestamp flexbox__flex--1"})
        tag = sauce.find("li",{"class":"article-breadCrumb"})
        titleTag = sauce.find("h1",{"class":"wsj-article-headline"})
        contentTag = sauce.find("div",{"class":"wsj-snippet-body"})

        date = None
        tagName = None
        title = None
        content = None

        if isinstance(dateTag,Tag):
            date = dateTag.get_text().strip()

        if isinstance(tag,Tag):
            tagName = tag.get_text().strip()

        if isinstance(titleTag,Tag):
            title = titleTag.get_text().strip()

        if isinstance(contentTag,Tag):
            content = contentTag.get_text().strip()

        print(f'{date}\n {tagName}\n {title}\n {content}\n')
        time.sleep(3)

O/P:

March 31, 2019 10:00 a.m. ET
 Tech
 Care.com Removes Tens of Thousands of Unverified Listings
 The online child-care marketplace Care.com scrubbed its site of tens of thousands of unverified day-care center listings just before a Wall Street Journal investigation published March 8, an analysis shows. Care.com, the largest site in the U.S. for finding caregivers, removed about 72% of day-care centers, or about 46,594 businesses, listed on its site, a Journal review of the website shows. Those businesses were listed on the site as recently as March 1....

Updated March 29, 2019 6:08 p.m. ET
 Politics
 FBI, Retooling Once Again, Sets Sights on Expanding Cyber Threats
 The FBI has launched its biggest transformation since the 2001 terror attacks to retrain and refocus special agents to combat cyber criminals, whose threats to lives, property and critical infrastructure have outstripped U.S. efforts to thwart them. The push comes as federal investigators grapple with an expanding range of cyber attacks sponsored by foreign adversaries against businesses or national interests, including Russian election interference and Chinese cyber thefts from American companies, senior bureau executives...


问:
How can I select an Animatedmodal to display different demos using one ID
I have a website that i am trying to personalize and I am trying to use the AnimatedModal.js framework. I have been able to display some content in one modal, but when it comes to make several modal it gets tricky, because there is just one ID. My question i, how can i use the same ID and change the content for other modals(demo03,demo04..etc.), in order to personalize each.

I will put some code in order to understand the problem

I have been reading the documentation but I am still stuck in this problem.

```<code><!-- single work -->
<div class="col-md-4 col-sm-6 ads graphics">
  <a id="demo02" href="#animatedModal" class="portfolio_item">
    <img src="img/portfolio/03.jpg" alt="image" class="img-responsive" />
    <div class="portfolio_item_hover">
      <div class="portfolio-border clearfix">
        <div class="item_info">
          <span>Should open here </span> <em> ads / Graphics </em>
        </div>
      </div>
    </div>
  </a>
</div>
<!-- end single work -->
</code>```

Then I have the demo where it displays the content of the modal, where it has the #animatedmodal ID

```<code><div id="animatedModal" class="popup-modal ">
<!--THIS IS IMPORTANT! to close the modal, the class name has to match the name given on the ID -->
  <div id="btn-close-modal" class="close-animatedModal close-popup-modal">
    <i class="ion-close-round"></i>
  </div>
  <div class="clearfix"></div>
  <div class="modal-content ">
    <div class="container">
      <div class="portfolio-padding" >
        Hello World
        </a>
      </div>
    </div>
  </div>
</div>
</code>```

this is my Js file where there is just one element assigned to it, to avoid showing the same content into all different classes.

```<code>$("#demo02").animatedModal();
</code>```

答:
I don't think it can be done without hacking the plugin.

As a matter of fact, the script jQuery.animatedModal ALWAYS TARGETS the page element which has id="animatedModal"

You can see the plugin source code here:

https://cdn.jsdelivr.net/npm/animatedmodal@1.0.0/animatedModal.js

```<code>...
//Defaults
var settings = $.extend({
  modalTarget:'animatedModal',
 ...
</code>```

Here is the AnimatedModal reference:

https://joaopereirawd.github.io/animatedModal.js/

At the bottom of the page, I can't see any OPTION regarding how to specify a different target, all options are about styles and animation features.

At this point, I think the only way to allow multiple modals on the same page is to rewrite the plugin, but I'm pretty sure you don't want to choose this way.

Body:
I have a website that i am trying to personalize and I am trying to use the AnimatedModal.js framework. I have been able to display some content in one modal, but when it comes to make several modal it gets tricky, because there is just one ID. My question i, how can i use the same ID and change the content for other modals(demo03,demo04..etc.), in order to personalize each.

I will put some code in order to understand the problem

I have been reading the documentation but I am still stuck in this problem.

          Should open here   ads / Graphics

Then I have the demo where it displays the content of the modal, where it has the #animatedmodal ID

        Hello World

this is my Js file where there is just one element assigned to it, to avoid showing the same content into all different classes.

$("#demo02").animatedModal();

Body:
I don't think it can be done without hacking the plugin.

As a matter of fact, the script jQuery.animatedModal ALWAYS TARGETS the page element which has id="animatedModal"

You can see the plugin source code here:

https://cdn.jsdelivr.net/npm/animatedmodal@1.0.0/animatedModal.js

...
//Defaults
var settings = $.extend({
  modalTarget:'animatedModal',
 ...

Here is the AnimatedModal reference:

https://joaopereirawd.github.io/animatedModal.js/

At the bottom of the page, I can't see any OPTION regarding how to specify a different target, all options are about styles and animation features.

At this point, I think the only way to allow multiple modals on the same page is to rewrite the plugin, but I'm pretty sure you don't want to choose this way.


问:
Try to build Azure function app in linux following error returns "No job functions found. Try making your job classes and methods public"
When I try to build azure functions in Linux(Ubuntu 18.04) Following error returns.
Following are the steps I followed in the process.After cloning the repository from the git.

```<code>dotnet build
func start --build
</code>```

And following output returns,

```<code>[5/29/19 6:46:18 AM] No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).
[5/29/19 6:46:18 AM] Host initialized (49ms)
[5/29/19 6:46:18 AM] Host started (55ms)
[5/29/19 6:46:18 AM] Job host started
Hosting environment: Production
Content root path: /media/ishara/Data/MAS/SAGE/SageShipmentFunctions/SageShipmentFunctionsApp
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.
[5/29/19 6:46:23 AM] Host lock lease acquired by instance ID '000000000000000000000000CAE400CD'.
</code>```

Below follows the information about my system,

```<code>.NET Core SDK (reflecting any global.json):
 Version:   2.2.300
 Commit:    73efd5bd87

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  18.04
 OS Platform: Linux
 RID:         ubuntu.18.04-x64
 Base Path:   /usr/share/dotnet/sdk/2.2.300/

Host (useful for support):
  Version: 2.2.5
  Commit:  0a3c9209c0

.NET Core SDKs installed:
  2.2.300 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.5 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

</code>```

答:
Couple of options to try for this kind of error:

Where are you running 'func start --build' from?
Make sure you run it from the folder that has the built artifact, e.g. bin\Debug\net461.

If you are converting from another project or version.

In the VS csproj file, make sure AzureFunctionsVersion is present

```<code><Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
...etc
</code>```

You should upgrade to the latest Microsoft.NET.Sdk.Functions if it is not, sometimes code repo in the sample have the lower version.

Try these and see if it works, if not please provide the code repo link will take it forward.

Body:
When I try to build azure functions in Linux(Ubuntu 18.04) Following error returns.
Following are the steps I followed in the process.After cloning the repository from the git.

dotnet build
func start --build

And following output returns,

[5/29/19 6:46:18 AM] No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).
[5/29/19 6:46:18 AM] Host initialized (49ms)
[5/29/19 6:46:18 AM] Host started (55ms)
[5/29/19 6:46:18 AM] Job host started
Hosting environment: Production
Content root path: /media/ishara/Data/MAS/SAGE/SageShipmentFunctions/SageShipmentFunctionsApp
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.
[5/29/19 6:46:23 AM] Host lock lease acquired by instance ID '000000000000000000000000CAE400CD'.

Below follows the information about my system,

.NET Core SDK (reflecting any global.json):
 Version:   2.2.300
 Commit:    73efd5bd87

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  18.04
 OS Platform: Linux
 RID:         ubuntu.18.04-x64
 Base Path:   /usr/share/dotnet/sdk/2.2.300/

Host (useful for support):
  Version: 2.2.5
  Commit:  0a3c9209c0

.NET Core SDKs installed:
  2.2.300 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.5 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Body:
Couple of options to try for this kind of error:

Where are you running 'func start --build' from?
Make sure you run it from the folder that has the built artifact, e.g. bin\Debug\net461.

If you are converting from another project or version.

In the VS csproj file, make sure AzureFunctionsVersion is present

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
...etc

You should upgrade to the latest Microsoft.NET.Sdk.Functions if it is not, sometimes code repo in the sample have the lower version.

Try these and see if it works, if not please provide the code repo link will take it forward.


问:
Triggering DynamicData cache update using Reactive Subject
As a caveat I'm a novice with Rx (2 weeks) and have been experimenting with using Rx, RxUI and Roland Pheasant's DynamicData.

I have a service that initially loads data from local persistence and then, upon some user (or system) instruction will contact the server (TriggerServer in the example) to get additional or replacement data.  The solution I've come up with uses a Subject and I've come across many a site discussing the pros/cons of using them.  Although I understand the basics of hot/cold it's all based on reading rather than real world.

So, using the below as a simplified version, is this 'right' way of going about this problem or is there something I haven't properly understood somewhere?

NB: I'm not sure how important it is, but the actual code is taken from a Xamarin.Forms app, that uses RxUI, the user input being a ReactiveCommand.

Example:

```<code>using DynamicData;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;

public class MyService : IDisposable
{

    private CompositeDisposable _cleanup;
    private Subject<Unit> _serverSubject = new Subject<Unit>();

    public MyService()
    {

        var data = Initialise().Publish();
        AllData = data.AsObservableCache();

        _cleanup = new CompositeDisposable(AllData, data.Connect());
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public void TriggerServer()
    {
        // This is what I'm not sure about...
        _serverSubject.OnNext(Unit.Default);
    }

    private IObservable<IChangeSet<MyData, Guid>> Initialise()
    {
        return ObservableChangeSet.Create<MyData, Guid>(async cache =>
        {
            // inital load - is this okay?
            cache.AddOrUpdate(await LoadLocalData());

            // is this a valid way of doing this?
            var sync = _serverSubject.Select(_ => GetDataFromServer())
                .Subscribe(async task =>
                {
                    var data = await task.ConfigureAwait(false);
                    cache.AddOrUpdate(data);
                });

            return new CompositeDisposable(sync);
        }, d=> d.Id);
    }

    private IObservable<MyData> LoadLocalData()
    {
        return Observable.Timer(TimeSpan.FromSeconds(3)).Select(_ => new MyData("localdata"));
    }

    private async Task<MyData> GetDataFromServer()
    {
        await Task.Delay(2000).ConfigureAwait(true);
        return new MyData("serverdata");
    }

    public void Dispose()
    {
        _cleanup?.Dispose();
    }
}

public class MyData
{
    public MyData(string value)
    {
        Value = value;
    }

    public Guid Id { get; } = Guid.NewGuid();

    public string Value { get; set; }
}
</code>```

And a simple Console app to run:

```<code>public static class TestProgram
{
    public static void Main()
    {
        var service = new MyService();

        service.AllData.Connect()
            .Bind(out var myData)
            .Subscribe(_=> Console.WriteLine("data in"), ()=> Console.WriteLine("COMPLETE"));

        while (Continue())
        {
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine($"Triggering Server Call, current data is: {string.Join(", ", myData.Select(x=> x.Value))}");
            service.TriggerServer();
        }
    }

    private static bool Continue()
    {
        Console.WriteLine("Press any key to call server, x to exit");
        var key = Console.ReadKey();
        return key.Key != ConsoleKey.X;
    }
}
</code>```

答:
Looks very good for first try with Rx

I would suggest few changes:

1) Remove the Initialize() call from the constructor and make it a public method - helps a lot with unit tests and now you can await it if you need to

```<code> public static void Main()
    {
        var service = new MyService();
        service.Initialize();
</code>```

2) Add Throttle to you trigger - this fixes parallel calls to the server returning the same results

3) Don't do anything that can throw in Subscribe, use Do instead:

```<code>var sync = _serverSubject
                .Throttle(Timespan.FromSeconds(0.5), RxApp.TaskPoolScheduler) // you can pass a scheduler via arguments, or use TestScheduler in unit tests to make time pass faster
                .Do(async _ =>
                {
                    var data = await GetDataFromServer().ConfigureAwait(false); // I just think this is more readable, your way was also correct
                    cache.AddOrUpdate(data);
                })
               // .Retry(); // or anything alese to handle failures
                .Subscribe();
</code>```

Body:
As a caveat I'm a novice with Rx (2 weeks) and have been experimenting with using Rx, RxUI and Roland Pheasant's DynamicData.

I have a service that initially loads data from local persistence and then, upon some user (or system) instruction will contact the server (TriggerServer in the example) to get additional or replacement data.  The solution I've come up with uses a Subject and I've come across many a site discussing the pros/cons of using them.  Although I understand the basics of hot/cold it's all based on reading rather than real world.

So, using the below as a simplified version, is this 'right' way of going about this problem or is there something I haven't properly understood somewhere?

NB: I'm not sure how important it is, but the actual code is taken from a Xamarin.Forms app, that uses RxUI, the user input being a ReactiveCommand.

Example:

using DynamicData;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;

public class MyService : IDisposable
{

    private CompositeDisposable _cleanup;
    private Subject<Unit> _serverSubject = new Subject<Unit>();

    public MyService()
    {

        var data = Initialise().Publish();
        AllData = data.AsObservableCache();

        _cleanup = new CompositeDisposable(AllData, data.Connect());
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public void TriggerServer()
    {
        // This is what I'm not sure about...
        _serverSubject.OnNext(Unit.Default);
    }

    private IObservable<IChangeSet<MyData, Guid>> Initialise()
    {
        return ObservableChangeSet.Create<MyData, Guid>(async cache =>
        {
            // inital load - is this okay?
            cache.AddOrUpdate(await LoadLocalData());

            // is this a valid way of doing this?
            var sync = _serverSubject.Select(_ => GetDataFromServer())
                .Subscribe(async task =>
                {
                    var data = await task.ConfigureAwait(false);
                    cache.AddOrUpdate(data);
                });

            return new CompositeDisposable(sync);
        }, d=> d.Id);
    }

    private IObservable<MyData> LoadLocalData()
    {
        return Observable.Timer(TimeSpan.FromSeconds(3)).Select(_ => new MyData("localdata"));
    }

    private async Task<MyData> GetDataFromServer()
    {
        await Task.Delay(2000).ConfigureAwait(true);
        return new MyData("serverdata");
    }

    public void Dispose()
    {
        _cleanup?.Dispose();
    }
}

public class MyData
{
    public MyData(string value)
    {
        Value = value;
    }

    public Guid Id { get; } = Guid.NewGuid();

    public string Value { get; set; }
}

And a simple Console app to run:

public static class TestProgram
{
    public static void Main()
    {
        var service = new MyService();

        service.AllData.Connect()
            .Bind(out var myData)
            .Subscribe(_=> Console.WriteLine("data in"), ()=> Console.WriteLine("COMPLETE"));

        while (Continue())
        {
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine($"Triggering Server Call, current data is: {string.Join(", ", myData.Select(x=> x.Value))}");
            service.TriggerServer();
        }
    }

    private static bool Continue()
    {
        Console.WriteLine("Press any key to call server, x to exit");
        var key = Console.ReadKey();
        return key.Key != ConsoleKey.X;
    }
}

Body:
Looks very good for first try with Rx

I would suggest few changes:

1) Remove the Initialize() call from the constructor and make it a public method - helps a lot with unit tests and now you can await it if you need to

 public static void Main()
    {
        var service = new MyService();
        service.Initialize();

2) Add Throttle to you trigger - this fixes parallel calls to the server returning the same results

3) Don't do anything that can throw in Subscribe, use Do instead:

var sync = _serverSubject
                .Throttle(Timespan.FromSeconds(0.5), RxApp.TaskPoolScheduler) // you can pass a scheduler via arguments, or use TestScheduler in unit tests to make time pass faster
                .Do(async _ =>
                {
                    var data = await GetDataFromServer().ConfigureAwait(false); // I just think this is more readable, your way was also correct
                    cache.AddOrUpdate(data);
                })
               // .Retry(); // or anything alese to handle failures
                .Subscribe();


答: you should create a new object from your class and then set values for that .</p>

Title: how to instantiate the imported class in angular

Body:
i am working on a angualr weather app.
for which i have created weather class

 export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

weather:Weather;
getWeather():void{
               this.weatherserv.getWeather().subscribe(data=>{
                   this.weather.city=data.location.name;
                  this.weather.condition=data.condition.text;
                   this.weather.condition=data.condition.icon;
                   this.weather.temp=data.current.temp_c;
               })
             }

Error i am getting is:

Error: Cannot set property 'city' of undefined


问:
when to use and when not to use the DP and PX measures Android
I am trying to understand the "Best practices for Screen Independence".
 Can someone explain me when to use and when not to use the DP and PX measures ? (of course it is in documentation but my understanding is little vague from it..)

Thanks

答: I tend to use DP at all times. Avoid PX like the plague.


问:
When defining multiple classes in one file, I am getting that functions in the lower class are inaccessible to my main function
```<code>#include <iostream>
#include <string>
using namespace std;

/*----------------RECTANGLE CLASS----------------*/

class rectangle {
    int w, h;
public:
    void setVals(int, int);
    int area();
    int perimeter();
};

void rectangle::setVals( int x, int y) {
    w = x;
    h = y;
}

int rectangle::area() {
    return w * h;
}

int rectangle::perimeter() {
    return (2 * w) + (2 * h);
}

/*----------------CIRCLE CLASS----------------*/

class circle {
    double pi = 3.14159265358979;
    double r;
    void setR(double);
    double area();
    double circumference();
};

void circle::setR(double radius) {
    r = radius;
}

double circle::area() {
    return pi * (r * r);
}

double circle::circumference() {
    return 2 * pi * r;
}

/*----------------MAIN FUNCTION----------------*/

int main() {
    int choice;
    cout << "Enter 1 if you would like to calculate the area of a rectangle, Enter 2 if you would like calculate the area of a circle";
    cin >> choice;
    if (choice == 1) {
        int width, height;
        cout << "Enter the width of the rectangle ";
        cin >> width;
        cout << "Enter the height of the rectangle ";
        cin >> height;
        rectangle r;
        r.setVals(width, height);
        cout << "The area of the rectangle is " << r.area() << "\n";
        cout << "The perimeter of the rectangle is " << r.perimeter() << "\n";
    }
    else if (choice == 2) {
        double r;
        cout << "Enter the radius of the circle ";
        cin >> r;
        circle c;
        c.setR(r);
        cout << "The area of the circle is " << c.area(); << "\n"l;
        cout << "The circumference of the circle is " << c.circumference() << "\n";
    }
    return 0;
}
</code>```

this is just a practice program for getting the hang of OOP in C++, I am aware that C++ compiles from the top-down (so your main function has to be below any variables and objects that it is using), but from what I have seen, there shouldn't be any issue with creating two classes in a single .cpp file, yet I am having this issue. Any help is greatly appreciated, thanks.

答:
The member functions of circle are not marked public.

It has nothing to do with multiple classes; it's just that your second class is improperly defined.

Body:
#include <iostream>
#include <string>
using namespace std;

/*----------------RECTANGLE CLASS----------------*/

class rectangle {
    int w, h;
public:
    void setVals(int, int);
    int area();
    int perimeter();
};

void rectangle::setVals( int x, int y) {
    w = x;
    h = y;
}

int rectangle::area() {
    return w * h;
}

int rectangle::perimeter() {
    return (2 * w) + (2 * h);
}

/*----------------CIRCLE CLASS----------------*/

class circle {
    double pi = 3.14159265358979;
    double r;
    void setR(double);
    double area();
    double circumference();
};

void circle::setR(double radius) {
    r = radius;
}

double circle::area() {
    return pi * (r * r);
}

double circle::circumference() {
    return 2 * pi * r;
}

/*----------------MAIN FUNCTION----------------*/

int main() {
    int choice;
    cout << "Enter 1 if you would like to calculate the area of a rectangle, Enter 2 if you would like calculate the area of a circle";
    cin >> choice;
    if (choice == 1) {
        int width, height;
        cout << "Enter the width of the rectangle ";
        cin >> width;
        cout << "Enter the height of the rectangle ";
        cin >> height;
        rectangle r;
        r.setVals(width, height);
        cout << "The area of the rectangle is " << r.area() << "\n";
        cout << "The perimeter of the rectangle is " << r.perimeter() << "\n";
    }
    else if (choice == 2) {
        double r;
        cout << "Enter the radius of the circle ";
        cin >> r;
        circle c;
        c.setR(r);
        cout << "The area of the circle is " << c.area(); << "\n"l;
        cout << "The circumference of the circle is " << c.circumference() << "\n";
    }
    return 0;
}

this is just a practice program for getting the hang of OOP in C++, I am aware that C++ compiles from the top-down (so your main function has to be below any variables and objects that it is using), but from what I have seen, there shouldn't be any issue with creating two classes in a single .cpp file, yet I am having this issue. Any help is greatly appreciated, thanks.


问:
About using namespace std in C++
If we use

using namespace std

in our source file, in which step is the definition of namespace imported to our source file?

答:
The definition of the namespace is imported when you write:

```<code>#include <iostream>
</code>```

or

```<code>#include <stdio.h>
</code>```

by writing using namespace std you don't import the namespace, you allow using its entities without std prefix, like cout instead of std::cout

Title: About using namespace std in C++

Body:
The definition of the namespace is imported when you write:

#include <iostream>

or

#include <stdio.h>

by writing using namespace std you don't import the namespace, you allow using its entities without std prefix, like cout instead of std::cout


问:
Azure Service Bus "The lock supplied is invalid" after message work successfully completed
I've an Azure Web Job with the following initialization code

```<code>class Program
{
    static void Main(string[] args)
    {
        IHostBuilder builder = new HostBuilder()
        .ConfigureWebJobs(b =>
        {
            b.AddServiceBus((opt) =>
            {
                opt.ConnectionString = "Connection string";
                opt.MessageHandlerOptions = new MessageHandlerOptions((ex) =>
                {
                    return Task.Run(() =>
                    {
                        // logging the error message
                    });
                })
                {
                    MaxAutoRenewDuration = new TimeSpan(0, 0, 5, 0),
                    MaxConcurrentCalls = 1
                };
            });
        })
        .UseConsoleLifetime();

        IHost host = builder.Build();
        using (host)
        {
            host.Run();
        }
    }
}
</code>```

The Service Bus queue is configured to have a Lock Duration of 5 minutes, that is the maximum time that Azure allows.
The message processing can take more than 30 minutes and the lock renew mechanism works correctly.
When the process ends correctly, an exception is thrown The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance and the message goes back to the queue again.

答:
When you call messsage.Complete() (or CompleteAsync()) then you should instantiate an MessageHandlerOptions object, set AutoComplete to false, and pass it into your message handler registration.

```<code>new MessageHandlerOptions(OnException)
{
    AutoComplete = false,
    MaxConcurrentCalls = MaxConcurrentCalls, // 1
    MaxAutoRenewDuration = MaxAutoRenewDuration // 2 hrs
}
</code>```

For more details, you could refer to this article.

Body:
I've an Azure Web Job with the following initialization code

class Program
{
    static void Main(string[] args)
    {
        IHostBuilder builder = new HostBuilder()
        .ConfigureWebJobs(b =>
        {
            b.AddServiceBus((opt) =>
            {
                opt.ConnectionString = "Connection string";
                opt.MessageHandlerOptions = new MessageHandlerOptions((ex) =>
                {
                    return Task.Run(() =>
                    {
                        // logging the error message
                    });
                })
                {
                    MaxAutoRenewDuration = new TimeSpan(0, 0, 5, 0),
                    MaxConcurrentCalls = 1
                };
            });
        })
        .UseConsoleLifetime();

        IHost host = builder.Build();
        using (host)
        {
            host.Run();
        }
    }
}

The Service Bus queue is configured to have a Lock Duration of 5 minutes, that is the maximum time that Azure allows.
The message processing can take more than 30 minutes and the lock renew mechanism works correctly.
When the process ends correctly, an exception is thrown The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance and the message goes back to the queue again.

Body:
When you call messsage.Complete() (or CompleteAsync()) then you should instantiate an MessageHandlerOptions object, set AutoComplete to false, and pass it into your message handler registration.

new MessageHandlerOptions(OnException)
{
    AutoComplete = false,
    MaxConcurrentCalls = MaxConcurrentCalls, // 1
    MaxAutoRenewDuration = MaxAutoRenewDuration // 2 hrs
}

For more details, you could refer to this article.


答:
try this:</p>

```<code>weather: Weather =  new Weather();
getWeather():void{
           this.weatherserv.getWeather().subscribe(data=>{
               this.weather.city=data.location.name;
              this.weather.condition=data.condition.text;
               this.weather.condition=data.condition.icon;
               this.weather.temp=data.current.temp_c;
           })
         }
</code>```

Body:
try this:

weather: Weather =  new Weather();
getWeather():void{
           this.weatherserv.getWeather().subscribe(data=>{
               this.weather.city=data.location.name;
              this.weather.condition=data.condition.text;
               this.weather.condition=data.condition.icon;
               this.weather.temp=data.current.temp_c;
           })
         }


问:
Run two commands synchronously in a split terminal
I would like to launch my development server using a single launch script in a split console with ConEmu. It can be a ConEmu task, a batch script, or whatever it takes. I have achieved this with Gulp but find that solution to be overkill.

I need to execute

```<code>cd C:\Repo\myApp\frontEnd
npm start
</code>```

I would then like to split the window cmd -new_console:s50H

And without waiting for npm start to finish, because it does not, execute the following in the new window. Syncronously so to speak.

```<code>cd C:\Repo\myApp\backEnd -new_console:s50H
node backEnd.js
</code>```

答:
Do you really care about executing npm start before creating new split with backend?

If you don't - the simplest way is starting backend before frontend. Actually, due to some minor delays in processing, your npm start may start same time or even before than node.

```<code>cd /d C:\Repo\myApp\frontEnd
node backEnd.js -new_console:s50H -new_console:d:"C:\Repo\myApp\backEnd"
npm start
</code>```

Another option is starting npm in background and node thereafter.

```<code>cd /d C:\Repo\myApp\frontEnd
ConEmuC -async -c npm start
node backEnd.js -new_console:s50H -new_console:d:"C:\Repo\myApp\backEnd"
</code>```

Body:
I would like to launch my development server using a single launch script in a split console with ConEmu. It can be a ConEmu task, a batch script, or whatever it takes. I have achieved this with Gulp but find that solution to be overkill.

I need to execute

cd C:\Repo\myApp\frontEnd
npm start

I would then like to split the window cmd -new_console:s50H

And without waiting for npm start to finish, because it does not, execute the following in the new window. Syncronously so to speak.

cd C:\Repo\myApp\backEnd -new_console:s50H
node backEnd.js

Body:
Do you really care about executing npm start before creating new split with backend?

If you don't - the simplest way is starting backend before frontend. Actually, due to some minor delays in processing, your npm start may start same time or even before than node.

cd /d C:\Repo\myApp\frontEnd
node backEnd.js -new_console:s50H -new_console:d:"C:\Repo\myApp\backEnd"
npm start

Another option is starting npm in background and node thereafter.

cd /d C:\Repo\myApp\frontEnd
ConEmuC -async -c npm start
node backEnd.js -new_console:s50H -new_console:d:"C:\Repo\myApp\backEnd"


问:
Update values for all rows based on unique ID - Oracle
I have a table:

table1

```<code>unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       null        null
1               2           test 2      abc         1       null        null
1               3           test 3      103         1       null        null
1               4           test 4      105         2       null        null
1               5           test 5      10          1       null        null
1               6           my date     20180912    1       null        null
1               7           my date 1   20180913    2       null        null
1               8           test 6      100         1       null        null

2               1           test 1      100         1       null        null
2               2           test 2      abc         1       null        null
2               3           test 3      103         1       null        null
2               4           test 4      105         2       null        null
2               5           test 5      10          1       null        null
2               6           my date     20180911    1       null        null
2               7           my date 1   20180910    2       null        null
2               8           test 6      100         1       null        null
</code>```

For each unique_id, I need to get col_val and set s_date and e_date:

s_date = col_val of col_id = 6 and col_nm = 'my date' and sequence = 1

e_date = col_val of col_id = 7 and col_nm = 'my date 1' and sequence = 2

and then set it for all rows of the appropriate unique_id.

The output table looks like:

```<code>unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       20180912    20180913
1               2           test 2      abc         1       20180912    20180913
1               3           test 3      103         1       20180912    20180913
1               4           test 4      105         2       20180912    20180913
1               5           test 5      10          1       20180912    20180913
1               6           my date     20180912    1       20180912    20180913
1               7           my date 1   20180913    2       20180912    20180913
1               8           test 6      100         1       20180912    20180913

2               1           test 1      100         1       20180911    20180910
2               2           test 2      abc         1       20180911    20180910
2               3           test 3      103         1       20180911    20180910
2               4           test 4      105         2       20180911    20180910
2               5           test 5      10          1       20180911    20180910
2               6           my date     20180911    1       20180911    20180910
2               7           my date 1   20180910    2       20180911    20180910
2               8           test 6      100         1       20180911    20180910
</code>```

My table has over 50 million records, so need the query to take that into consideration.

Is there a way in SQL to achieve this?

答:
You can try the following query:

```<code>MERGE INTO TABLE1 T1 USING (
                               SELECT
                                   START_DATE.UNIQUE_ID,
                                   START_DATE.COL_VAL   AS START_DATE,
                                   END_DATE.COL_VAL     AS END_DATE
                               FROM
                                   (
                                       SELECT
                                           T.UNIQUE_ID,
                                           T.COL_VAL
                                       FROM
                                           TABLE1 T
                                       WHERE
                                           T.COL_ID = 6
                                           AND T.COL_NM = 'my date'
                                   ) START_DATE,
                                   (
                                       SELECT
                                           T.UNIQUE_ID,
                                           T.COL_VAL
                                       FROM
                                           TABLE1 T
                                       WHERE
                                           T.COL_ID = 7
                                           AND T.COL_NM = 'my date 1'
                                   ) END_DATE
                               WHERE
                                   START_DATE.UNIQUE_ID = END_DATE.UNIQUE_ID
                           )
DATES ON ( T1.UNIQUE_ID = DATES.UNIQUE_ID ) WHEN MATCHED THEN
UPDATE SET
    T1.S_DATE = DATES.START_DATE,
    T1.E_DATE = DATES.END_DATE;
</code>```

Demo

Thanks.

Body:
I have a table:

table1

unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       null        null
1               2           test 2      abc         1       null        null
1               3           test 3      103         1       null        null
1               4           test 4      105         2       null        null
1               5           test 5      10          1       null        null
1               6           my date     20180912    1       null        null
1               7           my date 1   20180913    2       null        null
1               8           test 6      100         1       null        null

2               1           test 1      100         1       null        null
2               2           test 2      abc         1       null        null
2               3           test 3      103         1       null        null
2               4           test 4      105         2       null        null
2               5           test 5      10          1       null        null
2               6           my date     20180911    1       null        null
2               7           my date 1   20180910    2       null        null
2               8           test 6      100         1       null        null

For each unique_id, I need to get col_val and set s_date and e_date:

s_date = col_val of col_id = 6 and col_nm = 'my date' and sequence = 1

e_date = col_val of col_id = 7 and col_nm = 'my date 1' and sequence = 2

and then set it for all rows of the appropriate unique_id.

The output table looks like:

unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       20180912    20180913
1               2           test 2      abc         1       20180912    20180913
1               3           test 3      103         1       20180912    20180913
1               4           test 4      105         2       20180912    20180913
1               5           test 5      10          1       20180912    20180913
1               6           my date     20180912    1       20180912    20180913
1               7           my date 1   20180913    2       20180912    20180913
1               8           test 6      100         1       20180912    20180913

2               1           test 1      100         1       20180911    20180910
2               2           test 2      abc         1       20180911    20180910
2               3           test 3      103         1       20180911    20180910
2               4           test 4      105         2       20180911    20180910
2               5           test 5      10          1       20180911    20180910
2               6           my date     20180911    1       20180911    20180910
2               7           my date 1   20180910    2       20180911    20180910
2               8           test 6      100         1       20180911    20180910

My table has over 50 million records, so need the query to take that into consideration.

Is there a way in SQL to achieve this?

Body:
You can try the following query:

MERGE INTO TABLE1 T1 USING (
                               SELECT
                                   START_DATE.UNIQUE_ID,
                                   START_DATE.COL_VAL   AS START_DATE,
                                   END_DATE.COL_VAL     AS END_DATE
                               FROM
                                   (
                                       SELECT
                                           T.UNIQUE_ID,
                                           T.COL_VAL
                                       FROM
                                           TABLE1 T
                                       WHERE
                                           T.COL_ID = 6
                                           AND T.COL_NM = 'my date'
                                   ) START_DATE,
                                   (
                                       SELECT
                                           T.UNIQUE_ID,
                                           T.COL_VAL
                                       FROM
                                           TABLE1 T
                                       WHERE
                                           T.COL_ID = 7
                                           AND T.COL_NM = 'my date 1'
                                   ) END_DATE
                               WHERE
                                   START_DATE.UNIQUE_ID = END_DATE.UNIQUE_ID
                           )
DATES ON ( T1.UNIQUE_ID = DATES.UNIQUE_ID ) WHEN MATCHED THEN
UPDATE SET
    T1.S_DATE = DATES.START_DATE,
    T1.E_DATE = DATES.END_DATE;

Demo

Thanks.


问:
How to mock custom ILoggerManager to do UnitTest
I declared a class LogManager and an interface ILogManager, and has a method LoggerError,  this method use ILogger (DI) to logerror and do other things.

There is a class A (DI ILogClass ) and declare a method  funA()， and funA() will use _LogManager.LoggerError("test message").

When do I unit test with mock ?

How to Verify _LogManager.LoggerError("test message") ?

If I just use ILogger in class A, I can Verify with :

```<code>loggerMock.Verify(l => l.Log(LogLevel.Error,It.IsAny<EventId>(),
It.Is<object>(o => o.ToString().Contains("test message")),null,It.IsAny<Func<object, Exception, string>>()), Times.Once);
</code>```

But not support with ILogManager mock.

```<code>public class LoggerManager<TCategoryName> : ILoggerManager<TCategoryName>
{
    private readonly ILogger<TCategoryName> _logger;
    public LoggerManager(ILogger<TCategoryName> logger)
    {
        this._logger = logger;
    }
    public void LogError(string message, LoggerErrorType type)
    {
     var errorLogger = NLog.LogManager.GetLogger(loggerName);
     errorLogger.Error(message);
    }
}

class A
{
....DI
     public void Test()
     {
         _loggerManager.LogError("test message")
     }
}

UT:
public void TestUT()
{
    var loggerMock = new Mock ILoggerManager A>>();
    var service = ServiceFactory.Create<A>(loggerMock);

    service.Test();
    //how to Verify logerror message?
}
</code>```

答:
Your LoggerManager<TCategoryName> is just a wrapper over the ILogger<TCategoryName> and thus you can just mock ILogger<TCategoryName> and verify the same as you have already done and that should work just fine.

Though while making the actuall call to SUT you will have to dependency inject the LoggerManager<TCategoryName> accordingly

Body:
I declared a class LogManager and an interface ILogManager, and has a method LoggerError,  this method use ILogger (DI) to logerror and do other things.

There is a class A (DI ILogClass ) and declare a method  funA()， and funA() will use _LogManager.LoggerError("test message").

When do I unit test with mock ?

How to Verify _LogManager.LoggerError("test message") ?

If I just use ILogger in class A, I can Verify with :

loggerMock.Verify(l => l.Log(LogLevel.Error,It.IsAny<EventId>(),
It.Is<object>(o => o.ToString().Contains("test message")),null,It.IsAny<Func<object, Exception, string>>()), Times.Once);

But not support with ILogManager mock.

public class LoggerManager<TCategoryName> : ILoggerManager<TCategoryName>
{
    private readonly ILogger<TCategoryName> _logger;
    public LoggerManager(ILogger<TCategoryName> logger)
    {
        this._logger = logger;
    }
    public void LogError(string message, LoggerErrorType type)
    {
     var errorLogger = NLog.LogManager.GetLogger(loggerName);
     errorLogger.Error(message);
    }
}

class A
{
....DI
     public void Test()
     {
         _loggerManager.LogError("test message")
     }
}

UT:
public void TestUT()
{
    var loggerMock = new Mock ILoggerManager A>>();
    var service = ServiceFactory.Create(loggerMock);

    service.Test();
    //how to Verify logerror message?
}


问:
How to plot just the legends in ggplot2?
I'm currently working with igraph and have colour labelled my vertices. I would like to add a legend Indicating what each colour represents.

What I can think of at this point is to use ggplot2 to print only the legend and hide a bar plot.
Is there a way to just output the legend?

答:
I used the ggpubr package - makes it very easy!

https://rpkgs.datanovia.com/ggpubr/reference/get_legend.html

```<code># Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot and print
as_ggplot(leg)
</code>```

Body:
I used the ggpubr package - makes it very easy!

https://rpkgs.datanovia.com/ggpubr/reference/get_legend.html

# Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot and print
as_ggplot(leg)


问:
Retrieving Java list from ruby
My service(written in Java) returns me an output in the format:

```<code> "serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"}
     }
  ]
</code>```

I need to retrieve the values metricDate and metricValue from my Ruby client. Am not sure about how this can be done. Any help in this regard will be great.

答:
Looks like you java service spits JSON (looks close to this, no ?)

You can try and parse that with a JSON Parser in ruby:

```<code>require 'rubygems'; require 'json';
a = JSON.parse( "{"+ str + "}" )
</code>```

Btw, your sample is broken, the } is closed twice after urlSerialNo. Apart from that, it's JSON !

Title: Retrieving Java list from ruby

Body:
My service(written in Java) returns me an output in the format:

 "serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"}
     }
  ]

I need to retrieve the values metricDate and metricValue from my Ruby client. Am not sure about how this can be done. Any help in this regard will be great.

Body:
Looks like you java service spits JSON (looks close to this, no ?)

You can try and parse that with a JSON Parser in ruby:

require 'rubygems'; require 'json';
a = JSON.parse( "{"+ str + "}" )

Btw, your sample is broken, the } is closed twice after urlSerialNo. Apart from that, it's JSON !


问:
Linux telnet shell script
I'm trying to read multiple hosts and ports from a text file (ip.txt) and check if they are connected/failed to connect/timed out, and echo the responses to Telnet_Success.txt/Telnet_Failure.txt/Telnet_Refused.txt files

I have tried the following script, it simply shows all the connection results as failed, but when checking manually one by one, I find some of them connected. any help is appreciated.
Here is the script:

```<code>>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
file=ip.txt
while read line ; do
  ip=$( echo "$line" |cut -d ' ' -f1 )
  port=$( echo "$line" |cut -d ' ' -f2 )
  if telnet -c $ip $port </dev/null 2>&1 | grep -q Escape; then
  echo "$ip $port Connected" >> Telnet_Success.txt
  elif telnet -c $ip $port </dev/null 2>&1 | grep -q refused; then
  echo "$ip $port Refused" >> Telnet_Refused.txt
  else
  echo "$ip $port Failed" >> Telnet_Failure.txt
  fi
 done < ${file}
</code>```

答:
I can't tell you exactly what's failing from the diagnostics you have provided, but it's definitely a problem that you attempt to call telnet multiple times - you could get different outcomes each time, producing bugs which are hard to troubleshoot. You also have some stylistic issues in your code.

Try this refactoring; see the inline comments.

```<code>>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
# Why use a variable for something you only reference once anyway?
file=ip.txt
# Use the shell's field splitting facility
# Cope with missing final newline; see
# https://mywiki.wooledge.org/BashFAQ/001#My_text_files_are_broken.21__They_lack_their_final_newlines.21
while read -r ip port _ || [[ -n $port ]]; do
  # Run telnet once, capture result for analysis
  output=$(telnet -c "$ip" "$port" </dev/null 2>&1)
  case $output in
    *Escape*)
        echo "$ip $port Connected" >> Telnet_Success.txt;;
  *refused*)
        echo "$ip $port Refused" >> Telnet_Refused.txt;;
  *)
        echo "$ip $port Failed" >> Telnet_Failure.txt;;
  esac
# Always double quote file name variables, just in case
done < "${file}"
</code>```

Title: Linux telnet shell script

Body:
I'm trying to read multiple hosts and ports from a text file (ip.txt) and check if they are connected/failed to connect/timed out, and echo the responses to Telnet_Success.txt/Telnet_Failure.txt/Telnet_Refused.txt files

I have tried the following script, it simply shows all the connection results as failed, but when checking manually one by one, I find some of them connected. any help is appreciated.
Here is the script:

>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
file=ip.txt
while read line ; do
  ip=$( echo "$line" |cut -d ' ' -f1 )
  port=$( echo "$line" |cut -d ' ' -f2 )
  if telnet -c $ip $port </dev/null 2>&1 | grep -q Escape; then
  echo "$ip $port Connected" >> Telnet_Success.txt
  elif telnet -c $ip $port </dev/null 2>&1 | grep -q refused; then
  echo "$ip $port Refused" >> Telnet_Refused.txt
  else
  echo "$ip $port Failed" >> Telnet_Failure.txt
  fi
 done < ${file}

Body:
I can't tell you exactly what's failing from the diagnostics you have provided, but it's definitely a problem that you attempt to call telnet multiple times - you could get different outcomes each time, producing bugs which are hard to troubleshoot. You also have some stylistic issues in your code.

Try this refactoring; see the inline comments.

>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
# Why use a variable for something you only reference once anyway?
file=ip.txt
# Use the shell's field splitting facility
# Cope with missing final newline; see
# https://mywiki.wooledge.org/BashFAQ/001#My_text_files_are_broken.21__They_lack_their_final_newlines.21
while read -r ip port _ || [[ -n $port ]]; do
  # Run telnet once, capture result for analysis
  output=$(telnet -c "$ip" "$port" </dev/null 2>&1)
  case $output in
    *Escape*)
        echo "$ip $port Connected" >> Telnet_Success.txt;;
  *refused*)
        echo "$ip $port Refused" >> Telnet_Refused.txt;;
  *)
        echo "$ip $port Failed" >> Telnet_Failure.txt;;
  esac
# Always double quote file name variables, just in case
done < "${file}"


问:
How to bind class to more than two options in Vue.js?
I have the following Vue.js bound HTML:

```<code><span :class="[obj.status === 'Online' ? 'badge-success' : 'badge-danger', 'badge badge-pill']">{{obj.status}}</span>
</code>```

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

答:
You can add another tertiary operator in case if Status is not online like below </p>

```<code> <span :class="[obj.status === 'Online' ? 'badge-success' : (obj.status === 'updating'?'badge-warning':'badge-danger'), 'badge badge-pill']">{{obj.status}}</span>
</code>```

Body:
I have the following Vue.js bound HTML:

{{obj.status}}

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

Body:
You can add another tertiary operator in case if Status is not online like below

 <span :class="[obj.status === 'Online' ? 'badge-success' : (obj.status === 'updating'?'badge-warning':'badge-danger'), 'badge badge-pill']">{{obj.status}}</span>