问:
Spring Batch Late Binding - Step Scope or Job Scope?
I'm working on a project using Spring Batch. In this project, I use Spring Batch late binding in which I injected a parameter (a string that will be used as a condition for SQL reader query) using JobParameters. Currently, I'm using the @StepScope for that late binding and everything works perfectly fine.

What I'm asking here is when to use @StepScope and when to use @JobScope. I've read the Spring Batch reference and I've googled about StepScope and JobScope. All I'm getting is that :

a. StepScope : Spring Batch will use the spring container to instantiate a new instance of that component for each step execution.

b. JobScope : There will be only one instance per executing job.

I just can't determine the consideration of when to use StepScope or JobScope. Can someone explain a little deeper?

答:
A step is composed of a read, transform/process, and write stage, the latter is per chunk with retry / rollback complications through the process stage, and the read stage is usually no-rollback no-retry. A Job is composed of as many steps, each doing that, as you like. So a step scope bean is the same instance for each read/process/write phase and listeners of a given step. Job scope is the same instance for all steps in a job.

So, if you need to use the same listener for some processing in multiple steps of a job (you have a step to convert data to an intermediary format and validate, then a step to process all data to your database and you want the same listener to do some async auditing process somewhere) then you would job scope that listener and register it against both steps in the job. This way, each step would see the same instance of the object behind the proxy and the same methods on the same instance would be called for things like "on read error" or "after write" or "after step" (depending if you're using annotation based listener or interface based listener and what you're listening for)

Your reader, for example, is / should only be used by one step at any time, so having things like your readers as step scope is usually correct, where that reader is created and pointed at a particular resource. A better example is a listener that you need to perhaps clean up a directory or do something after a step has completed, but because this process changes (location of directory) with each step, although you want the same actual object type for the listener, and you might even want it to do the same thing, you want it to use a new directory and a new UUID prefix or something per step, you'd have one definition for that bean perhaps using the same Job parameters but the definition would new up a temp directory or UUID etc and you'd set that bean definition to Step scope so that when you wire it into two different steps they get two different actual objects behind the lazy proxies.

Now, a Job Listener should probably be job scoped, but here raises the question, if you want the same instance across all steps and all jobs, then you use a "regular scoped" singleton and use that instead.

Outside of a job you cannot see job scope or step scope

Outside of a step you cannot see step scope

Or

Inside of a step you can see job and step scope beans

Inside of a job you can see all Job scope beans or singletons

Also To Consider:

When you create a singleton and it has, wired into it, a job scope or step scope bean, even though your singleton is the same object used "everywhere" , when it references the job or step scoped object inside (really a proxy) it will see a different one per job or step accordingly.
So you can have a singleton bean that represents your step and the step can reference step scoped beans. That way your Step instance you build your Job with could and possibly should just be a singleton but it has wired into it's bean method / definition / constructor the step scoped beans it relies upon at execution to be different instances.


来源: stackexchange

问:
Finding a value to the left Reverse Vlookup using INDEX and MATCH VBA
I've seen many forum saying that it is possible to find data to the left column, as opposed to Vlookup function.

I have a sheet of which I would like to get the value from the left. In other words, I would like to seach for a serial # on the right, say column 3, and get a value on column 1.

What would an alternative to Vlookup in VBA? (i.e., reverse vlookup)

I seen several forums with examples using index match, but I cannot understand the syntax. Can someone please provide me with a simple example?

Here is what I was using before and found out that Vlookup cannot search to the left:

```<code>Sal = Application.WorksheetFunction.VLookup("3491709101",Sheets(PreviousTabName).Range(ThisRAnge), 2, False)
</code>```

答:
Index-Match syntax VBA

```<code>Dim ReturnValueRange as range, LookupRange as range

Set ReturnValueRange = Thisworkbook.Sheets("Sheet1").range("$E$1:$E$7")
Set LookupRange = Thisworkbook.Sheets("Sheet1").range("$G$1:$G$7")

LookUpValue = "findMe"

Result = Application.WorksheetFunction.INDEX(ReturnValueRange,Application.WorksheetFunction.MATCH(LookUpValue, LookupRange, 0))
</code>```

Index-Match syntax FORMULA

```<code>=INDEX(ReturnValueRange,MATCH(LookUpValue, LookupRange, 0))
</code>```

LEFT VLOOKUP Syntax VBA

Return Error in not match

Result = WorksheetFunction.VLOOKUP(LookUpValue, WorksheetFunction.CHOOSE(Array(1,2), LookupRange, ReturnValueRange), 2, 0))

LEFT VLOOKUP Syntax FORMULA

```<code>=VLOOKUP(LookUpValue, WorksheetFunction.CHOOSE({1,2}, LookupRange, ReturnValueRange), 2, 0))
</code>```

the “CHOOSE” function is manipulating the two fields.

You’re assigning reference “index” numbers to ranges of data –
assigning the LookupRange to index number 1 and the ReturnValueRange to index number 2

So, when you type “2” in the VLookup function, you’re actually
referring to Index number 2 in the CHOOSE function.

ContentLicense: CC BY-SA 4.0

Body:
I've seen many forum saying that it is possible to find data to the left column, as opposed to Vlookup function.

I have a sheet of which I would like to get the value from the left. In other words, I would like to seach for a serial # on the right, say column 3, and get a value on column 1.

What would an alternative to Vlookup in VBA? (i.e., reverse vlookup)

I seen several forums with examples using index match, but I cannot understand the syntax. Can someone please provide me with a simple example?

Here is what I was using before and found out that Vlookup cannot search to the left:

Sal = Application.WorksheetFunction.VLookup("3491709101",Sheets(PreviousTabName).Range(ThisRAnge), 2, False)

Body:
Index-Match syntax VBA

Dim ReturnValueRange as range, LookupRange as range

Set ReturnValueRange = Thisworkbook.Sheets("Sheet1").range("$E$1:$E$7")
Set LookupRange = Thisworkbook.Sheets("Sheet1").range("$G$1:$G$7")

LookUpValue = "findMe"

Result = Application.WorksheetFunction.INDEX(ReturnValueRange,Application.WorksheetFunction.MATCH(LookUpValue, LookupRange, 0))

Index-Match syntax FORMULA

=INDEX(ReturnValueRange,MATCH(LookUpValue, LookupRange, 0))

LEFT VLOOKUP Syntax VBA

Return Error in not match

Result = WorksheetFunction.VLOOKUP(LookUpValue, WorksheetFunction.CHOOSE(Array(1,2), LookupRange, ReturnValueRange), 2, 0))

LEFT VLOOKUP Syntax FORMULA

=VLOOKUP(LookUpValue, WorksheetFunction.CHOOSE({1,2}, LookupRange, ReturnValueRange), 2, 0))

the “CHOOSE” function is manipulating the two fields.

You’re assigning reference “index” numbers to ranges of data –
assigning the LookupRange to index number 1 and the ReturnValueRange to index number 2

So, when you type “2” in the VLookup function, you’re actually
referring to Index number 2 in the CHOOSE function.


问:
Check if a week of dates sits between two specific dates SQL ORACLE
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time. </p>

```<code>SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);
</code>```

答:
I think you are looking for something like the following:

```<code>WITH weeks AS (SELECT TO_DATE('05-07-2017', 'DD-MM-RRRR') + LEVEL * 7 - 7 week_start
                    , TO_DATE('05-07-2017', 'DD-MM-RRRR') + LEVEL * 7 - 1 week_end
                 FROM dual
                 CONNECT BY LEVEL < 50)
SELECT *
  FROM MY_DATA
  JOIN WEEKS
    ON MY_DATA.end_date   >= weeks.week_start
   AND MY_DATA.start_date <= weeks.week_end
</code>```

The first part gets you some consecutive weeks then you join them with your data to get the desired results.

Body:
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time.

SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);

Body:
I think you are looking for something like the following:

WITH weeks AS (SELECT TO_DATE('05-07-2017', 'DD-MM-RRRR') + LEVEL * 7 - 7 week_start
                    , TO_DATE('05-07-2017', 'DD-MM-RRRR') + LEVEL * 7 - 1 week_end
                 FROM dual
                 CONNECT BY LEVEL < 50)
SELECT *
  FROM MY_DATA
  JOIN WEEKS
    ON MY_DATA.end_date   >= weeks.week_start
   AND MY_DATA.start_date <= weeks.week_end

The first part gets you some consecutive weeks then you join them with your data to get the desired results.


问:
How do I implement remember me functionality in Oauth 2.0 with refresh_token?
I have read a lot of material, including the OAuth 2.0's RFC, to make a secure login using this protocol. The flow that I have implemented is the authorization code grant, because I have a secure NET CORE back-end to store the client secret. I have implemented the protocol as it is described in the RFC or in other Oauth 2.0 implementation workflow sheets.

At the moment I have the access_token and the refresh_token, but I desire to implement the remeber me functionality. I thinked it in different ways, but I don't figure out how to implement it in a secure way.

If I will save the refresh in the browser's http security cookies through the server, I'm vulnerable to the CSRF attack, and if I will save it in local storage is even worse because I'm vulnerable to XSS attacks and it can be stolen.

In simple words I need to mitigate the XSS and CSRF vulnerabilities, having a remember me functionality. (I also thinked about using browsers' same-site cookie attribute, to mitigate se CSRF vulnerability, but I need to get back-to-back compatibility and this feature is only available in the recent version of the browsers).

My question is: How do I implement remember me functionality also taking care of security aspects?

答:
If your application has an XSS vulnerability, then it doesn't matter whether you keep a token in-memory (variable) or in localStorage. The malicious code will not have a problem accessing it. So I think keeping a "remember me" info in localStorage doesn't degrade your current security level. To protect your application against XSS attacks, you can use things like Content Security Policy, so that only the JavaScript code you trust will be executed. For more info, see the OWASP XSS prevention cheat sheet.

I think you could keep your access token in sessionStorage instead of a variable so users don't have to log in when they reload the page.

If you store the "remember me" info in an HTTP-only cookie, it may make your application vulnerable to CSRF attacks, but again, there are ways to prevent it (OWASP CSRF prevention) such as CORS and sending a extra token in each request, which needs to be read from a cookie by JavaScript code.

The "remember me" functionality may add some kind of risk, since users stay logged in for a long time. So it's up to you to assess the balance between the risks and convenience for users.

You can take a look at the OAuth 2.0 for Browser-Based Apps. It doesn't discuss the "remember me" functionality, but it discusses good practices and security considerations.


问:
React Google Analytics - How to check if initialized?
I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).

So, I would like to create a text field in backoffice which value is saved in database.

Then in the front side, I initialize react-ga only if I have a value in database.

To achieve this, I'm trying do this in componentDidUpdate in App.jsx.

I retrieve all my data set in backoffice via :

```<code>componentDidMount() {
    // I get my data in this.props.data_admin
    this.props.list_admin();
}
</code>```

Then in componentDidUpdate(prevProps, prevState) I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :

```<code>componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin) {
        // this.props.data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(this.props.data_admin.trackingNumber);
    }
}
</code>```

But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done.
How can I check if react-ga is already initialized ?

Thanks for your help

答:
Finally what I did :

I called this.props.list_admin(); in App.jsx constructor and I created a state variable initialized at false :

```<code>constructor(props) {
    super(props);

    this.state = {
        googleAnalyticsInitialized: false,
    };

    this.props.list_admin();
}
</code>```

Then, in componentDidupdate I checked values from this.props.data_admin and if googleAnalyticsInitialized is false. If it is, I initialiaze Google Analytics with the ID received from the call to the API :

```<code>componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin && this.props.data_admin.idGoogleAnalytics && !this.state.googleAnalyticsInitialized) {
        ReactGA.initialize(this.props.data_admin.idGoogleAnalytics);
        this.setState({googleAnalyticsInitialized: true});
    }
}
</code>```

Thanks to @Chukwuemeka Onyenezido who helped me and directed me on the right way.

Body:
I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).

So, I would like to create a text field in backoffice which value is saved in database.

Then in the front side, I initialize react-ga only if I have a value in database.

To achieve this, I'm trying do this in componentDidUpdate in App.jsx.

I retrieve all my data set in backoffice via :

componentDidMount() {
    // I get my data in this.props.data_admin
    this.props.list_admin();
}

Then in componentDidUpdate(prevProps, prevState) I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :

componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin) {
        // this.props.data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(this.props.data_admin.trackingNumber);
    }
}

But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done.
How can I check if react-ga is already initialized ?

Thanks for your help

Body:
Finally what I did :

I called this.props.list_admin(); in App.jsx constructor and I created a state variable initialized at false :

constructor(props) {
    super(props);

    this.state = {
        googleAnalyticsInitialized: false,
    };

    this.props.list_admin();
}

Then, in componentDidupdate I checked values from this.props.data_admin and if googleAnalyticsInitialized is false. If it is, I initialiaze Google Analytics with the ID received from the call to the API :

componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin && this.props.data_admin.idGoogleAnalytics && !this.state.googleAnalyticsInitialized) {
        ReactGA.initialize(this.props.data_admin.idGoogleAnalytics);
        this.setState({googleAnalyticsInitialized: true});
    }
}

Thanks to @Chukwuemeka Onyenezido who helped me and directed me on the right way.


问:
How can I use datetime.strptime on a string in the format '0000-00-00T00:00:00+00:00'?
Due to my application's circumstances, I would prefer to use datetime.strptime instead of dateutil.parser.

After looking at the docs, I thought that %Y-%m-%dT%H:%M:%S%z may be the proper format for parsing a date string like this. Yet it still gives me an error.

Example

from datetime import datetime

d = '0000-00-00T00:00:00+00:00'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')
```

```ValueError: time data '0000-00-00T00:00:00+00:00' does not
            match format '%Y-%m-%dT%H:%M:%S%z'
```

答:
The easiest way to deal with timezones is to use dateutil.parser:

```<code>from dateutil.parser import parse
date_obj = parse('1970-01-01T00:00:00+00:00')

date_obj

> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=tzutc())
</code>```

But you have to pass a valid datetime-value (not only zeros...)

If you want to use strptime(), the timezone has to be in the format 0000 not 00:00, so this works:

```<code>d = '1900-02-05T11:43:32+0000'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')

> datetime.datetime(1900, 2, 5, 11, 43, 32, tzinfo=datetime.timezone.utc)
</code>```

Body:
Due to my application's circumstances, I would prefer to use datetime.strptime instead of dateutil.parser.

After looking at the docs, I thought that %Y-%m-%dT%H:%M:%S%z may be the proper format for parsing a date string like this. Yet it still gives me an error.

Example

from datetime import datetime

d = '0000-00-00T00:00:00+00:00'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')

ValueError: time data '0000-00-00T00:00:00+00:00' does not
            match format '%Y-%m-%dT%H:%M:%S%z'

Body:
The easiest way to deal with timezones is to use dateutil.parser:

from dateutil.parser import parse
date_obj = parse('1970-01-01T00:00:00+00:00')

date_obj

> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=tzutc())

But you have to pass a valid datetime-value (not only zeros...)

If you want to use strptime(), the timezone has to be in the format 0000 not 00:00, so this works:

d = '1900-02-05T11:43:32+0000'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')

> datetime.datetime(1900, 2, 5, 11, 43, 32, tzinfo=datetime.timezone.utc)


问:
how to read an lxml.objectify.ObjectifiedElement object with django-piston?
I am trying to make a django-piston API which reads another API and presents it in a different format (reads an XML-only API and presents it in JSON). But I am having trouble, because the way I am doing it I just an empty string.

Here is my handler:

```<code>class MyHandler(BaseHandler):
methods_allowed = ('GET')

def read(self, request, my_argument):

    my_node = get_node(my_argument)
    return my_node
</code>```

The get_node function is just a function which gets the object from the other API, and that is an lxml object:

```<code>In [27]: type(my_node)
Out[27]: <type 'lxml.objectify.ObjectifiedElement'>
</code>```

In my urls.py I have:

```<code>from django.conf.urls.defaults import *
from piston.resource import Resource
from api.handlers import MyHandler

class CsrfExemptResource( Resource ):
    def __init__( self, handler, authentication = None ):
        super( CsrfExemptResource, self ).__init__( handler, authentication )
        self.csrf_exempt = getattr( self.handler, 'csrf_exempt', True )

my_resource = CsrfExemptResource( MyHandler )

urlpatterns = patterns( '',
    url( r'^api/(?P<my_argument>.*)/$', my_resource ),
)
</code>```

And when I visit that URL (with the right argument, which given directly to get_node gives a correct object), I just get an empty string.

How to make it work?

答:
It depends on what you need from that lxml.objectify.ObjectifiedElement. If you want to get the text content from that element you can access it via

```<code>my_node.text
</code>```

If you want an attribute value you can access it via:

```<code>my_node.attrib['nameofattribute']
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to make a django-piston API which reads another API and presents it in a different format (reads an XML-only API and presents it in JSON). But I am having trouble, because the way I am doing it I just an empty string.

Here is my handler:

class MyHandler(BaseHandler):
methods_allowed = ('GET')

def read(self, request, my_argument):

    my_node = get_node(my_argument)
    return my_node

The get_node function is just a function which gets the object from the other API, and that is an lxml object:

In [27]: type(my_node)
Out[27]: <type 'lxml.objectify.ObjectifiedElement'>

In my urls.py I have:

from django.conf.urls.defaults import *
from piston.resource import Resource
from api.handlers import MyHandler

class CsrfExemptResource( Resource ):
    def __init__( self, handler, authentication = None ):
        super( CsrfExemptResource, self ).__init__( handler, authentication )
        self.csrf_exempt = getattr( self.handler, 'csrf_exempt', True )

my_resource = CsrfExemptResource( MyHandler )

urlpatterns = patterns( '',
    url( r'^api/(?P<my_argument>.*)/$', my_resource ),
)

And when I visit that URL (with the right argument, which given directly to get_node gives a correct object), I just get an empty string.

How to make it work?

Body:
It depends on what you need from that lxml.objectify.ObjectifiedElement. If you want to get the text content from that element you can access it via

my_node.text

If you want an attribute value you can access it via:

my_node.attrib['nameofattribute']

ContentLicense: CC BY-SA 3.0


问:
Order items in a ItemsControl from right top to left bottom
I'm trying to set a list in an ItemsControl in one of the views of my WPF application.

The problem is I want an other order of my items which are displayed in the control.
Prmiary, the ItemsControl displays items left to right and top to bottom :

```<code>1  2  3  4   5   6
7  8  9  10  11  12
</code>```

However, I want to display my items in a other way - from right top to left bottom - like this :

```<code>11  9   7  5  3  1
12  10  8  6  4  2
</code>```

My current ItemsControl is :

```<code>        Grid.Column="1"
        BorderThickness="1"
        BorderBrush="{DynamicResource WindowTitleColorBrush}">
    <ItemsControl ItemsSource="{Binding Truck.Containers}">
         <ItemsControl.ItemsPanel>
              <ItemsPanelTemplate>
                  <UniformGrid Rows="2" />
              </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
    </ItemsControl>
</Border>
</code>```

I cannot just reorder my list by descending in the viewmodel as it will start with 12 and finish with 1 and not 11 - 2.
Is there an other way to display my list in the order I want ?

答: Just a suggestion to do it in code : split your list even or odd, order this two list by descending then add the elements from the two previous list in a third list bound to your ItemsControl !</p>

Body:
I'm trying to set a list in an ItemsControl in one of the views of my WPF application.

The problem is I want an other order of my items which are displayed in the control.
Prmiary, the ItemsControl displays items left to right and top to bottom :

1  2  3  4   5   6
7  8  9  10  11  12

However, I want to display my items in a other way - from right top to left bottom - like this :

11  9   7  5  3  1
12  10  8  6  4  2

My current ItemsControl is :

        Grid.Column="1"
        BorderThickness="1"
        BorderBrush="{DynamicResource WindowTitleColorBrush}">
    <ItemsControl ItemsSource="{Binding Truck.Containers}">
         <ItemsControl.ItemsPanel>
              <ItemsPanelTemplate>
                  <UniformGrid Rows="2" />
              </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
    </ItemsControl>
</Border>

I cannot just reorder my list by descending in the viewmodel as it will start with 12 and finish with 1 and not 11 - 2.
Is there an other way to display my list in the order I want ?


问:
Easiest way to make complex div with waves
I would like to create divs with complex waves, I'm coming across a lot of tutorials and I tried a lot of things but I can not do it. What is the best way to make waves and the background goes around and stops at the wave? What is the best/simplest way, I heard about the SVG but no skill with that. Is it complicated to realize? I wish I could draw curves and change the background accordingly as on this WordPress theme:
https://www.elegantthemes.com/blog/theme-releases/shape-dividers

I wish I could do that:
http://www.zupimages.net/viewer.php?id=19/22/jr0r.png

I have to learn SVG ? or use illustrator, too complicated directly in CSS if I have several waves. A software like an illustrator to do that for free with SVG exist?

and then do the rest of my style with bootstrap 4 etc? ...thank you

答:
Normally you can do this using Perlin noise. However you can do it also by setting a number of points with successive x and random y on the svg canvas, and connecting the points with Béziers.

let w = 1000;
let h = 300;
svg.setAttributeNS(null,"viewBox",`0 0 ${w} ${h}`)
let n = 18; //number of points
let points = [];// the points array used to draw the curve

// add points to the points array
for(let x=0; x <= w; x+= w/n){
  let y = h - Math.random()*h;
  points.push({x:x,y:y})
}

// a function to connect all the points in the points array with beziers
function  connect(points) {
   let d = "";// the d attribute for the path
   // move to the first point of the array
   d+= `M${points[0].x}, ${points[0].y}`;
    //build the path
    for (var i = 1; i < points.length - 2; i++) {
      var cp = {};
      cp.x = (points[i].x + points[i + 1].x) / 2;
      cp.y = (points[i].y + points[i + 1].y) / 2;

      d+=`Q${points[i].x},${points[i].y} ${cp.x},${cp.y}`
    }
    //the last curve
    let index = points.length-2
   d+=`Q${points[index].x},${points[index].y} ${points[index + 1].x},${points[index + 1].y}`;
   //close the path
   d+=`V${h}H0z`
    return d;
  }
//set the attribute `d` for the wave
wave.setAttributeNS(null,"d",connect(points))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{border:1px solid}</code>```

<svg id="svg" >
  <path id="wave" />
</svg>```

Body:
Normally you can do this using Perlin noise. However you can do it also by setting a number of points with successive x and random y on the svg canvas, and connecting the points with Béziers.

let w = 1000;
let h = 300;
svg.setAttributeNS(null,"viewBox",`0 0 ${w} ${h}`)
let n = 18; //number of points
let points = [];// the points array used to draw the curve

// add points to the points array
for(let x=0; x <= w; x+= w/n){
  let y = h - Math.random()*h;
  points.push({x:x,y:y})
}

// a function to connect all the points in the points array with beziers
function  connect(points) {
   let d = "";// the d attribute for the path
   // move to the first point of the array
   d+= `M${points[0].x}, ${points[0].y}`;
    //build the path
    for (var i = 1; i < points.length - 2; i++) {
      var cp = {};
      cp.x = (points[i].x + points[i + 1].x) / 2;
      cp.y = (points[i].y + points[i + 1].y) / 2;

      d+=`Q${points[i].x},${points[i].y} ${cp.x},${cp.y}`
    }
    //the last curve
    let index = points.length-2
   d+=`Q${points[index].x},${points[index].y} ${points[index + 1].x},${points[index + 1].y}`;
   //close the path
   d+=`V${h}H0z`
    return d;
  }
//set the attribute `d` for the wave
wave.setAttributeNS(null,"d",connect(points))

svg{border:1px solid}

<svg id="svg" >
  <path id="wave" />
</svg>


问:
SQL like NOT IN clause for PySpark data frames
In SQL, we can for example, do select * from table where col1 not in ('A','B');

I was wondering if there is a PySpark equivalent for this. I was able to find the isin function for SQL like IN clause, but nothing for NOT IN.

答:
Alternatively, you can do this: </p>

```<code>df = df.filter(df.sbg_digitalId.isin(1, 2, 3) == False)
</code>```

Body:
Alternatively, you can do this:

df = df.filter(df.sbg_digitalId.isin(1, 2, 3) == False)


问:
SVG.js 3 with Angular 7 "has no compatible call signatures" error
I'm using Angular 7 and have been able to use SVG.js v2.* but I've been unable to get SVG.js v3.* to work. I've made two github projects, the first show SVG.js v2 working angular7-svgjs2, and the second shows SVG.js v3 not working with the only thing changed being the imported library angular7-svgjs3

Using SVG.js 2.7* (This works)

```<code>import { Component, AfterContentInit } from '@angular/core';

import * as SVGjs from 'svg.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  title = 'angular7-svgjs2';

  ngAfterContentInit () {
    let draw = SVGjs('drawing');
    let rect = draw.rect(100, 100);
  }
}
</code>```

Using SVG.js 3.0.* (This fails)

```<code>import { Component, AfterContentInit } from '@angular/core';

import * as SVGjs from '@svgdotjs/svg.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  title = 'angular7-svgjs3';

  ngAfterContentInit () {
    let draw = SVGjs('drawing');
    let rect = draw.rect(100, 100);
  }
}
</code>```

Here is the failure when running "ng serve" in the second example

答:
On my end I do that to use svg.js 3.x in my project:

import * as SvgJs from '@svgdotjs/svg.js';

this.svgContainer = SvgJs.SVG(this.svgElement.nativeElement);
```

After it's your choice how you want to import classes/methods, my solution (the one you basically have) requires you to use the namespace to access them. The one from @Fuzzyma requires you to import one by one everything you want to use.

Body:
I'm using Angular 7 and have been able to use SVG.js v2.* but I've been unable to get SVG.js v3.* to work. I've made two github projects, the first show SVG.js v2 working angular7-svgjs2, and the second shows SVG.js v3 not working with the only thing changed being the imported library angular7-svgjs3

Using SVG.js 2.7* (This works)

import { Component, AfterContentInit } from '@angular/core';

import * as SVGjs from 'svg.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  title = 'angular7-svgjs2';

  ngAfterContentInit () {
    let draw = SVGjs('drawing');
    let rect = draw.rect(100, 100);
  }
}

Using SVG.js 3.0.* (This fails)

import { Component, AfterContentInit } from '@angular/core';

import * as SVGjs from '@svgdotjs/svg.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  title = 'angular7-svgjs3';

  ngAfterContentInit () {
    let draw = SVGjs('drawing');
    let rect = draw.rect(100, 100);
  }
}

Here is the failure when running "ng serve" in the second example

Body:
On my end I do that to use svg.js 3.x in my project:

import * as SvgJs from '@svgdotjs/svg.js';

this.svgContainer = SvgJs.SVG(this.svgElement.nativeElement);

After it's your choice how you want to import classes/methods, my solution (the one you basically have) requires you to use the namespace to access them. The one from @Fuzzyma requires you to import one by one everything you want to use.


问:
Decoding/Encoding an array of mixed objects from JSON data
I'm having trouble implementing the proper way of parsing the incoming JSON data into codeable objects because of an array which has mixed objects and I'm unable to figure out how to parse that array into an array with their respective object types.

I tried following the suggestion from here, since it seems to be similar but with no luck.
Reddit link to tried solution.

I also red this article, and the ones it references.
Article link.

But I'm just very confused what thing I have to exactly implement due to my inexperience with swift and being a newcomer to it.

Using dummy data, my incoming JSON data looks like this.

My Swift model also contains several nested structs, but I don't have a problem with those, so I will only paste the relevant bits. But basically it looks like this:

struct Message: Codable {
    let messageID: Int
    let appVersion: String
    let certaintyFactor: Int
    let comments: String?
    let defaultPriority: String
    let explanation: [Explanation]
    let name: String
    let patient: [PatientInfo]
    let risk: String
    let rule: Rule
    let urgency: String

struct Explanation: Codable {
    let id, name: String
    let content: Resource

    private enum CodingKeys: String, CodingKey {
        case id
        case name
        case content
    }
}
```

<p>And the models for the objects which a 'Resource' could be</p>

<pre class="lang-swift prettyprint-override"><code>struct Patient: Codable{
    let id: String
    let text: Text
    let identifier: [Identifier]
    let active: Bool
    let name: [Name]
    let telecom: [Identifier]
    let gender, birthDate: String
    let deceasedBoolean: Bool
    let address: [Address]
    let maritalStatus: MaritalStatus
    let multipleBirthBoolean: Bool
    let contact: [Contact]
    let communication: [Communication]
    let managingOrganization: ManagingOrganization

    enum CodingKeys: CodingKey {
        case id
        case text
        case identifier
        case active
        case name
        case telecom
        case gender
        case birthDate
        case deceasedBoolean
        case address
        case maritalStatus
        case multipleBirthBoolean
        case contact
        case communication
        case managingOrganization
    }

}

struct Address: Codable {
    let use: String
    let line: [String]
    let city, postalCode, country: String
}

struct Communication: Codable {
    let language: MaritalStatus
    let preferred: Bool
}

struct MaritalStatus: Codable {
    let coding: [MaritalStatusCoding]
    let text: String
}

struct MaritalStatusCoding: Codable {
    let system: String
    let code, display: String
}

struct Contact: Codable {
    let relationship: [Relationship]
    let name: Name
    let telecom: [Identifier]
}

struct Name: Codable {
    let use, family: String
    let given: [String]
    let suffix: [String]?
}

struct Relationship: Codable {
    let coding: [RelationshipCoding]
}

struct RelationshipCoding: Codable {
    let system: String
    let code: String
}

struct ManagingOrganization: Codable {
    let reference, display: String
}
</code>```

```<code>struct MedicationRequest: Codable {
    let resourceType, id: String
    let text: Text
    let contained: [Contained]
    let identifier: [Identifier]
    let status, intent: String
    let medicationReference: MedicationReference
    let subject, context: Context
    let authoredOn: String
    let requester: Requester
    let dosageInstruction: [DosageInstruction]
    let dispenseRequest: DispenseRequest
    let substitution: Substitution

    enum CodingKeys: String, CodingKey {
        case resourceType
        case id
        case text
        case contained
        case identifier
        case status
        case intent
        case medicationReference
        case subject
        case context
        case authoredOn
        case requester
        case dosageInstruction
        case dispenseRequest
        case substitution
    }
}

struct Contained: Codable {
    let resourceType, id: String
    let code: Reason
}

struct Reason: Codable {
    let coding: [Coding]
}

struct Coding: Codable {
    let system: String
    let code, display: String
    let type: String?
}

struct Context: Codable {
    let reference, display: String
}

struct DispenseRequest: Codable {
    let validityPeriod: Period
    let numberOfRepeatsAllowed: Int
    let quantity, expectedSupplyDuration: ExpectedSupplyDuration
}

struct ExpectedSupplyDuration: Codable {
    let value: Int
    let unit: String
    let system: String
    let code: String
}

struct Period: Codable {
    let start, end: String
}

struct DosageInstruction: Codable {
    let sequence: Int
    let text: String
    let additionalInstruction: [Reason]
    let timing: Timing
    let asNeededCodeableConcept, route: Reason
    let doseQuantity, maxDosePerAdministration: ExpectedSupplyDuration
}

struct Timing: Codable {
    let timingRepeat: Repeat

    enum CodingKeys: String, CodingKey {
        case timingRepeat = "repeat"
    }
}

struct Repeat: Codable {
    let boundsPeriod: Period
    let frequency, period, periodMax: Int
    let periodUnit: String
}

struct MedicationReference: Codable {
    let reference: String
}

struct Requester: Codable {
    let agent: Context
    let onBehalfOf: MedicationReference
}

struct Substitution: Codable {
    let allowed: Bool
    let reason: Reason
}

//// MARK: - Text
struct Text: Codable {
    let status, div: String

    enum CodingKeys: String, CodingKey {
        case status,div
    }
}

// MARK: - Identifier
struct Identifier: Codable {
    let use: String
    let system: String
    let value: String
}
</code>```

The parsing part

let jsonData = try? JSON(parseJSON: rowData).rawData()
let message = try? JSONDecoder().decode(Message.self, from: jsonData!)
```

<p>And finally my tested solution which I'm not able to get working because I don't know how to exactly write the encoder.
I'm trying to follow a similar example, explained here</p>

<pre class="lang-swift prettyprint-override"><code>enum Resource{
    case patient(Patient)
    case medicationRequest(MedicationRequest)
}

extension Resource :Codable {
    enum CodingKeys: CodingKey {
        case patient
        case medicationRequest
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do {
            let leftValue =  try container.decode(Patient.self, forKey: .patient)
            self = .patient(leftValue)
        } catch {
            let rightValue =  try container.decode(MedicationRequest.self, forKey: .medicationRequest)
            self = .medicationRequest(rightValue)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        switch self {
        case .patient(let value):
            try container.encode(value, forKey: .patient)
        case .medicationRequest(let value):
            try container.encode(value, forKey: .medicationRequest)
        }
    }
}
</code>```

答: One thing I noticed that jsonResponse of explanation key holds an array of dictionary but, both dictionaries should have the same set of key and different value pairs. But it's not. so you can't be able to decode it until it's the same I hope it helps you.</p>

Body:
I'm having trouble implementing the proper way of parsing the incoming JSON data into codeable objects because of an array which has mixed objects and I'm unable to figure out how to parse that array into an array with their respective object types.

I tried following the suggestion from here, since it seems to be similar but with no luck.
Reddit link to tried solution.

I also red this article, and the ones it references.
Article link.

But I'm just very confused what thing I have to exactly implement due to my inexperience with swift and being a newcomer to it.

Using dummy data, my incoming JSON data looks like this.

My Swift model also contains several nested structs, but I don't have a problem with those, so I will only paste the relevant bits. But basically it looks like this:

struct Message: Codable {
    let messageID: Int
    let appVersion: String
    let certaintyFactor: Int
    let comments: String?
    let defaultPriority: String
    let explanation: [Explanation]
    let name: String
    let patient: [PatientInfo]
    let risk: String
    let rule: Rule
    let urgency: String

struct Explanation: Codable {
    let id, name: String
    let content: Resource

    private enum CodingKeys: String, CodingKey {
        case id
        case name
        case content
    }
}

And the models for the objects which a 'Resource' could be

struct Patient: Codable{
    let id: String
    let text: Text
    let identifier: [Identifier]
    let active: Bool
    let name: [Name]
    let telecom: [Identifier]
    let gender, birthDate: String
    let deceasedBoolean: Bool
    let address: [Address]
    let maritalStatus: MaritalStatus
    let multipleBirthBoolean: Bool
    let contact: [Contact]
    let communication: [Communication]
    let managingOrganization: ManagingOrganization

    enum CodingKeys: CodingKey {
        case id
        case text
        case identifier
        case active
        case name
        case telecom
        case gender
        case birthDate
        case deceasedBoolean
        case address
        case maritalStatus
        case multipleBirthBoolean
        case contact
        case communication
        case managingOrganization
    }

}

struct Address: Codable {
    let use: String
    let line: [String]
    let city, postalCode, country: String
}

struct Communication: Codable {
    let language: MaritalStatus
    let preferred: Bool
}

struct MaritalStatus: Codable {
    let coding: [MaritalStatusCoding]
    let text: String
}

struct MaritalStatusCoding: Codable {
    let system: String
    let code, display: String
}

struct Contact: Codable {
    let relationship: [Relationship]
    let name: Name
    let telecom: [Identifier]
}

struct Name: Codable {
    let use, family: String
    let given: [String]
    let suffix: [String]?
}

struct Relationship: Codable {
    let coding: [RelationshipCoding]
}

struct RelationshipCoding: Codable {
    let system: String
    let code: String
}

struct ManagingOrganization: Codable {
    let reference, display: String
}

struct MedicationRequest: Codable {
    let resourceType, id: String
    let text: Text
    let contained: [Contained]
    let identifier: [Identifier]
    let status, intent: String
    let medicationReference: MedicationReference
    let subject, context: Context
    let authoredOn: String
    let requester: Requester
    let dosageInstruction: [DosageInstruction]
    let dispenseRequest: DispenseRequest
    let substitution: Substitution

    enum CodingKeys: String, CodingKey {
        case resourceType
        case id
        case text
        case contained
        case identifier
        case status
        case intent
        case medicationReference
        case subject
        case context
        case authoredOn
        case requester
        case dosageInstruction
        case dispenseRequest
        case substitution
    }
}

struct Contained: Codable {
    let resourceType, id: String
    let code: Reason
}

struct Reason: Codable {
    let coding: [Coding]
}

struct Coding: Codable {
    let system: String
    let code, display: String
    let type: String?
}

struct Context: Codable {
    let reference, display: String
}

struct DispenseRequest: Codable {
    let validityPeriod: Period
    let numberOfRepeatsAllowed: Int
    let quantity, expectedSupplyDuration: ExpectedSupplyDuration
}

struct ExpectedSupplyDuration: Codable {
    let value: Int
    let unit: String
    let system: String
    let code: String
}

struct Period: Codable {
    let start, end: String
}

struct DosageInstruction: Codable {
    let sequence: Int
    let text: String
    let additionalInstruction: [Reason]
    let timing: Timing
    let asNeededCodeableConcept, route: Reason
    let doseQuantity, maxDosePerAdministration: ExpectedSupplyDuration
}

struct Timing: Codable {
    let timingRepeat: Repeat

    enum CodingKeys: String, CodingKey {
        case timingRepeat = "repeat"
    }
}

struct Repeat: Codable {
    let boundsPeriod: Period
    let frequency, period, periodMax: Int
    let periodUnit: String
}

struct MedicationReference: Codable {
    let reference: String
}

struct Requester: Codable {
    let agent: Context
    let onBehalfOf: MedicationReference
}

struct Substitution: Codable {
    let allowed: Bool
    let reason: Reason
}

//// MARK: - Text
struct Text: Codable {
    let status, div: String

    enum CodingKeys: String, CodingKey {
        case status,div
    }
}

// MARK: - Identifier
struct Identifier: Codable {
    let use: String
    let system: String
    let value: String
}

The parsing part

let jsonData = try? JSON(parseJSON: rowData).rawData()
let message = try? JSONDecoder().decode(Message.self, from: jsonData!)

And finally my tested solution which I'm not able to get working because I don't know how to exactly write the encoder.
I'm trying to follow a similar example, explained here

enum Resource{
    case patient(Patient)
    case medicationRequest(MedicationRequest)
}

extension Resource :Codable {
    enum CodingKeys: CodingKey {
        case patient
        case medicationRequest
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do {
            let leftValue =  try container.decode(Patient.self, forKey: .patient)
            self = .patient(leftValue)
        } catch {
            let rightValue =  try container.decode(MedicationRequest.self, forKey: .medicationRequest)
            self = .medicationRequest(rightValue)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        switch self {
        case .patient(let value):
            try container.encode(value, forKey: .patient)
        case .medicationRequest(let value):
            try container.encode(value, forKey: .medicationRequest)
        }
    }
}


问:
How to handle two different times if they are not in the same day?
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .</p>

```<code>   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

</code>```

答:
You can use date along with the time.
Or you can also convert the date and time to epoch and then try comparing

For Eg-

```<code>let d1= new Date('1-1-2019').getTime(); //1546281000000
let d2= new Date('1-2-2019').getTime(); //1546367400000

let current_time= new Date().getTime(); // gives current epoch
</code>```

Now you can write a function to check if the current_time is between d1 and d2.

Body:
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

Body:
You can use date along with the time.
Or you can also convert the date and time to epoch and then try comparing

For Eg-

let d1= new Date('1-1-2019').getTime(); //1546281000000
let d2= new Date('1-2-2019').getTime(); //1546367400000

let current_time= new Date().getTime(); // gives current epoch

Now you can write a function to check if the current_time is between d1 and d2.


问:
Change an object passed by pointer to a function
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

```<code>#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}
</code>```

How make the output in the func2 5, cause now it's 2?

答:
here is another possibility using pointers </p>

```<code>Grid *  func1();
void func2(Grid * g);

int main ()
{

    Grid * g = func1();
    func2(g);
}

Grid * func1 ()
{
    Grid * g = new Grid();
    g->a = 5;
    return g;
}

void func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}
</code>```

Body:
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}

How make the output in the func2 5, cause now it's 2?

Body:
here is another possibility using pointers

Grid *  func1();
void func2(Grid * g);

int main ()
{

    Grid * g = func1();
    func2(g);
}

Grid * func1 ()
{
    Grid * g = new Grid();
    g->a = 5;
    return g;
}

void func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}


问:
Django shell: Model-to-string with unicode fails / fails not
can someone give me a hint why the umlaut in the model instance's name is turned to garbage once but printed correctly when the unicode() is 'print()'ed?

```<code>class Geo(Position):
    name = models.CharField(max_length = 161)

    def __unicode__(self):
        return u'%s' % self.name
</code>```

In shell:

```<code>In [10]: Geo.objects.get(pk=1)
Out[10]: <Geo: Eichst├ñtt>
In [11]: print Geo.objects.get(pk=1).__unicode__()
Eichstätt
</code>```

答:
If you leave off the __unicode__() from the end of your print statement, you will find it still works correctly. That's because that method is automatically invoked when you call print.

When you just type the name of the object in the interpreter, the method that is invoked is __repr__.

Note that Django's model instances all use unicode internally, so actually your __unicode__ method could just be return self.name.

Body:
can someone give me a hint why the umlaut in the model instance's name is turned to garbage once but printed correctly when the unicode() is 'print()'ed?

class Geo(Position):
    name = models.CharField(max_length = 161)

    def __unicode__(self):
        return u'%s' % self.name

In shell:

In [10]: Geo.objects.get(pk=1)
Out[10]: <Geo: Eichst├ñtt>
In [11]: print Geo.objects.get(pk=1).__unicode__()
Eichstätt


问:
How to keep quality after image scaling animation in Android?
I have bad image quality after image scaling 2 times bigger. Is there any way to keep its quality? Without scaling it looks great.

I tried to increase image dimensions but with no affect.

java code:

ImageView imgView = findViewById(R.id.image_1);
Animation scaleAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale);
scaleAnimation.setFillAfter(true);
imgView.startAnimation(scaleAnimation);
```

<p>scale.xml code:</p>

<pre class="lang-xml prettyprint-override"><code>    <scale
        android:duration="200"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toXScale="2.0"
        android:toYScale="2.0">
    </scale>
</code>```

答:
Try to use svg file format for the drawable. It can scale to any size without losing quality.

Or double the height and width values of the ImageView at your xml layout then change the scaleX and scaleY values to 0.5 on your activity's onCreate to change the size to its normal size. And you can double its size without losing quality.

Body:
I have bad image quality after image scaling 2 times bigger. Is there any way to keep its quality? Without scaling it looks great.

I tried to increase image dimensions but with no affect.

java code:

ImageView imgView = findViewById(R.id.image_1);
Animation scaleAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale);
scaleAnimation.setFillAfter(true);
imgView.startAnimation(scaleAnimation);

scale.xml code:

    <scale
        android:duration="200"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toXScale="2.0"
        android:toYScale="2.0">
    </scale>


问:
React router Link; activeClassName not working
I have a navigation component which renders each navigation link.
The return of this component looks like this:

```<code>     return (
        <li key={`nav-list-${el.title}-${index}`}>
          <Link to={{pathname: '/c/' + el.urlkey}}
                activeClassName={s.active}>{el.title}</Link>
          {subNav}
        </li>
      );
</code>```

The active class is only set on a page refresh. When clicking through the links the active indicator stays at the initial link.

I'm not using Redux so it doesn't seem to be related to this issue: activeClassName does not work on the sideMenu when clicking on the link

My route look like this:

```<code>      <Route path="/c/:category(/:title)" component={CategoryView} name="category" />
</code>```

using React-Router 2.8.1 and browserHistory

答:
Instructions

Use <NavLink> instead of <Link> and add exact as a property

Include exact as a property to ensure activeClassName only triggers on url paths that match your location exactly

Example

```<code><NavLink exact activeClassName="active" to="/path1">
<NavLink exact activeClassName="active" to="/path2">
</code>```

Source

https://reacttraining.com/react-router/web/api/NavLink/exact-bool

exact: bool

When true, the active class/style will only be applied if the location is matched exactly.

Body:
I have a navigation component which renders each navigation link.
The return of this component looks like this:

     return (
        <li key={`nav-list-${el.title}-${index}`}>
          <Link to={{pathname: '/c/' + el.urlkey}}
                activeClassName={s.active}>{el.title}</Link>
          {subNav}

      );

The active class is only set on a page refresh. When clicking through the links the active indicator stays at the initial link.

I'm not using Redux so it doesn't seem to be related to this issue: activeClassName does not work on the sideMenu when clicking on the link

My route look like this:

      <Route path="/c/:category(/:title)" component={CategoryView} name="category" />

using React-Router 2.8.1 and browserHistory

Body:
Instructions

Use <NavLink> instead of <Link> and add exact as a property

Include exact as a property to ensure activeClassName only triggers on url paths that match your location exactly

Example

<NavLink exact activeClassName="active" to="/path1">
<NavLink exact activeClassName="active" to="/path2">

Source

https://reacttraining.com/react-router/web/api/NavLink/exact-bool

exact: bool

When true, the active class/style will only be applied if the location is matched exactly.


问:
Automatonymous Quick Start does not compile
Please see the code below, which I took from the latest quick start tutorials:

```<code>//the messages
public class BasicRequest :
    CorrelatedBy<Guid>
{
    public Guid CorrelationId { get;set; }
    public string Text { get; set; }
}
public class BasicResponse :
    CorrelatedBy<Guid>
{
    public Guid CorrelationId { get; set; }
    public string Text { get; set; }
}

//the responder
public class Program
{
    public static void Main()
    {
        Bus.Initialize(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.UseMulticastSubscriptionClient();
            sbc.ReceiveFrom("msmq://localhost/message_responder");
            sbc.Subscribe(subs=>
            {
                subs.Handler<RequestMessage>(msg=> Bus.Instance.MessageContext<RequestMessage>().Respond(new BasiceResponse{Text = "RESP"+msg.Text}));
            });
        });
    }
}

//the requester
public class Program
{
    public static void Main()
    {
        Bus.Initialize(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.UseMulticastSubscriptionClient();
            sbc.ReceiveFrom("msmq://localhost/message_requestor");
        });

        Bus.Instance.PublishRequest(new RequestMessage(), x =>
        {
            x.Handle<ResponseMessage>(message => Console.WriteLine(message.Text));
            x.SetTimeout(30.Seconds());
        });
    }
}
</code>```

I took the code from here: https://automatonymous.readthedocs.io/en/latest/overview/request.html

The errors I get are:

1) Bus does not contain a definition for initialise

2) RequestMessage cannot be found

A lot of other webpages reference Bus.Initialise: https://automatonymous.readthedocs.io/en/latest/overview/saga.html

答:
You seem to have found documentation that is beyond ancient. The fact you are using MSMQ clearly indicates it's a version of MassTransit that is many years out of being supported.

Documentation on using state machines with MassTransit:
http://masstransit-project.com/MassTransit/advanced/sagas/automatonymous.html

Samples that use state machines with MassTransit:
https://github.com/MassTransit/TheCoffeeShop

https://github.com/phatboyg/Demo-Registration

You'll have better luck working with the latest version of MassTransit.

Body:
Please see the code below, which I took from the latest quick start tutorials:

//the messages
public class BasicRequest :
    CorrelatedBy<Guid>
{
    public Guid CorrelationId { get;set; }
    public string Text { get; set; }
}
public class BasicResponse :
    CorrelatedBy<Guid>
{
    public Guid CorrelationId { get; set; }
    public string Text { get; set; }
}

//the responder
public class Program
{
    public static void Main()
    {
        Bus.Initialize(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.UseMulticastSubscriptionClient();
            sbc.ReceiveFrom("msmq://localhost/message_responder");
            sbc.Subscribe(subs=>
            {
                subs.Handler<RequestMessage>(msg=> Bus.Instance.MessageContext<RequestMessage>().Respond(new BasiceResponse{Text = "RESP"+msg.Text}));
            });
        });
    }
}

//the requester
public class Program
{
    public static void Main()
    {
        Bus.Initialize(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.UseMulticastSubscriptionClient();
            sbc.ReceiveFrom("msmq://localhost/message_requestor");
        });

        Bus.Instance.PublishRequest(new RequestMessage(), x =>
        {
            x.Handle<ResponseMessage>(message => Console.WriteLine(message.Text));
            x.SetTimeout(30.Seconds());
        });
    }
}

I took the code from here: https://automatonymous.readthedocs.io/en/latest/overview/request.html

The errors I get are:

1) Bus does not contain a definition for initialise

2) RequestMessage cannot be found

A lot of other webpages reference Bus.Initialise: https://automatonymous.readthedocs.io/en/latest/overview/saga.html


问:
Getting negative cosine distance using tensorflow
I am using tf.losses.cosine_distance(Y, outputs, axis=2, reduction=tf.losses.Reduction.MEAN) to measure the difference between my labels and predictions. The tensor shape is [batch_size, sequence_length, embedding]. In my case, the shape of the prediction is [16311, 20, 100].

My result is as follow.

```<code>----------------------epoch1----------------------
train 1  loss 1.1429076
----------------------epoch2----------------------
train 2  loss 0.51511204
----------------------epoch3----------------------
train 3  loss -2.5750072
----------------------epoch4----------------------
train 4  loss -6.685198
----------------------epoch5----------------------
train 5  loss -10.863398
</code>```

The boundary of cosine similarity is [0,1]. But in my case, it is larger than 1 at the beginning and became negative after several epochs. I wonder why these could happen.

My embedding contains negative numbers. Should I normalise it before calculating the cosine distance?

答:
First, yes, you should normalize before computing cosine distance: (from the documentation)

Note that the function assumes that predictions and labels are already
  unit-normalized.

However, the range of the cosine similarity function is not [0,1]. Consider the vectors (1 0) and (-1 0). Both are unit vectors and their cosine similarity is -1.

Finally, notice that the loss is computing cosine distance, which is 1 minus cosine similarity because the optimization operation for losses is minimization and not maximization (as would be appropriate for cosine similarity). So you would expect to get negative numbers getting increasingly bigger in absolute value.

Body:
I am using tf.losses.cosine_distance(Y, outputs, axis=2, reduction=tf.losses.Reduction.MEAN) to measure the difference between my labels and predictions. The tensor shape is [batch_size, sequence_length, embedding]. In my case, the shape of the prediction is [16311, 20, 100].

My result is as follow.

----------------------epoch1----------------------
train 1  loss 1.1429076
----------------------epoch2----------------------
train 2  loss 0.51511204
----------------------epoch3----------------------
train 3  loss -2.5750072
----------------------epoch4----------------------
train 4  loss -6.685198
----------------------epoch5----------------------
train 5  loss -10.863398

The boundary of cosine similarity is [0,1]. But in my case, it is larger than 1 at the beginning and became negative after several epochs. I wonder why these could happen.

My embedding contains negative numbers. Should I normalise it before calculating the cosine distance?


问:
Zero an array in C code

Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

```<code>arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
</code>```

This is the long way... I need it the short way.

答:
man bzero</p>

```<code>NAME
   bzero - write zero-valued bytes

SYNOPSIS
   #include <strings.h>

   void bzero(void *s, size_t n);

DESCRIPTION
   The  bzero()  function sets the first n bytes of the byte area starting
   at s to zero (bytes containing '\0').
</code>```

Title: Zero an array in C code

Body:
Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;

This is the long way... I need it the short way.

Body:
man bzero

NAME
   bzero - write zero-valued bytes

SYNOPSIS
   #include <strings.h>

   void bzero(void *s, size_t n);

DESCRIPTION
   The  bzero()  function sets the first n bytes of the byte area starting
   at s to zero (bytes containing '\0').


问:
Google Ads : tracking events
I'm little confused with Google services.
I want to track conversion events.

I've already configured the script like that :

```<code><!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
</code>```

My Google Tag Manager account is configured with deux services : Analytics and Ads

I've configured conversion event on Google Ads and I try to push it through Javascript calls, but maybe I'm wrong somewhere.

Here is my Javascript code :

```<code>gtag('send', <event_action>, {
  'event_category': <event_category>,
  'event_label': <event_label>,
  'value': <event_value
});
</code>```

At the end of the day, I have no conversion on my dashboard on Google Ads.

Can someone helps with to figure out what's wrong ?

答:
Shouldn't it be event instead of send?

```<code>gtag('event', <action>, {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});
</code>```

reference

Title: Google Ads : tracking events

Body:
I'm little confused with Google services.
I want to track conversion events.

I've already configured the script like that :

My Google Tag Manager account is configured with deux services : Analytics and Ads

I've configured conversion event on Google Ads and I try to push it through Javascript calls, but maybe I'm wrong somewhere.

Here is my Javascript code :

gtag('send', <event_action>, {
  'event_category': <event_category>,
  'event_label': <event_label>,
  'value': <event_value
});

At the end of the day, I have no conversion on my dashboard on Google Ads.

Can someone helps with to figure out what's wrong ?

Body:
Shouldn't it be event instead of send?

gtag('event', <action>, {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});

reference


问:
How to send the element object as parameter to javascript function without ID
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

```<code><td ...... >
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXX">

<td ......
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXXX">
</code>```

Based on clicked ....> I would like to hide/show it (or to show/hide next class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

```<code>function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}
</code>```

答:
I can't tell by OP if the td are being used in a tr and the tr in a table as it should so I'll just mention real quick that it's invalid HTML should there be any td without a tr as a parent and it's invalid HTML having a tr without a table as its ancestor.

If starting at a tag nested within a td you'll need to climb out:

```<code>$(this).closest('td')...
</code>```

Once at the cell level look around for the cells to the left: ....prev('td'), or to the right: ....next('td') or both: ....siblings('td'). Then go down each td and find the link nested within and turn it off/on: ....find('.gLR').fadeToggle();

```<code>$(this).closest('td').siblings('td').find('.gLR').fadeToggle();
</code>```

$('.gLR').not('.g5').hide();

$('.gLR').on('click', function(e) {

  if ($(this).hasClass('g5')) {
    $('.gDir').fadeToggle();
  } else if ($(this).hasClass('g1') || $(this).hasClass('g9')) {
    const cell = $(this).closest('td');
    cell.siblings('td').find('.gLR').fadeToggle();
  } else if ($(this).hasClass('g4')) {
    $(this).closest('td').prev('td').find('.gLR').fadeToggle();
  } else if ($(this).hasClass('g6')) {
    $(this).closest('td').next('td').find('.gLR').fadeToggle();
  } else {
    return false;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  font: 700 5vw/1.5 Consolas
}

table {
  table-layout: fixed;
  border-collapse: collapse;
}

td {
  width: 20%;
  text-align: center
}

a {
  display: block;
  height: 10vh;
  text-decoration: none;
  color: cyan;
}

a:hover {
  color: tomato;
}

a.g5:hover {
  font-size: 0;
}

a.g5:hover::after {
  content: '\1f536';
  font-size: 5vw;
}

td b {
  display: block;
  height: 10vh;
}</code>```

    ⮝

    ⮜

    ⮞

    ⮟

```

Body:
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

<td ......

Based on clicked  I would like to hide/show it (or to show/hide next <a class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}

Body:
I can't tell by OP if the td are being used in a tr and the tr in a table as it should so I'll just mention real quick that it's invalid HTML should there be any td without a tr as a parent and it's invalid HTML having a tr without a table as its ancestor.

If starting at a tag nested within a td you'll need to climb out:

$(this).closest('td')...

Once at the cell level look around for the cells to the left: ....prev('td'), or to the right: ....next('td') or both: ....siblings('td'). Then go down each td and find the link nested within and turn it off/on: ....find('.gLR').fadeToggle();

$(this).closest('td').siblings('td').find('.gLR').fadeToggle();

$('.gLR').not('.g5').hide();

$('.gLR').on('click', function(e) {

  if ($(this).hasClass('g5')) {
    $('.gDir').fadeToggle();
  } else if ($(this).hasClass('g1') || $(this).hasClass('g9')) {
    const cell = $(this).closest('td');
    cell.siblings('td').find('.gLR').fadeToggle();
  } else if ($(this).hasClass('g4')) {
    $(this).closest('td').prev('td').find('.gLR').fadeToggle();
  } else if ($(this).hasClass('g6')) {
    $(this).closest('td').next('td').find('.gLR').fadeToggle();
  } else {
    return false;
  }
});

:root {
  font: 700 5vw/1.5 Consolas
}

table {
  table-layout: fixed;
  border-collapse: collapse;
}

td {
  width: 20%;
  text-align: center
}

a {
  display: block;
  height: 10vh;
  text-decoration: none;
  color: cyan;
}

a:hover {
  color: tomato;
}

a.g5:hover {
  font-size: 0;
}

a.g5:hover::after {
  content: '\1f536';
  font-size: 5vw;
}

td b {
  display: block;
  height: 10vh;
}

<table>
  <tr class='gRA'>
    <td colspan='2'>
      <b><a href='#/' class="gLR g0"></a></b>
    </td>
    <td><b><a href='#/' class="gLR gDir g1">⮝</a></b></td>
    <td colspan='2'>
      <b><a href='#/' class="gLR g2"></a></b>
    </td>
  </tr>
  <tr class='gRB'>
    <td><b><a href='#/' class="gLR g3"></a></b></td>
    <td><b><a href='#/' class="gLR gDir g4">⮜</a></b></td>
    <td><b><a href='#/' class="gLR g5"></a></b></td>
    <td><b><a href='#/' class="gLR gDir g6">⮞</a></b></td>
    <td><b><a href='#/' class="gLR g7"></a></b></td>
  </tr>
  <tr class='gRC'>
    <td colspan='2'>
      <b><a href='#/' class="gLR g8"></a></b>
    </td>
    <td><b><a href='#/' class="gLR gDir g9">⮟</a></b></td>
    <td colspan='2'>
      <b><a href='#/' class="gLR g10"></a></b>
    </td>
  </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Treeview expand/collapse stops working after checking a checkbox
I have some code for showing a tree made with a
 list, and I need 2 buttons for expanding and collapsing all of the tree items. This button works correctly
but I have problems when I click on a checkbox in my
 tag. After that the 2 buttons do not work

If you check the result code and use the expand and collapse button you'll find my problem.

At first this button works very well, but when we clicked on a checkbox the buttons do not work at all.

$(function() {
  $("#tree-collapse-all").click(function() {
    $(".tree input").removeAttr("checked");
  });

  $("#tree-expand-all").click(function() {
    $(".tree input").attr("checked", "checked");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ol,
ul {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  list-style: none;
}

body {
  margin: 30px;
  font-family: sans-serif;
}

#fontSizeWrapper {
  font-size: 16px;
}

#fontSize {
  width: 100px;
  font-size: 1em;
}

/* ————————————————————–
  Tree core styles
*/

.tree {
  margin: 1em;
}

.tree input {
  position: absolute;
  clip: rect(0, 0, 0, 0);
}

.tree input~ul {
  display: none;
}

.tree input:checked~ul {
  display: block;
}

/* ————————————————————–
  Tree rows
*/

.tree li {
  line-height: 1.2;
  position: relative;
  padding: 0 0 1em 1em;
}

.tree ul li {
  padding: 1em 0 0 1em;
}

.tree>li:last-child {
  padding-bottom: 0;
}

/* ————————————————————–
  Tree labels
*/

.tree_label {
  position: relative;
  display: inline-block;
  background: #fff;
}

label.tree_label {
  cursor: pointer;
}

label.tree_label:hover {
  color: #666;
}

/* ————————————————————–
  Tree expanded icon
*/

label.tree_label:before {
  background: #000;
  color: #fff;
  position: relative;
  z-index: 1;
  float: left;
  margin: 0 1em 0 -2em;
  width: 1em;
  height: 1em;
  border-radius: 1em;
  content: '+';
  text-align: center;
  line-height: .9em;
}

:checked~label.tree_label:before {
  content: '–';
}

/* ————————————————————–
  Tree branches
*/

.tree li:before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -.5em;
  display: block;
  width: 0;
  border-left: 1px solid rgb(7, 240, 112);
  content: "";
}

.tree_label:after {
  position: absolute;
  top: 0;
  left: -1.5em;
  display: block;
  height: 0.5em;
  width: 1em;
  border-bottom: 1px solid rgb(79, 7, 247);
  border-left: 1px solid rgb(240, 6, 6);
  border-radius: 0 0 0 .3em;
  content: '';
}

label.tree_label:after {
  border-bottom: 0;
}

:checked~label.tree_label:after {
  border-radius: 0 .3em 0 0;
  border-top: 1px solid rgb(79, 7, 247);
  border-right: 1px solid rgb(240, 6, 6);
  border-bottom: 0;
  border-left: 0;
  bottom: 0;
  top: 0.5em;
  height: auto;
}

.tree li:last-child:before {
  height: 1em;
  bottom: auto;
}

.tree>li:last-child:before {
  display: none;
}

.tree_custom {
  display: block;
  background: #eee;
  padding: 1em;
  border-radius: 0.3em;
}</code>```

Expand all | Collapse all

  Font size
  <input type="range" value="1" id="fontSize" step="0.5" min="0.5" max="5" />

    <input type="checkbox" id="c1" />
    Level 0

        <input type="checkbox" id="c2" />
        Level 1

Level 2

Level 2

        <input type="checkbox" id="c3" />
        Looong level 1
label text
with line-breaks

Level 2

            <input type="checkbox" id="c4" />
            Specified tree item view

Level 3

    <input type="checkbox" id="c5" />
    Level 0

        <input type="checkbox" id="c6" />
        Level 1

Level 2

        <input type="checkbox" id="c7" />
        Level 1

Level 2

            <input type="checkbox" id="c8" />
            Level 2

Level 3

```

答:
The issue is because you're using the checked attribute, which is not amended when a checkbox is interacted with by the user.

If you change your logic to work with the checked property of the element itself then the logic works correctly:

$(function() {
  $("#tree-collapse-all").click(function() {
    $(".tree input").prop('checked', false);
  });

  $("#tree-expand-all").click(function() {
    $(".tree input").prop("checked", true);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ol,
ul {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  list-style: none;
}

body {
  margin: 30px;
  font-family: sans-serif;
}

#fontSizeWrapper {
  font-size: 16px;
}

#fontSize {
  width: 100px;
  font-size: 1em;
}

/* ————————————————————–
  Tree core styles
*/

.tree {
  margin: 1em;
}

.tree input {
  position: absolute;
  clip: rect(0, 0, 0, 0);
}

.tree input~ul {
  display: none;
}

.tree input:checked~ul {
  display: block;
}

/* ————————————————————–
  Tree rows
*/

.tree li {
  line-height: 1.2;
  position: relative;
  padding: 0 0 1em 1em;
}

.tree ul li {
  padding: 1em 0 0 1em;
}

.tree>li:last-child {
  padding-bottom: 0;
}

/* ————————————————————–
  Tree labels
*/

.tree_label {
  position: relative;
  display: inline-block;
  background: #fff;
}

label.tree_label {
  cursor: pointer;
}

label.tree_label:hover {
  color: #666;
}

/* ————————————————————–
  Tree expanded icon
*/

label.tree_label:before {
  background: #000;
  color: #fff;
  position: relative;
  z-index: 1;
  float: left;
  margin: 0 1em 0 -2em;
  width: 1em;
  height: 1em;
  border-radius: 1em;
  content: '+';
  text-align: center;
  line-height: .9em;
}

:checked~label.tree_label:before {
  content: '–';
}

/* ————————————————————–
  Tree branches
*/

.tree li:before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -.5em;
  display: block;
  width: 0;
  border-left: 1px solid rgb(7, 240, 112);
  content: "";
}

.tree_label:after {
  position: absolute;
  top: 0;
  left: -1.5em;
  display: block;
  height: 0.5em;
  width: 1em;
  border-bottom: 1px solid rgb(79, 7, 247);
  border-left: 1px solid rgb(240, 6, 6);
  border-radius: 0 0 0 .3em;
  content: '';
}

label.tree_label:after {
  border-bottom: 0;
}

:checked~label.tree_label:after {
  border-radius: 0 .3em 0 0;
  border-top: 1px solid rgb(79, 7, 247);
  border-right: 1px solid rgb(240, 6, 6);
  border-bottom: 0;
  border-left: 0;
  bottom: 0;
  top: 0.5em;
  height: auto;
}

.tree li:last-child:before {
  height: 1em;
  bottom: auto;
}

.tree>li:last-child:before {
  display: none;
}

.tree_custom {
  display: block;
  background: #eee;
  padding: 1em;
  border-radius: 0.3em;
}</code>```

Expand all | Collapse all

  Font size
  <input type="range" value="1" id="fontSize" step="0.5" min="0.5" max="5" />

    <input type="checkbox" id="c1" />
    Level 0

        <input type="checkbox" id="c2" />
        Level 1

Level 2

Level 2

        <input type="checkbox" id="c3" />
        Looong level 1
label text
with line-breaks

Level 2

            <input type="checkbox" id="c4" />
            Specified tree item view

Level 3

    <input type="checkbox" id="c5" />
    Level 0

        <input type="checkbox" id="c6" />
        Level 1

Level 2

        <input type="checkbox" id="c7" />
        Level 1

Level 2

            <input type="checkbox" id="c8" />
            Level 2

Level 3

```

Body:
I have some code for showing a tree made with a
 list, and I need 2 buttons for expanding and collapsing all of the tree items. This button works correctly
but I have problems when I click on a checkbox in my
 tag. After that the 2 buttons do not work

If you check the result code and use the expand and collapse button you'll find my problem.

At first this button works very well, but when we clicked on a checkbox the buttons do not work at all.

$(function() {
  $("#tree-collapse-all").click(function() {
    $(".tree input").removeAttr("checked");
  });

  $("#tree-expand-all").click(function() {
    $(".tree input").attr("checked", "checked");
  });
});

ol,
ul {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  list-style: none;
}

body {
  margin: 30px;
  font-family: sans-serif;
}

#fontSizeWrapper {
  font-size: 16px;
}

#fontSize {
  width: 100px;
  font-size: 1em;
}

/* ————————————————————–
  Tree core styles
*/

.tree {
  margin: 1em;
}

.tree input {
  position: absolute;
  clip: rect(0, 0, 0, 0);
}

.tree input~ul {
  display: none;
}

.tree input:checked~ul {
  display: block;
}

/* ————————————————————–
  Tree rows
*/

.tree li {
  line-height: 1.2;
  position: relative;
  padding: 0 0 1em 1em;
}

.tree ul li {
  padding: 1em 0 0 1em;
}

.tree>li:last-child {
  padding-bottom: 0;
}

/* ————————————————————–
  Tree labels
*/

.tree_label {
  position: relative;
  display: inline-block;
  background: #fff;
}

label.tree_label {
  cursor: pointer;
}

label.tree_label:hover {
  color: #666;
}

/* ————————————————————–
  Tree expanded icon
*/

label.tree_label:before {
  background: #000;
  color: #fff;
  position: relative;
  z-index: 1;
  float: left;
  margin: 0 1em 0 -2em;
  width: 1em;
  height: 1em;
  border-radius: 1em;
  content: '+';
  text-align: center;
  line-height: .9em;
}

:checked~label.tree_label:before {
  content: '–';
}

/* ————————————————————–
  Tree branches
*/

.tree li:before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -.5em;
  display: block;
  width: 0;
  border-left: 1px solid rgb(7, 240, 112);
  content: "";
}

.tree_label:after {
  position: absolute;
  top: 0;
  left: -1.5em;
  display: block;
  height: 0.5em;
  width: 1em;
  border-bottom: 1px solid rgb(79, 7, 247);
  border-left: 1px solid rgb(240, 6, 6);
  border-radius: 0 0 0 .3em;
  content: '';
}

label.tree_label:after {
  border-bottom: 0;
}

:checked~label.tree_label:after {
  border-radius: 0 .3em 0 0;
  border-top: 1px solid rgb(79, 7, 247);
  border-right: 1px solid rgb(240, 6, 6);
  border-bottom: 0;
  border-left: 0;
  bottom: 0;
  top: 0.5em;
  height: auto;
}

.tree li:last-child:before {
  height: 1em;
  bottom: auto;
}

.tree>li:last-child:before {
  display: none;
}

.tree_custom {
  display: block;
  background: #eee;
  padding: 1em;
  border-radius: 0.3em;
}

Expand all | Collapse all

  Font size
  <input type="range" value="1" id="fontSize" step="0.5" min="0.5" max="5" />

    <input type="checkbox" id="c1" />
    Level 0

        <input type="checkbox" id="c2" />
        Level 1

Level 2

Level 2

        <input type="checkbox" id="c3" />
        Looong level 1
label text
with line-breaks

Level 2

            <input type="checkbox" id="c4" />
            Specified tree item view

Level 3

    <input type="checkbox" id="c5" />
    Level 0

        <input type="checkbox" id="c6" />
        Level 1

Level 2

        <input type="checkbox" id="c7" />
        Level 1

Level 2

            <input type="checkbox" id="c8" />
            Level 2

Level 3

Body:
The issue is because you're using the checked attribute, which is not amended when a checkbox is interacted with by the user.

If you change your logic to work with the checked property of the element itself then the logic works correctly:

$(function() {
  $("#tree-collapse-all").click(function() {
    $(".tree input").prop('checked', false);
  });

  $("#tree-expand-all").click(function() {
    $(".tree input").prop("checked", true);
  });
});

ol,
ul {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  list-style: none;
}

body {
  margin: 30px;
  font-family: sans-serif;
}

#fontSizeWrapper {
  font-size: 16px;
}

#fontSize {
  width: 100px;
  font-size: 1em;
}

/* ————————————————————–
  Tree core styles
*/

.tree {
  margin: 1em;
}

.tree input {
  position: absolute;
  clip: rect(0, 0, 0, 0);
}

.tree input~ul {
  display: none;
}

.tree input:checked~ul {
  display: block;
}

/* ————————————————————–
  Tree rows
*/

.tree li {
  line-height: 1.2;
  position: relative;
  padding: 0 0 1em 1em;
}

.tree ul li {
  padding: 1em 0 0 1em;
}

.tree>li:last-child {
  padding-bottom: 0;
}

/* ————————————————————–
  Tree labels
*/

.tree_label {
  position: relative;
  display: inline-block;
  background: #fff;
}

label.tree_label {
  cursor: pointer;
}

label.tree_label:hover {
  color: #666;
}

/* ————————————————————–
  Tree expanded icon
*/

label.tree_label:before {
  background: #000;
  color: #fff;
  position: relative;
  z-index: 1;
  float: left;
  margin: 0 1em 0 -2em;
  width: 1em;
  height: 1em;
  border-radius: 1em;
  content: '+';
  text-align: center;
  line-height: .9em;
}

:checked~label.tree_label:before {
  content: '–';
}

/* ————————————————————–
  Tree branches
*/

.tree li:before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -.5em;
  display: block;
  width: 0;
  border-left: 1px solid rgb(7, 240, 112);
  content: "";
}

.tree_label:after {
  position: absolute;
  top: 0;
  left: -1.5em;
  display: block;
  height: 0.5em;
  width: 1em;
  border-bottom: 1px solid rgb(79, 7, 247);
  border-left: 1px solid rgb(240, 6, 6);
  border-radius: 0 0 0 .3em;
  content: '';
}

label.tree_label:after {
  border-bottom: 0;
}

:checked~label.tree_label:after {
  border-radius: 0 .3em 0 0;
  border-top: 1px solid rgb(79, 7, 247);
  border-right: 1px solid rgb(240, 6, 6);
  border-bottom: 0;
  border-left: 0;
  bottom: 0;
  top: 0.5em;
  height: auto;
}

.tree li:last-child:before {
  height: 1em;
  bottom: auto;
}

.tree>li:last-child:before {
  display: none;
}

.tree_custom {
  display: block;
  background: #eee;
  padding: 1em;
  border-radius: 0.3em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><a href="#" id="tree-expand-all">Expand all</a> | <a href="#" id="tree-collapse-all">Collapse all</a></p>

<br /><br />
<div id="fontSizeWrapper">
  <label for="fontSize">Font size</label>
  <input type="range" value="1" id="fontSize" step="0.5" min="0.5" max="5" />
</div>
<ul class="tree">
  <li>
    <input type="checkbox" id="c1" />
    <label class="tree_label" for="c1">Level 0</label>
    <ul>
      <li>
        <input type="checkbox" id="c2" />
        <label for="c2" class="tree_label">Level 1</label>
        <ul>
          <li><span class="tree_label">Level 2</span></li>
          <li><span class="tree_label">Level 2</span></li>
        </ul>
      </li>
      <li>
        <input type="checkbox" id="c3" />
        <label for="c3" class="tree_label">Looong level 1 <br />label text <br />with line-breaks</label>
        <ul>
          <li><span class="tree_label">Level 2</span></li>
          <li>
            <input type="checkbox" id="c4" />
            <label for="c4" class="tree_label"><span class="tree_custom">Specified tree item view</span></label>
            <ul>
              <li><span class="tree_label">Level 3</span></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>
    <input type="checkbox" id="c5" />
    <label class="tree_label" for="c5">Level 0</label>
    <ul>
      <li>
        <input type="checkbox" id="c6" />
        <label for="c6" class="tree_label">Level 1</label>
        <ul>
          <li><span class="tree_label">Level 2</span></li>
        </ul>
      </li>
      <li>
        <input type="checkbox" id="c7" />
        <label for="c7" class="tree_label">Level 1</label>
        <ul>
          <li><span class="tree_label">Level 2</span></li>
          <li>
            <input type="checkbox" id="c8" />
            <label for="c8" class="tree_label">Level 2</label>
            <ul>
              <li><span class="tree_label">Level 3</span></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>


问:
Problems when creating a huge matrix
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

```<code>#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}
</code>```

Thanks in advance for all your help!

答:
If you are working with huge matrix you should use linked list.
example</p>

Title: Problems when creating a huge matrix

Body:
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}

Thanks in advance for all your help!


问:
How to get the list of items in a transaction in package arules
I know you can see the content of each transaction using inspect and then extract the items yourself, but is there a convenient way to get a list of all items which belong to a transaction?

答:
A possible simple solution if your goal is just to see all of the items contained across all transactions (that is, a complete item list) is the following:</p>

```<code>unique(unlist(as(a_list, "list")))
</code>```

Body:
A possible simple solution if your goal is just to see all of the items contained across all transactions (that is, a complete item list) is the following:

unique(unlist(as(a_list, "list")))


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
Others provided you with various method for doing your task. I want to explain why your 1st method do not work as intended:

```<code>upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if word.rfind(upper):
</code>```

.rfind method of str is looking for position of last substring ABCDEFGHIJKLMNOPQRSTUVWXYZ inside word. I guess that your words do NOT contain such substring, in which case .rfind returns -1, which according to rules of Python evaluate to True (as it is not zero), so it would catch almost any word (it will give 0 or False only for words starting with ABCDEFGHIJKLMNOPQRSTUVWXYZ and containing only single ABCDEFGHIJKLMNOPQRSTUVWXYZ)

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
Others provided you with various method for doing your task. I want to explain why your 1st method do not work as intended:

upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if word.rfind(upper):

.rfind method of str is looking for position of last substring ABCDEFGHIJKLMNOPQRSTUVWXYZ inside word. I guess that your words do NOT contain such substring, in which case .rfind returns -1, which according to rules of Python evaluate to True (as it is not zero), so it would catch almost any word (it will give 0 or False only for words starting with ABCDEFGHIJKLMNOPQRSTUVWXYZ and containing only single ABCDEFGHIJKLMNOPQRSTUVWXYZ)