问:
Creating a builder with some constants and other variables
```<code>kotlin 1.3.61
</code>```

I have the following class and not sure if its the best design for creating a builder. Basically, the sales and product will have different constants for the icon and background. But the title and description can be changed. There could be other constants added i.e. technical. So the user of this class doesn't have to worry how this constants are created.

But the title and address need to be provided from outside of the class. In creating my builder I have used the copy to update the title and description. And not sure if this is the best way to do do this?

```<code>class Marketing {
    data class Model(
        val title: String = "",
        val description: String = "",
        val icon: Int,
        val background: Int)

    class Builder() {
        private var title: String = ""
        private var description: String = ""

        private val PRODUCT = Model(
            icon = 111111,
            background = 333333)

        private val SALES = Model(
            icon = 222222,
            background = 444444)

        fun title(title: String): Builder {
            this.title = title
            return this
        }

        fun description(description: String): Builder {
            this.description = description
            return this
        }

        fun buildProduct(): Model {
            return PRODUCT.copy(title = title, description = description)
        }

        fun buildSales(): Model {
            return SALES.copy(title = title, description = description)
        }
    }
}
</code>```

And I am using it like this:

```<code>val product = Marketing.Builder()
    .description("this is the description of the product")
    .title("this is the title of the product")
    .buildProduct()

val sales = Marketing.Builder()
    .description("this is the description of the sales")
    .title("this is the title of the sales")
    .buildSales()
</code>```

As you can see its easy to create different products by calling the appropriate builder i.e. buildProduct() and buildSales()

Many thanks for any suggestions to make this better

答:
I'd like to say that it is not safe to use single builder to build multiple types. It would be better to separate it into specific classes, maybe with some shared base class. So my answer is:

Model classes

```<code>open class BaseModel(val icon: Int, val background: Int)
class ProductModel(val title: String, val description: String, icon: Int, background: Int) : BaseModel(icon, background)
class SalesModel(val title: String, val description: String, icon: Int, background: Int) : BaseModel(icon, background)
</code>```

Builders

```<code>abstract class BaseBuilder<T : BaseModel> {
    abstract var icon: Int
    abstract var background: Int

    abstract fun build(): T
}

class ProductBuilder : BaseBuilder<ProductModel>() {
    override var icon = 222222
    override var background = 444444
    var title = ""
    var description = ""

    override fun build() = ProductModel(title, description, icon, background)
}

class SalesBuilder : BaseBuilder<SalesModel>() {
    override var icon = 111111
    override var background = 333333
    var title = ""
    var description = ""

    override fun build() = SalesModel(title, description, icon, background)
}
</code>```

And finally, Marketing class

```<code>class Marketing {
    companion object {
        fun buildProduct(filler: ProductBuilder.() -> Unit) : ProductModel {
            return ProductBuilder().run {
                filler()
                build()
            }
        }
        fun buildSales(filler: SalesBuilder.() -> Unit) : SalesModel {
            return SalesBuilder().run {
                filler()
                build()
            }
        }
    }
}
</code>```

In this way you can create models easily and safe:

```<code>val product = Marketing.buildProduct {
    title = "title"
    description = "descr"
}
</code>```

Mandatory field

If you want to make some property unchancheable, you can replace it from var property into constructor with val. Example for title property:

Builder

```<code>class ProductBuilder(val title: String) : BaseBuilder<ProductModel>() {
    override var icon = 111111
    override var background = 333333

    var description = ""

    override fun build() = ProductModel(title, description, icon, background)
}
</code>```

Builder calling

```<code>fun buildProduct(title: String, filler: ProductBuilder.() -> Unit) : ProductModel {
    return ProductBuilder(title).run {
        filler()
        build()
    }
}
</code>```

Using

```<code>val product = Marketing.buildProduct("title") {
    //title = "title" - this line wouldn't be compiled anymore
    description = "descr"
}
</code>```

Body:
kotlin 1.3.61

I have the following class and not sure if its the best design for creating a builder. Basically, the sales and product will have different constants for the icon and background. But the title and description can be changed. There could be other constants added i.e. technical. So the user of this class doesn't have to worry how this constants are created.

But the title and address need to be provided from outside of the class. In creating my builder I have used the copy to update the title and description. And not sure if this is the best way to do do this?

class Marketing {
    data class Model(
        val title: String = "",
        val description: String = "",
        val icon: Int,
        val background: Int)

    class Builder() {
        private var title: String = ""
        private var description: String = ""

        private val PRODUCT = Model(
            icon = 111111,
            background = 333333)

        private val SALES = Model(
            icon = 222222,
            background = 444444)

        fun title(title: String): Builder {
            this.title = title
            return this
        }

        fun description(description: String): Builder {
            this.description = description
            return this
        }

        fun buildProduct(): Model {
            return PRODUCT.copy(title = title, description = description)
        }

        fun buildSales(): Model {
            return SALES.copy(title = title, description = description)
        }
    }
}

And I am using it like this:

val product = Marketing.Builder()
    .description("this is the description of the product")
    .title("this is the title of the product")
    .buildProduct()

val sales = Marketing.Builder()
    .description("this is the description of the sales")
    .title("this is the title of the sales")
    .buildSales()

As you can see its easy to create different products by calling the appropriate builder i.e. buildProduct() and buildSales()

Many thanks for any suggestions to make this better

Body:
I'd like to say that it is not safe to use single builder to build multiple types. It would be better to separate it into specific classes, maybe with some shared base class. So my answer is:

Model classes

open class BaseModel(val icon: Int, val background: Int)
class ProductModel(val title: String, val description: String, icon: Int, background: Int) : BaseModel(icon, background)
class SalesModel(val title: String, val description: String, icon: Int, background: Int) : BaseModel(icon, background)

Builders

abstract class BaseBuilder<T : BaseModel> {
    abstract var icon: Int
    abstract var background: Int

    abstract fun build(): T
}

class ProductBuilder : BaseBuilder<ProductModel>() {
    override var icon = 222222
    override var background = 444444
    var title = ""
    var description = ""

    override fun build() = ProductModel(title, description, icon, background)
}

class SalesBuilder : BaseBuilder<SalesModel>() {
    override var icon = 111111
    override var background = 333333
    var title = ""
    var description = ""

    override fun build() = SalesModel(title, description, icon, background)
}

And finally, Marketing class

class Marketing {
    companion object {
        fun buildProduct(filler: ProductBuilder.() -> Unit) : ProductModel {
            return ProductBuilder().run {
                filler()
                build()
            }
        }
        fun buildSales(filler: SalesBuilder.() -> Unit) : SalesModel {
            return SalesBuilder().run {
                filler()
                build()
            }
        }
    }
}

In this way you can create models easily and safe:

val product = Marketing.buildProduct {
    title = "title"
    description = "descr"
}

Mandatory field

If you want to make some property unchancheable, you can replace it from var property into constructor with val. Example for title property:

Builder

class ProductBuilder(val title: String) : BaseBuilder<ProductModel>() {
    override var icon = 111111
    override var background = 333333

    var description = ""

    override fun build() = ProductModel(title, description, icon, background)
}

Builder calling

fun buildProduct(title: String, filler: ProductBuilder.() -> Unit) : ProductModel {
    return ProductBuilder(title).run {
        filler()
        build()
    }
}

Using

val product = Marketing.buildProduct("title") {
    //title = "title" - this line wouldn't be compiled anymore
    description = "descr"
}


来源: stackexchange

问:
Fullcalendar 4 not working today in a custom buttom
I have a custom button that i want to go today day.

```<code> customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          calendar.fullCalendar('today');
        }
      }
    }
</code>```

But my error is a fullCalendar('today') dont exist on v4. I can do this the other way

答:
You're correct that calendar.fullCalendar('today'); no longer works in version 4. However this is simply due to a change of syntax. It has been directly replaced by the today method. Therefore this code:

```<code>click: function(info) {
  calendar.today();
}
</code>```

will solve your problem.

This change of syntax is explained in the v3 to v4 upgrade guide and there is a more detailed article in the v4 documentation about calling methods as well.

However I'd also like to point out that if all your button does is change to today's date, you don't even need a custom button at all! As documented in the header options you can simply put today as one of the buttons in the header and fullCalendar will auto-generate a button which moves to today's date.

e.g.

```<code>{
  left:   'title',
  center: '',
  right:  'today prev,next'
}
</code>```

This is visible in most of the demos on the fullCalendar site, including the ones on the home page: https://fullcalendar.io/#demos

ContentLicense: CC BY-SA 4.0

Body:
I have a custom button that i want to go today day.

 customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          calendar.fullCalendar('today');
        }
      }
    }

But my error is a fullCalendar('today') dont exist on v4. I can do this the other way

Body:
You're correct that calendar.fullCalendar('today'); no longer works in version 4. However this is simply due to a change of syntax. It has been directly replaced by the today method. Therefore this code:

click: function(info) {
  calendar.today();
}

will solve your problem.

This change of syntax is explained in the v3 to v4 upgrade guide and there is a more detailed article in the v4 documentation about calling methods as well.

However I'd also like to point out that if all your button does is change to today's date, you don't even need a custom button at all! As documented in the header options you can simply put today as one of the buttons in the header and fullCalendar will auto-generate a button which moves to today's date.

e.g.

{
  left:   'title',
  center: '',
  right:  'today prev,next'
}

This is visible in most of the demos on the fullCalendar site, including the ones on the home page: https://fullcalendar.io/#demos


问:
javascript variable value as a link
I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?</p>

```<code>var link = 'new link: <a href="http://test.com/" target="_blank"><b>Clink Here</font></b></a>'
</code>```

答:
You need a container where the HTML will be placed.  If you can use jQuery, this becomes very easy.

```<code><div id="container"></div>

var link = '...';
$('#container').html(link);
</code>```

Working sample: http://jsfiddle.net/mEjUg/

ContentLicense: CC BY-SA 3.0

Title: javascript variable value as a link

Body:
I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?

var link = 'new link: Clink Here'

Body:
You need a container where the HTML will be placed.  If you can use jQuery, this becomes very easy.

<div id="container"></div>

var link = '...';
$('#container').html(link);

Working sample: http://jsfiddle.net/mEjUg/


问:
Error: I18nextWithTranslation suspended while rendering, but no fallback UI was specified
I am trying to get I18N working using react-i18next. I am following the steps provided here as close as possible. I have tried for several hours with lots of googling around and have not yet discovered what I am doing wrong. Any help is appreciated.

I am getting this Error stack trace:

```<code>    Exception has occurred: Error
Error: I18nextWithTranslation suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
    in I18nextWithTranslation (created by App)
    in App
    in Router (created by BrowserRouter)
    in BrowserRouter
    in CookiesProvider
    at throwException (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:45969:13)
    at renderRoot (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47147:11)
    at performWorkOnRoot (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48000:7)
    at performWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47912:7)
    at performSyncWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47886:3)
    at requestWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47755:5)
    at scheduleWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47569:5)
    at scheduleRootUpdate (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48230:3)
    at updateContainerAtExpirationTime (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48258:10)
    at updateContainer (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48315:10)
</code>```

I have a Suspense with fallback at the very top level:

```<code>import React, { Suspense } from 'react';
import ReactDOM from "react-dom";
import { CookiesProvider } from 'react-cookie';
import App from "./App.js";
import { BrowserRouter } from "react-router-dom";
// import i18n (needs to be bundled ;))
import './i18n';

ReactDOM.render(
  <CookiesProvider>
    <BrowserRouter basename="/cgadmin-react-primeng/">
      <Suspense fallback={<Loader />}>
        <App />
      </Suspense>
    </BrowserRouter>
  </CookiesProvider>,
  document.getElementById("root")
);

const Loader = () => (
  <div>loading...</div>
);
</code>```

I am not using hooks, but rather the HOC recomended for use with classes on the App class like this:

```<code>export default withTranslation()(App);
</code>```

答:
If you are using XHR (i18next-xhr-backend), then you need to wrap your app into a Suspense component:</p>

```<code>import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();

  return <h1>{t('Welcome to React')}</h1>
}

// i18n translations might still be loaded by the xhr backend
// use react's Suspense
export default function App() {
  return (
    <Suspense fallback="loading">
      <MyComponent />
    </Suspense>
  );
}
</code>```

Body:
I am trying to get I18N working using react-i18next. I am following the steps provided here as close as possible. I have tried for several hours with lots of googling around and have not yet discovered what I am doing wrong. Any help is appreciated.

I am getting this Error stack trace:

    Exception has occurred: Error
Error: I18nextWithTranslation suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
    in I18nextWithTranslation (created by App)
    in App
    in Router (created by BrowserRouter)
    in BrowserRouter
    in CookiesProvider
    at throwException (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:45969:13)
    at renderRoot (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47147:11)
    at performWorkOnRoot (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48000:7)
    at performWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47912:7)
    at performSyncWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47886:3)
    at requestWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47755:5)
    at scheduleWork (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:47569:5)
    at scheduleRootUpdate (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48230:3)
    at updateContainerAtExpirationTime (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48258:10)
    at updateContainer (https://localhost:3000/cgadmin-react-primeng/dist/bundle.js:48315:10)

I have a Suspense with fallback at the very top level:

import React, { Suspense } from 'react';
import ReactDOM from "react-dom";
import { CookiesProvider } from 'react-cookie';
import App from "./App.js";
import { BrowserRouter } from "react-router-dom";
// import i18n (needs to be bundled ;))
import './i18n';

ReactDOM.render(
  <CookiesProvider>
    <BrowserRouter basename="/cgadmin-react-primeng/">
      <Suspense fallback={<Loader />}>
        <App />
      </Suspense>
    </BrowserRouter>
  </CookiesProvider>,
  document.getElementById("root")
);

const Loader = () => (

loading...

);

I am not using hooks, but rather the HOC recomended for use with classes on the App class like this:

export default withTranslation()(App);

Body:
If you are using XHR (i18next-xhr-backend), then you need to wrap your app into a Suspense component:

import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();

  return <h1>{t('Welcome to React')}</h1>
}

// i18n translations might still be loaded by the xhr backend
// use react's Suspense
export default function App() {
  return (
    <Suspense fallback="loading">
      <MyComponent />
    </Suspense>
  );
}


问:
Scraping job hunting website using BeautifulSoup
I am trying to scrape all the complete job descriptions from this website but I got stuck:
https://www.seek.co.nz/data-analyst-jobs/full-time?daterange=31&salaryrange=70000-999999&salarytype=annual

My logic is to find all the job links on one page first than loop through next pages.

My code looks like this:

```<code>from bs4 import BeautifulSoup
import requests

soup = BeautifulSoup(response.text, 'html.parser')
link_list = []

for a in soup.find_all('a', attrs={'data-automation': 'jobTitle'}, href=True):
    link_list.append('https://www.seek.co.nz/' + a['href'])
print(link_list)
</code>```

The above code looks fine. I can print a list of job links and put them in a list, but the following code only printed out 2 paragraphs then it threw an error:

```<code>for link in link_list:
    response = requests.get(link, 'lxml')
    sp = BeautifulSoup(response.text, 'html.parser')
    table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
    for x in table:
        print(x.find('p').text)

</code>```

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-41-8afe949a9497> in <module>()
      4     table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
      5     for x in table:
----> 6         print(x.find('p').text)

AttributeError: 'NoneType' object has no attribute 'text'
</code>```

Can someone tell me why it didn't work and how to make it right? I am using Python 3 and bs4. Thank you!

答:
Going through the webpage, it is clear that the first two posts that you'll get through soup.find_all('a', attrs={'data-automation': 'jobTitle'}, href=True) are advertisements or promoted posts, and consequently the webpages these two and the other job postings lead to are different. For the latter, perhaps soup.find('div', attrs={'class':'templatetext'}) will do the job.

Hope that helps!

Body:
I am trying to scrape all the complete job descriptions from this website but I got stuck:
https://www.seek.co.nz/data-analyst-jobs/full-time?daterange=31&salaryrange=70000-999999&salarytype=annual

My logic is to find all the job links on one page first than loop through next pages.

My code looks like this:

from bs4 import BeautifulSoup
import requests

soup = BeautifulSoup(response.text, 'html.parser')
link_list = []

for a in soup.find_all('a', attrs={'data-automation': 'jobTitle'}, href=True):
    link_list.append('https://www.seek.co.nz/' + a['href'])
print(link_list)

The above code looks fine. I can print a list of job links and put them in a list, but the following code only printed out 2 paragraphs then it threw an error:

for link in link_list:
    response = requests.get(link, 'lxml')
    sp = BeautifulSoup(response.text, 'html.parser')
    table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
    for x in table:
        print(x.find('p').text)

AttributeError                            Traceback (most recent call last)
<ipython-input-41-8afe949a9497> in <module>()
      4     table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
      5     for x in table:
----> 6         print(x.find('p').text)

AttributeError: 'NoneType' object has no attribute 'text'

Can someone tell me why it didn't work and how to make it right? I am using Python 3 and bs4. Thank you!


问:
Can we connect the gateway only once in hypeledger fabric using node SDK
I need to help with my query which related to hyperledger fabric gateway connection to client though node sdk. I wrote some API's which is connected to the fabric network using below code.

```<code>const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

const gateway = new Gateway();

await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

});
</code>```

Now I have to use the above code to connect each and every time controller which call API's, however, I want to use it onetime so Once the connection made to the network I don't need to connect again and again.
Is there is some way to implement it? if possible suggest to me so I can implement it in my API's.
Please let me know if there is anything more information need?

Thanks in Advance

答:
Gateways are designed to be re-used, in fact you should avoid constantly creating and disconnecting gateways as this can lead to network problems.

The one thing to realise with Gateways is that they have a 1-1 relationship with identities as well as the fabric network (but not channels, a gateway can connect to more than 1 channel) . So the correct use of gateways is to have a gateway for each different identity for your network and re-use this gateway.

If you plan to have a lot of different identities connecting then you may want to consider using a stale policy for gateways as they will keep network connections, so for example if an identity doesn't interact with the network in a while then you could disconnect that gateway and create a new one for that identity when they try to interact later.

Body:
I need to help with my query which related to hyperledger fabric gateway connection to client though node sdk. I wrote some API's which is connected to the fabric network using below code.

const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');

const gateway = new Gateway();

await gateway.connect(ccpPath, {
    wallet,
    identity: Username,
    discovery: {
        enabled: true,
        asLocalhost: false
    }

});

Now I have to use the above code to connect each and every time controller which call API's, however, I want to use it onetime so Once the connection made to the network I don't need to connect again and again.
Is there is some way to implement it? if possible suggest to me so I can implement it in my API's.
Please let me know if there is anything more information need?

Thanks in Advance


问:
Unable to understand why the following JavaScript function is not working
I am new to Java Script and I am unable to understand why the following function is not working, what am I doing wrong here? Its prompting me to enter the var gender value but once I enter it is not executing any further. Given below the JavaScript code I am trying to run.

var gender = prompt('What is your gender..?');

function name(fname = 'Sayantan', mname, lname = 'Choudhury') {
  if (gender == male) {
    document.write('Hello Mr. ' + fname + ' ' + mname + ' ' + lname + '
');
  } else {
    document.write('Hello Mrs. ' + fname + ' ' + mname + ' ' + lname + '
');
  }
}

name('Mridula', 'Dutta', 'Chowdhury');
name('Mridula');```

答:
If you use male as male instead of 'male' javascript thinks that male is a variable declared somewhere in your code and throws an error because it doesn't exist(at least in your case), but what you enter inside prompt is stored in gender variable and it contains the string 'male' which you entered so the condition should be:

```<code>if(gender === 'male')
</code>```

or

```<code>if(gender === 'female')
</code>```

=== compares the type along with value, if you only want to compare the value then you can use ==.

Body:
If you use male as male instead of 'male' javascript thinks that male is a variable declared somewhere in your code and throws an error because it doesn't exist(at least in your case), but what you enter inside prompt is stored in gender variable and it contains the string 'male' which you entered so the condition should be:

if(gender === 'male')

or

if(gender === 'female')

=== compares the type along with value, if you only want to compare the value then you can use ==.


问:
How to divide one dataframe by the other without converting to numpy first?
I have a dataframe with two columns, x and y, and a few hundred rows.
I have another dataframe with only one row and two columns, x and y.

I want to divide column x of the big dataframe by the value in x of the small dataframe, and column y by column y.

If I divide one dataframe by the other, I get all NaNs. For the division to work, I must convert the small dataframe to numpy.

Why can't I divide one dataframe by the other? What am I missing? I have a toy example below.

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame()
r = int(10)
df['x'] = np.arange(0,r)
df['y'] = df['x'] * 2

other_df = pd.DataFrame()
other_df['x'] = [100]
other_df['y'] = [400]

# This doesn't work - I get all nans
new = df / other_df

# this works - it gives me what I want
new2 = df / [100,400]

# this also works
new3 = df / other_df.to_numpy()
</code>```

答:
You can use numpy.divide() to divide as numpy has a great property that is Broadcasting.

```<code>new = np.divide(df,other_df)
</code>```

Please check this link for more details.

Body:
I have a dataframe with two columns, x and y, and a few hundred rows.
I have another dataframe with only one row and two columns, x and y.

I want to divide column x of the big dataframe by the value in x of the small dataframe, and column y by column y.

If I divide one dataframe by the other, I get all NaNs. For the division to work, I must convert the small dataframe to numpy.

Why can't I divide one dataframe by the other? What am I missing? I have a toy example below.

import numpy as np
import pandas as pd

df = pd.DataFrame()
r = int(10)
df['x'] = np.arange(0,r)
df['y'] = df['x'] * 2

other_df = pd.DataFrame()
other_df['x'] = [100]
other_df['y'] = [400]

# This doesn't work - I get all nans
new = df / other_df

# this works - it gives me what I want
new2 = df / [100,400]

# this also works
new3 = df / other_df.to_numpy()

Body:
You can use numpy.divide() to divide as numpy has a great property that is Broadcasting.

new = np.divide(df,other_df)

Please check this link for more details.


问:
Multiple Dropzone in a single page
I'm using Dropzone without creating a dropzone form. It works great for me in this way.

But in this case I can not create another instance of Dropzone in my page.

```<code>var myDropzone1 = new Dropzone(
        document.body,
        {
            url : "upload1"...
            .
            .
            . some parameters
         };

var myDropzone2 = new Dropzone(
        document.body,
        {
            url : "upload'"...
            .
            .
            . some parameters
         };
</code>```

When I do this, I'm getting the error Dropzone already attached.

答:
I want to add something here because I have experienced problems with multiple dropzones on the same page.

In your init code you must remember to include var if putting a reference otherwise it isn't dealing with this instance of the dropzone rather trying to access/relate to the others.

Simple javascript but makes a big difference.

```<code>init:       function(){
    var dzClosure = this;

    $('#Btn').on('click',function(e) {
        dzClosure.processQueue();
    });
</code>```

Title: Multiple Dropzone in a single page

Body:
I'm using Dropzone without creating a dropzone form. It works great for me in this way.

But in this case I can not create another instance of Dropzone in my page.

var myDropzone1 = new Dropzone(
        document.body,
        {
            url : "upload1"...
            .
            .
            . some parameters
         };

var myDropzone2 = new Dropzone(
        document.body,
        {
            url : "upload'"...
            .
            .
            . some parameters
         };

When I do this, I'm getting the error Dropzone already attached.

Body:
I want to add something here because I have experienced problems with multiple dropzones on the same page.

In your init code you must remember to include var if putting a reference otherwise it isn't dealing with this instance of the dropzone rather trying to access/relate to the others.

Simple javascript but makes a big difference.

init:       function(){
    var dzClosure = this;

    $('#Btn').on('click',function(e) {
        dzClosure.processQueue();
    });


问:
Replace value across multiple lines in bash
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

```<code>    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

```<code>pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt
</code>```

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

```<code>./run.sh r.start 0x284569
</code>```

should be

```<code>    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

Here's my best shot for the second part

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

答:
You want sed for this, and don't need a script:

Assuming the text is a file called the_text:

```<code>sed "s/0x256/REPLACETEXT/g" the_text
</code>```

If you ant to do that with out echoing out the text then add a -i

```<code>sed -i "s/0x256/REPLACETEXT/g" the_text
</code>```

It is possible to daisy chain these commands or embed them into single script, this one echoes to the standard out:

```<code>#!/bin/bash

sed "s/0x256/${2}/g" $1
sed "s/0x256/${2}/g" $1
</code>```

Body:
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

./run.sh r.start 0x284569

should be

    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

Here's my best shot for the second part

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

Body:
You want sed for this, and don't need a script:

Assuming the text is a file called the_text:

sed "s/0x256/REPLACETEXT/g" the_text

If you ant to do that with out echoing out the text then add a -i

sed -i "s/0x256/REPLACETEXT/g" the_text

It is possible to daisy chain these commands or embed them into single script, this one echoes to the standard out:

#!/bin/bash

sed "s/0x256/${2}/g" $1
sed "s/0x256/${2}/g" $1


问:
How do you test pages that require authentication with Selenium?
I need to test a web application using Selenium. The app is fairly common in its setup: it requires signing in for most of the functionality to be exposed. Upon loading a page, if the user is not authenticated, it will redirect to a login form and then back to the requested page once credentials are supplied.

What's the usual way to go around this with Selenium? I take it people are not logging in on every single test as this would cause significant overhead on big test suites. Is there a way to set up a session in a test and then use the cookie information for subsequent tests, or do a conditional sign-in (without incurring in massive code repetition!)?

I am using PHPUnit with Selenium ATM.

Thank you!

Gonzalo

答:
If this is basic http auth you can use the username/password with the url request as documented in the Selenium FAQ: http://wiki.openqa.org/display/SEL/Selenium+Core+FAQ#SeleniumCoreFAQ-HowdoIuseSeleniumtologintositesthatrequireHTTPbasicauthentication%28wherethebrowsermakesamodaldialogaskingforcredentials%29%3F

How do I use Selenium to login to
  sites that require HTTP basic
  authentication (where the browser
  makes a modal dialog asking for
  credentials)?

Use a username and password in the
  URL, as described in RFC 1738: Test
  Type        open
    http://myusername:myuserpassword@myexample.com/blah/blah/blah

Note that on Internet Explorer this
  won't work, since Microsoft has
  disabled usernames/passwords in URLs
  in IE. However, you can add that
  functionality back in by modifying
  your registry, as described in the
  linked KB article. Set an
  "iexplore.exe" DWORD to 0 in
  HKEY_CURRENT_USER\Software\Microsoft\Internet
  Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE.

If you don't want to modify the
  registry yourself, you can always just
  use Selenium Remote Control, which
  automatically sets that that registry
  key for you as of version 0.9.2.


问:
How can I calculate pos_weight variable of the tf.nn.weighted_cross_entropy_with_logits for multiple classes?
I want to use tf.nn.weighted_cross_entropy_with_logits.

There are three classes of the dataset. The number of images in class A is 5500, in class B is 2000, and in class C is 20000.

How can I calculate and use pos_weight variable in tf.nn.weighted_cross_entropy_with_logits?

答:
The function tf.nn.weighted_cross_entropy_with_logits is implementing binary cross entropy loss. The loss you are looking for is a "categorical" cross entropy. And if you are looking for a concrete behaviour I recommend you to implement it from scratch.
Here you have what you are asking for:

```<code>>>> import tensorflow as tf
>>> from sklearn.utils.class_weight import compute_class_weight
>>> # Weighted categorical cross entropy
>>> def ce(y_pred, y_true, weights):
...   y_pred = tf.clip_by_value(y_pred, 1e-6, 1 - 1e-6)
...   loss = -tf.math.log(y_pred)
...   loss = y_true * loss
...   loss = weights * loss
...   return tf.reduce_mean(tf.reduce_sum(loss, axis=1))
>>>
# A B C just refers to your classes
>>> weights = compute_class_weight('balanced', [A, B, C], y_true)
>>> y_true = tf.one_hot(y_true, NUM_CLASSES)
>>> y_pred = tf.random.uniform((3, 3)) # Mock predictions (Should be activated by a softmax)
>>> print(y_true.shape, y_pred.shape)
(3, 3) (3, 3)
>>> ce(y_pred, y_true, weights)
<tf.Tensor: id=23, shape=(), dtype=float32, numpy=2.8649616>
</code>```

Body:
The function tf.nn.weighted_cross_entropy_with_logits is implementing binary cross entropy loss. The loss you are looking for is a "categorical" cross entropy. And if you are looking for a concrete behaviour I recommend you to implement it from scratch.
Here you have what you are asking for:

>>> import tensorflow as tf
>>> from sklearn.utils.class_weight import compute_class_weight
>>> # Weighted categorical cross entropy
>>> def ce(y_pred, y_true, weights):
...   y_pred = tf.clip_by_value(y_pred, 1e-6, 1 - 1e-6)
...   loss = -tf.math.log(y_pred)
...   loss = y_true * loss
...   loss = weights * loss
...   return tf.reduce_mean(tf.reduce_sum(loss, axis=1))
>>>
# A B C just refers to your classes
>>> weights = compute_class_weight('balanced', [A, B, C], y_true)
>>> y_true = tf.one_hot(y_true, NUM_CLASSES)
>>> y_pred = tf.random.uniform((3, 3)) # Mock predictions (Should be activated by a softmax)
>>> print(y_true.shape, y_pred.shape)
(3, 3) (3, 3)
>>> ce(y_pred, y_true, weights)
<tf.Tensor: id=23, shape=(), dtype=float32, numpy=2.8649616>


问:
Displaying a video with an alpha channel using qt
I need to display RGBA encoded videos (that is, video with a transparent background) using qt. The idea is to merge videos in real time. I usually use libmpv but it does not seem to be allow rendering transparent background video.
I am trying to use a QMediaPlayer with the following code:

```<code> QMainWindow w;
 w.resize(1920,1080);
 QVideoWidget videoWidget(&w);
 videoWidget.move(0,100);
 videoWidget.resize(1920,1080);
 QMediaPlayer *player = new QMediaPlayer(&w);
 w.resize(w.size());
 player->setMedia( QUrl::fromLocalFile(PATH+"video2.mov") );
 player->setVideoOutput(&videoWidget);
 w.show();
 player->play();
</code>```

This successfully loads the video (which is an RGBA mov video) but fills the video widget with a black background where it should be transparent thus covering any item behind the video player.

Is there any way to actually load a transparent video using QVideoPlayer/QVideoWidget? If not, is there an efficient alternative (I would rather not use a lower level solution such as opencv).

Thanks a lot,

Fred

答:
here's the solution I finally found:

Subclass a QAbstractVideoSurface:

```<code>class alphaVideoDrawer : public QAbstractVideoSurface
{
    Q_OBJECT
public:
    alphaVideoDrawer(QLabel *displayLbl);
private:
    QLabel *displayLbl;

protected:
    bool present(const QVideoFrame &frame);

    QList<QVideoFrame::PixelFormat> supportedPixelFormats(
            QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const
    {
        Q_UNUSED(handleType);
        return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_ARGB32;
    }
};
</code>```

The surface will receive the frame convert and forward it to the qlabel which displays the video.

```<code>alphaVideoDrawer::alphaVideoDrawer(QLabel *displayLbl):displayLbl(displayLbl)
{
}

extern QImage qt_imageFromVideoFrame(const QVideoFrame &f);

bool alphaVideoDrawer::present(const QVideoFrame &frame)
{
    QImage image = qt_imageFromVideoFrame(frame);
    displayLbl->setPixmap(QPixmap::fromImage(image));
    return true;
}
</code>```

Then we subclass a QLabel which will be our video output:

```<code>class alphaVideo : public QLabel
{
    Q_OBJECT
public:
    alphaVideo(QLabel *parent = nullptr);

private:
    alphaVideoDrawer *videoDrawer;
    QMediaPlayer *videoPlayer;
    QMediaPlaylist *playlist;
};
</code>```

It loads the drawer and the player and start playing/rendering the video:

```<code>    alphaVideo::alphaVideo(QLabel *parent): QLabel(parent)
{
    setStyleSheet("QLabel { background-color : transparent; }");
    videoDrawer = new alphaVideoDrawer(this);
    videoPlayer = new QMediaPlayer(this);
    playlist = new QmediaPlaylist();
    videoPlayer->setPlaylist(playlist);
    videoPlayer->setVideoOutput(videoDrawer);
    playlist->addMedia( Qurl::fromLocalFile(“your RGBA video file.mp4”) );
    videoPlayer->play();
}
</code>```

Body:
I need to display RGBA encoded videos (that is, video with a transparent background) using qt. The idea is to merge videos in real time. I usually use libmpv but it does not seem to be allow rendering transparent background video.
I am trying to use a QMediaPlayer with the following code:

 QMainWindow w;
 w.resize(1920,1080);
 QVideoWidget videoWidget(&w);
 videoWidget.move(0,100);
 videoWidget.resize(1920,1080);
 QMediaPlayer *player = new QMediaPlayer(&w);
 w.resize(w.size());
 player->setMedia( QUrl::fromLocalFile(PATH+"video2.mov") );
 player->setVideoOutput(&videoWidget);
 w.show();
 player->play();

This successfully loads the video (which is an RGBA mov video) but fills the video widget with a black background where it should be transparent thus covering any item behind the video player.

Is there any way to actually load a transparent video using QVideoPlayer/QVideoWidget? If not, is there an efficient alternative (I would rather not use a lower level solution such as opencv).

Thanks a lot,

Fred

Body:
here's the solution I finally found:

Subclass a QAbstractVideoSurface:

class alphaVideoDrawer : public QAbstractVideoSurface
{
    Q_OBJECT
public:
    alphaVideoDrawer(QLabel *displayLbl);
private:
    QLabel *displayLbl;

protected:
    bool present(const QVideoFrame &frame);

    QList<QVideoFrame::PixelFormat> supportedPixelFormats(
            QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const
    {
        Q_UNUSED(handleType);
        return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_ARGB32;
    }
};

The surface will receive the frame convert and forward it to the qlabel which displays the video.

alphaVideoDrawer::alphaVideoDrawer(QLabel *displayLbl):displayLbl(displayLbl)
{
}

extern QImage qt_imageFromVideoFrame(const QVideoFrame &f);

bool alphaVideoDrawer::present(const QVideoFrame &frame)
{
    QImage image = qt_imageFromVideoFrame(frame);
    displayLbl->setPixmap(QPixmap::fromImage(image));
    return true;
}

Then we subclass a QLabel which will be our video output:

class alphaVideo : public QLabel
{
    Q_OBJECT
public:
    alphaVideo(QLabel *parent = nullptr);

private:
    alphaVideoDrawer *videoDrawer;
    QMediaPlayer *videoPlayer;
    QMediaPlaylist *playlist;
};

It loads the drawer and the player and start playing/rendering the video:

    alphaVideo::alphaVideo(QLabel *parent): QLabel(parent)
{
    setStyleSheet("QLabel { background-color : transparent; }");
    videoDrawer = new alphaVideoDrawer(this);
    videoPlayer = new QMediaPlayer(this);
    playlist = new QmediaPlaylist();
    videoPlayer->setPlaylist(playlist);
    videoPlayer->setVideoOutput(videoDrawer);
    playlist->addMedia( Qurl::fromLocalFile(“your RGBA video file.mp4”) );
    videoPlayer->play();
}


问:
Markers not working with google-map-react
I'm working with the 'google-map-react' library and I have tried all but the markers are not showing up.
I pass the coords to the marker in many ways but none worked.
Here's my code & repository:

https://github.com/jorginyu/ubica

```<code>import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const API_KEY = 'WTFULOOKINAT';

const contacts = [
  { name: 'Spiderman', lat: 41.529616, lng: 2.434130 },
  { name: 'Iron Man', lat: 41.528103, lng: 2.433834 },
  { name: 'Hulk', lat: 41.530192, lng: 2.422994 }
];

const MarkersC = (text ) => <div className="contact">{text}</div>;

export default class MapComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      center: {
        lat: 41.528452,
        lng: 2.434195
      },
      zoom: 18
    }
  }

  render() {
    return (
      // Important! Always set the container height explicitly
      <div className="mt-5" style={{ height: '80vh', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: API_KEY }}
          defaultCenter={this.state.center}
          defaultZoom={this.state.zoom}
        >
            {contacts.map((contact,i) => {
            <MarkersC  position={{lat: contact.lat, lng: contact.lng}} text={contact.name} key={i} />
          })}

        </GoogleMapReact>
      </div>
    );
  }
}
</code>```

What can I do? Thanks for your time :)

答:
In your question, you have provided invalid GoogleMap key so it is showing error in console Google Maps JavaScript API error: InvalidKeyMapError.

So provide a valid GoogleMap key or blank(const API_KEY = '') for development use only.

In my case with blank API_KEY, it's working fine.

(Your git repo code is different than code you have posted here in StackOverflow.)

Body:
I'm working with the 'google-map-react' library and I have tried all but the markers are not showing up.
I pass the coords to the marker in many ways but none worked.
Here's my code & repository:

https://github.com/jorginyu/ubica

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const API_KEY = 'WTFULOOKINAT';

const contacts = [
  { name: 'Spiderman', lat: 41.529616, lng: 2.434130 },
  { name: 'Iron Man', lat: 41.528103, lng: 2.433834 },
  { name: 'Hulk', lat: 41.530192, lng: 2.422994 }
];

const MarkersC = (text ) =>
{text}
;

export default class MapComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      center: {
        lat: 41.528452,
        lng: 2.434195
      },
      zoom: 18
    }
  }

  render() {
    return (
      // Important! Always set the container height explicitly

        <GoogleMapReact
          bootstrapURLKeys={{ key: API_KEY }}
          defaultCenter={this.state.center}
          defaultZoom={this.state.zoom}
        >
            {contacts.map((contact,i) => {
            <MarkersC  position={{lat: contact.lat, lng: contact.lng}} text={contact.name} key={i} />
          })}

        </GoogleMapReact>

    );
  }
}

What can I do? Thanks for your time :)


问:
How should properly formatted data for NER in BERT look like?
I am using Huggingface's transformers library and want to perform NER using BERT. I tried to find an explicit example of how to properly format the data for NER using BERT. It is not entirely clear to me from the paper and the comments I've found.

Let's say we have a following sentence and labels:

```<code>sent = "John Johanson lives in Ramat Gan."
labels = ['B-PER', 'I-PER', 'O', 'O', 'B-LOC', 'I-LOC']
</code>```

Would data that we input to the model be something like this:

```<code>sent = ['[CLS]', 'john', 'johan',  '##son', 'lives',  'in', 'ramat', 'gan', '.', '[SEP]']
labels = ['O', 'B-PER', 'I-PER', 'I-PER', 'O', 'O', 'B-LOC', 'I-LOC', 'O', 'O']
attention_mask = [0, 1, 1, 1, 1, 1, 1, 1, 1, 0]
sentence_id = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

?

Thank you!

答:
Update 2021-08-27: The tutorial link points to a legacy tutorial, which I don't fully recommend anymore, since it does not use Huggingface's convenience library datasets.

There is actually a great tutorial for the NER example on the huggingface documentation page. Specifically, it also goes into detail how the provided script does the preprocessing. Specifically, there is a link to an external contributor's preprocess.py script, that basically takes the data from the CoNLL 2003 format to whatever is required by the huggingface library. I found this to be the easiest way to assert I have proper formatting, and unless you have some specific changes that you might want to incorporate, this gets you started super quick without worrying about implementation details.

The linked example script also provides more than enough detail on how to feed the respective inputs into the model itself, but generally, you are correct in your above-mentioned input pattern.

Body:
I am using Huggingface's transformers library and want to perform NER using BERT. I tried to find an explicit example of how to properly format the data for NER using BERT. It is not entirely clear to me from the paper and the comments I've found.

Let's say we have a following sentence and labels:

sent = "John Johanson lives in Ramat Gan."
labels = ['B-PER', 'I-PER', 'O', 'O', 'B-LOC', 'I-LOC']

Would data that we input to the model be something like this:

sent = ['[CLS]', 'john', 'johan',  '##son', 'lives',  'in', 'ramat', 'gan', '.', '[SEP]']
labels = ['O', 'B-PER', 'I-PER', 'I-PER', 'O', 'O', 'B-LOC', 'I-LOC', 'O', 'O']
attention_mask = [0, 1, 1, 1, 1, 1, 1, 1, 1, 0]
sentence_id = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

?

Thank you!


问:
How to iterate a big list to make it smaller for a REST call using Java streams?
I have logic something like this to process in chunks.

```<code>List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}
</code>```

Is there a better way of doing this iteration using java streams?

答:
You can batch your processing into chucks of a fixed size (or more advance dynamically computed batch size).

```<code> final List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,); // any range of items.
    final int batchSize = 3;
    final AtomicInteger counter = new AtomicInteger();

    final Collection<List<Integer>> result = numbers.stream()
        .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / batchSize))
        .values();
</code>```

You have now a collection of List of N element each (N=3)

Body:
I have logic something like this to process in chunks.

List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}

Is there a better way of doing this iteration using java streams?

Body:
You can batch your processing into chucks of a fixed size (or more advance dynamically computed batch size).

 final List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,); // any range of items.
    final int batchSize = 3;
    final AtomicInteger counter = new AtomicInteger();

    final Collection<List<Integer>> result = numbers.stream()
        .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / batchSize))
        .values();

You have now a collection of List of N element each (N=3)


答:
you have to use find_all

```<code>for link in link_list:
    response = requests.get(link, 'lxml')
    sp = BeautifulSoup(response.text, 'html.parser')
    table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
    for x in table:
        all_p = x.find_all('p')
        for para in all_p:
            if para:
                print(para.text)
</code>```

Title: Scraping job hunting website using BeautifulSoup

Body:
you have to use find_all

for link in link_list:
    response = requests.get(link, 'lxml')
    sp = BeautifulSoup(response.text, 'html.parser')
    table = sp.find_all('div',attrs={'data-automation': 'jobDescription'})
    for x in table:
        all_p = x.find_all('p')
        for para in all_p:
            if para:
                print(para.text)


问:
Bit shifting with enums
I have 4 properties and want to shift them in a byte called controlByte. The TypeEnum for example has 4 entries (0 = Unknown, 1 = Red, 2 = Blue, 3 = Green)

Bit 0-1: TypeEnum

Bit 2-3: SpeedEnum

Bit 4: IsActive

Bit 5: Optional

Code:

```<code> Byte controlByte = 0;
 controlByte  = (byte) (controlByte  | ((int)TypeEnum << 0));
 controlByte  = (byte) (controlByte  | ((int)SpeedEnum  << 2));
 controlByte  = (byte) (controlByte  | (IsActive ? 1 : 0 << 4));
</code>```

Expected Result:

```<code>     | Optional | IsActive | Speed | Type |
 Bit 7          5          4       2      0
</code>```

I'm not sure if the logic with the enums is correct. But the 3rd line with IsActive doesn't work. The Bit with index 0 is set instead of the Bit with index 4

答:
```<code>controlByte  = (byte) (controlByte  | ((IsActive ? 1 : 0) << 4));
</code>```

Your conditional reads like this: IsActive? then 1, not active then (0 with 4 left shift) a.k.a 0

Title: Bit shifting with enums

Body:
I have 4 properties and want to shift them in a byte called controlByte. The TypeEnum for example has 4 entries (0 = Unknown, 1 = Red, 2 = Blue, 3 = Green)

Bit 0-1: TypeEnum

Bit 2-3: SpeedEnum

Bit 4: IsActive

Bit 5: Optional

Code:

 Byte controlByte = 0;
 controlByte  = (byte) (controlByte  | ((int)TypeEnum << 0));
 controlByte  = (byte) (controlByte  | ((int)SpeedEnum  << 2));
 controlByte  = (byte) (controlByte  | (IsActive ? 1 : 0 << 4));

Expected Result:

     | Optional | IsActive | Speed | Type |
 Bit 7          5          4       2      0

I'm not sure if the logic with the enums is correct. But the 3rd line with IsActive doesn't work. The Bit with index 0 is set instead of the Bit with index 4

Body:
controlByte  = (byte) (controlByte  | ((IsActive ? 1 : 0) << 4));

Your conditional reads like this: IsActive? then 1, not active then (0 with 4 left shift) a.k.a 0


答:
In jQuery:</p>

```<code>$("<div />")
    .html('new link: <a href="http://test.com/" target="_blank"><b>Click Here</b></a>')
    .appendTo("body");
</code>```

Title: javascript variable value as a link

Body:
I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?

var link = 'new link: Clink Here'

Body:
In jQuery:

$("<div />")
    .html('new link: <a href="http://test.com/" target="_blank"><b>Click Here</b></a>')
    .appendTo("body");


问:
Gson to json coverting getting issue with class
{"f":"RECEIVED","g":"Siva Sankar","n":"342","o":"PREPAID"}

I am getting keys as f,g,n instead of my key set

My code is:GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            Gson gson = gsonBuilder.create();
            String gsonStr = gson.toJson(saveOrderDetails(),OrderDetails.class);

答: After making a lot of work on it.If found the issue in android that in build.gradle file in build release for debug we enabled it as minifyEnabled true. Make sure to change to minifyEnabled to false. Because of minifyEnabled true keys are converting into original keys to some random keys.</p>


问:
Merge Dyad_Year with Country_Year data
I have two data-frames, one dyad-year and the other country-year.

```<code>        Xccode1 ccode2 ccdistance            countryname_1       countryname_2 majorpower_1
        majorpower_2   milex_1 milper_1
        1   1      2     20          0 United States of America              Canada            1
         0 143981000     2050
        2   2      2     31        957 United States of America             Bahamas            1
        0 143981000     2050
        3   3      2     40       1129 United States of America                Cuba            1
        0 143981000     2050
        4   4      2     41       1437 United States of America               Haiti            1
</code>```

Country-Year:

```<code>   ccode1  year Fac1_A Fac2_A Fac3_A
   <int> <int>  <dbl>  <dbl>  <dbl>
    1      2  1980 -0.661   4.66   15.5
    2      2  1981 -0.661   4.66   15.5
    3      2  1982 -0.661   5.11   15.5
    4      2  1983 -0.661   5.21   15.5
    5      2  1984 -0.661   5.66   15.5
    6      2  1985 -0.661   5.21   15.5
    7      2  1986 -0.661   5.21   15.5
    8      2  1987 -0.661   5.21   15.5
    9      2  1988 -0.661   5.21   15.5
   10      2  1989 -0.661   5.00   15.5
</code>```

I'd like to merge this two data-frames so that each country in the dyad has a FacX value, however my attempts at doing this has either given me an error or lots of NA's. I first attempted to use a simple ifelse:

```<code>    Demo_Dyad$Fac1_A_NR <- ifelse(Demo_Dyad$ccode1 == Cntry_yr$ccode1 &
                            Demo_Dyad$year == Cntry_yr$year,
                          Cntry_yr$Fac1_A, NA)
</code>```

However, that results in each country in the Dyad_Year only having the value once. So e.g. USA <--> Haiti 1981 might have value X, but USA <--> Cuba 1981 will be NA.

I then attempted to do it by grouping in dplyr:

```<code>     Demo_Dyad %>%
     group_by(ccode1, year) %>%
     mutate(Fac1_A_NR <- ifelse(ccode1 == Cntry_yr$ccode1 &
                            year == Cntry_yr$year, Cntry_yr$Fac1_A, NA))
</code>```

But get the error: Error in `$<-.data.frame`(`*tmp*`, Fac1_A_NR, value = c(-0.660552389122193,  :
  replacement has 4942 rows, data has 217149

If anyone can see what is wrong with my code I would greatly appreciate it.

答:
If the whole task is to merge two dataframes based on a column or columns they have in common, then use merge. For example:

DATA:

```<code>set.seed(111)
df_a <- data.frame(
  Xccode = 1:10,
  v1a = rnorm(10),
  v2a = sample(LETTERS[1:5], 10, replace = T))

df_b <- data.frame(
  ccode = 1:10,
  v1b = rnorm(10, 5),
  v2b = sample(LETTERS[4:7], 10, replace = T))
</code>```

SOLUTION:

Assuming that the column the two dataframes have in common is Xccodeand, respectively, ccodeyou can use merge and specify the two columns as the ones to merge by:

```<code>df_ab <- merge(df_a, df_b, by.x =  "Xccode", by.y = "ccode")
df_ab
   Xccode        v1a v2a      v1b v2b
1       1  0.2352207   B 3.806391   E
2       2 -0.3307359   A 5.364187   E
3       3 -0.3116238   C 5.361662   E
4       4 -2.3023457   A 5.346964   G
5       5 -0.1708760   C 5.189737   D
6       6  0.1402782   E 4.840423   D
7       7 -1.4974267   A 5.326549   F
8       8 -1.0101884   A 5.598254   D
9       9 -0.9484756   A 3.158466   F
10     10 -0.4939622   C 7.718056   G
</code>```

Title: Merge Dyad_Year with Country_Year data

Body:
I have two data-frames, one dyad-year and the other country-year.

        Xccode1 ccode2 ccdistance            countryname_1       countryname_2 majorpower_1
        majorpower_2   milex_1 milper_1
        1   1      2     20          0 United States of America              Canada            1
         0 143981000     2050
        2   2      2     31        957 United States of America             Bahamas            1
        0 143981000     2050
        3   3      2     40       1129 United States of America                Cuba            1
        0 143981000     2050
        4   4      2     41       1437 United States of America               Haiti            1

Country-Year:

   ccode1  year Fac1_A Fac2_A Fac3_A
   <int> <int>  <dbl>  <dbl>  <dbl>
    1      2  1980 -0.661   4.66   15.5
    2      2  1981 -0.661   4.66   15.5
    3      2  1982 -0.661   5.11   15.5
    4      2  1983 -0.661   5.21   15.5
    5      2  1984 -0.661   5.66   15.5
    6      2  1985 -0.661   5.21   15.5
    7      2  1986 -0.661   5.21   15.5
    8      2  1987 -0.661   5.21   15.5
    9      2  1988 -0.661   5.21   15.5
   10      2  1989 -0.661   5.00   15.5

I'd like to merge this two data-frames so that each country in the dyad has a FacX value, however my attempts at doing this has either given me an error or lots of NA's. I first attempted to use a simple ifelse:

    Demo_Dyad$Fac1_A_NR <- ifelse(Demo_Dyad$ccode1 == Cntry_yr$ccode1 &
                            Demo_Dyad$year == Cntry_yr$year,
                          Cntry_yr$Fac1_A, NA)

However, that results in each country in the Dyad_Year only having the value once. So e.g. USA <--> Haiti 1981 might have value X, but USA <--> Cuba 1981 will be NA.

I then attempted to do it by grouping in dplyr:

     Demo_Dyad %>%
     group_by(ccode1, year) %>%
     mutate(Fac1_A_NR <- ifelse(ccode1 == Cntry_yr$ccode1 &
                            year == Cntry_yr$year, Cntry_yr$Fac1_A, NA))

But get the error: Error in `$<-.data.frame`(`*tmp*`, Fac1_A_NR, value = c(-0.660552389122193,  :
  replacement has 4942 rows, data has 217149

If anyone can see what is wrong with my code I would greatly appreciate it.

Body:
If the whole task is to merge two dataframes based on a column or columns they have in common, then use merge. For example:

DATA:

set.seed(111)
df_a <- data.frame(
  Xccode = 1:10,
  v1a = rnorm(10),
  v2a = sample(LETTERS[1:5], 10, replace = T))

df_b <- data.frame(
  ccode = 1:10,
  v1b = rnorm(10, 5),
  v2b = sample(LETTERS[4:7], 10, replace = T))

SOLUTION:

Assuming that the column the two dataframes have in common is Xccodeand, respectively, ccodeyou can use merge and specify the two columns as the ones to merge by:

df_ab <- merge(df_a, df_b, by.x =  "Xccode", by.y = "ccode")
df_ab
   Xccode        v1a v2a      v1b v2b
1       1  0.2352207   B 3.806391   E
2       2 -0.3307359   A 5.364187   E
3       3 -0.3116238   C 5.361662   E
4       4 -2.3023457   A 5.346964   G
5       5 -0.1708760   C 5.189737   D
6       6  0.1402782   E 4.840423   D
7       7 -1.4974267   A 5.326549   F
8       8 -1.0101884   A 5.598254   D
9       9 -0.9484756   A 3.158466   F
10     10 -0.4939622   C 7.718056   G


问:
SQLite CASE query with multiple conditions
I am trying to execute a query to find the minimum price of various products in the same store in the same week

When I only have two products, the query is working perfectly fine.

When I have 3 or more products I am doing something wrong, but do not know what.

This is what I use for two products (works fine) :

```<code> select a.* , b.*,

 case when a.preis_pro_unze < b.preis_pro_unze then a.preis_pro_unze
    when b.preis_pro_unze < a.preis_pro_unze then b.preis_pro_unze

end as minpreis

 FROM Heinz32_36 as a, Heinz32_36 as b
WHERE
a.IRI_KEY = b.IRI_KEY
AND a.week = b.week
AND a.UPC_DESC != b.UPC_DESC
</code>```

This is what I tried for three products (does not work):

```<code>Select a.UPC_DESC, a.IRI_KEY , a.WEEK , a.Price_per_unit, a.Preis_pro_unze,
b.UPC_DESC, b.IRI_KEY , b.WEEK , b.Price_per_unit, b.Preis_pro_unze,
c.UPC_DESC, c.IRI_KEY , c.WEEK , c.Price_per_unit, c.Preis_pro_unze,
case
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze

end as minpreis

FROM "prv24" as a , "prv24" as b, "prv24" as c

WHERE

a.IRI_KEY = b.IRI_KEY = c.IRI_KEY AND
a.week = b.week = c.week AND

a.UPC_DESC  != b.UPC_DESC or a.UPC_DESC  != c.UPC_DESC
OR
b.UPC_DESC != c.UPC_DESC
</code>```

LIMIT 10

It Could be something with the "!=" conditions at the very end. I already tried to rewrite it with some bracket-statements but that didn´t do the job either.

I am working with SQLite. I do not get any error-messages, but the query is processing endlessly.

答:
Without sample data and a schema, it's hard to be certain, but I think you're missing some brackets. The OR condition means that your query is evaluating all your AND conditions, and then adding the OR condition in addition; that probably leads to a huge data set, which would explain the endless processing.

```<code>Select a.UPC_DESC,
       a.IRI_KEY ,
       a.WEEK ,
       a.Price_per_unit,
       a.Preis_pro_unze,
       b.UPC_DESC,
       b.IRI_KEY ,
       b.WEEK ,
       b.Price_per_unit,
       b.Preis_pro_unze,
       c.UPC_DESC,
       c.IRI_KEY ,
       c.WEEK ,
       c.Price_per_unit,
       c.Preis_pro_unze,
       case
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
         when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
         when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze

end as minpreis

FROM "prv24" as a ,
     "prv24" as b,
     "prv24" as c

WHERE

a.IRI_KEY = b.IRI_KEY = c.IRI_KEY AND
 a.week = b.week = c.week AND

(a.UPC_DESC  != b.UPC_DESC or
a.UPC_DESC  != c.UPC_DES  OR
b.UPC_DESC != c.UPC_DESC)
</code>```

However, you may find it makes much more sense if you use explicit join syntax and use meaningful aliases. Explicit joins avoid the problems you've just encountered (an OR condition messing up your joins), and make your code easier to read.

Here's a much neater version:

```<code>Select a.UPC_DESC,
       a.IRI_KEY,
       a.WEEK,
       a.Price_per_unit,
       a.Preis_pro_unze,
       b.UPC_DESC,
       b.IRI_KEY,
       b.WEEK,
       b.Price_per_unit,
       b.Preis_pro_unze,
       c.UPC_DESC,
       c.IRI_KEY ,
       c.WEEK ,
       c.Price_per_unit,
       c.Preis_pro_unze,
       case
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze
        end as minpreis
FROM "prv24" as a
      inner join  "prv24" as b
          on a.IRI_KEY = b.IRI_KEY
          and a.week = b.week
      inner join "prv24" as c
          on a.IRI_KEY = c.IRI_KEY
          and a.week = c.week
WHERE
(a.UPC_DESC  != b.UPC_DESC or
a.UPC_DESC  != c.UPC_DES  or
b.UPC_DESC != c.UPC_DESC)
</code>```

Body:
I am trying to execute a query to find the minimum price of various products in the same store in the same week

When I only have two products, the query is working perfectly fine.

When I have 3 or more products I am doing something wrong, but do not know what.

This is what I use for two products (works fine) :

 select a.* , b.*,

 case when a.preis_pro_unze < b.preis_pro_unze then a.preis_pro_unze
    when b.preis_pro_unze < a.preis_pro_unze then b.preis_pro_unze

end as minpreis

 FROM Heinz32_36 as a, Heinz32_36 as b
WHERE
a.IRI_KEY = b.IRI_KEY
AND a.week = b.week
AND a.UPC_DESC != b.UPC_DESC

This is what I tried for three products (does not work):

Select a.UPC_DESC, a.IRI_KEY , a.WEEK , a.Price_per_unit, a.Preis_pro_unze,
b.UPC_DESC, b.IRI_KEY , b.WEEK , b.Price_per_unit, b.Preis_pro_unze,
c.UPC_DESC, c.IRI_KEY , c.WEEK , c.Price_per_unit, c.Preis_pro_unze,
case
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze

end as minpreis

FROM "prv24" as a , "prv24" as b, "prv24" as c

WHERE

a.IRI_KEY = b.IRI_KEY = c.IRI_KEY AND
a.week = b.week = c.week AND

a.UPC_DESC  != b.UPC_DESC or a.UPC_DESC  != c.UPC_DESC
OR
b.UPC_DESC != c.UPC_DESC

LIMIT 10

It Could be something with the "!=" conditions at the very end. I already tried to rewrite it with some bracket-statements but that didn´t do the job either.

I am working with SQLite. I do not get any error-messages, but the query is processing endlessly.

Body:
Without sample data and a schema, it's hard to be certain, but I think you're missing some brackets. The OR condition means that your query is evaluating all your AND conditions, and then adding the OR condition in addition; that probably leads to a huge data set, which would explain the endless processing.

Select a.UPC_DESC,
       a.IRI_KEY ,
       a.WEEK ,
       a.Price_per_unit,
       a.Preis_pro_unze,
       b.UPC_DESC,
       b.IRI_KEY ,
       b.WEEK ,
       b.Price_per_unit,
       b.Preis_pro_unze,
       c.UPC_DESC,
       c.IRI_KEY ,
       c.WEEK ,
       c.Price_per_unit,
       c.Preis_pro_unze,
       case
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
         when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
         when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze

end as minpreis

FROM "prv24" as a ,
     "prv24" as b,
     "prv24" as c

WHERE

a.IRI_KEY = b.IRI_KEY = c.IRI_KEY AND
 a.week = b.week = c.week AND

(a.UPC_DESC  != b.UPC_DESC or
a.UPC_DESC  != c.UPC_DES  OR
b.UPC_DESC != c.UPC_DESC)

However, you may find it makes much more sense if you use explicit join syntax and use meaningful aliases. Explicit joins avoid the problems you've just encountered (an OR condition messing up your joins), and make your code easier to read.

Here's a much neater version:

Select a.UPC_DESC,
       a.IRI_KEY,
       a.WEEK,
       a.Price_per_unit,
       a.Preis_pro_unze,
       b.UPC_DESC,
       b.IRI_KEY,
       b.WEEK,
       b.Price_per_unit,
       b.Preis_pro_unze,
       c.UPC_DESC,
       c.IRI_KEY ,
       c.WEEK ,
       c.Price_per_unit,
       c.Preis_pro_unze,
       case
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = a.preis_pro_unze then a.preis_pro_unze
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = b.preis_pro_unze then b.preis_pro_unze
          when min(min(a.preis_pro_unze , b.preis_pro_unze , c.preis_pro_unze )) = c.preis_pro_unze then c.preis_pro_unze
        end as minpreis
FROM "prv24" as a
      inner join  "prv24" as b
          on a.IRI_KEY = b.IRI_KEY
          and a.week = b.week
      inner join "prv24" as c
          on a.IRI_KEY = c.IRI_KEY
          and a.week = c.week
WHERE
(a.UPC_DESC  != b.UPC_DESC or
a.UPC_DESC  != c.UPC_DES  or
b.UPC_DESC != c.UPC_DESC)


问:
LinQ Remove products based on Status
So I have a issue with a API showing drafted products.

So my solution is to iterate over the list before my view is set and remove any drafted products.

However i'm not familiar with LinQ so im not exactly sure how to go about this, Or what to Phrase id use to look into this more

Here are my attempts

Attempt 1: only removes 1 Product(If I say Any|All its just says cannot convert bool to product)

```<code>
  var listitem = (from itm in products where itm.status == "draft" select itm).FirstOrDefault();
                products.Remove(listitem);
  //Also tried something like

.Where(a => a.status == "draft")
</code>```

Attempt 2: Finds the item, But then removes everything

```<code>       foreach (var item in products)
                {
                    if (item.status == "draft")
                    {
                        products.Remove(item);
                    }
                }
</code>```

```<code>      productsListView.FlowItemsSource = products;
</code>```

Whats the correct way of doing this?

答:
How about

productsListView.FlowItemsSource = products.Where(p => p.status != "draft");

Does this work?

Title: LinQ Remove products based on Status

Body:
So I have a issue with a API showing drafted products.

So my solution is to iterate over the list before my view is set and remove any drafted products.

However i'm not familiar with LinQ so im not exactly sure how to go about this, Or what to Phrase id use to look into this more

Here are my attempts

Attempt 1: only removes 1 Product(If I say Any|All its just says cannot convert bool to product)

  var listitem = (from itm in products where itm.status == "draft" select itm).FirstOrDefault();
                products.Remove(listitem);
  //Also tried something like

.Where(a => a.status == "draft")

Attempt 2: Finds the item, But then removes everything

       foreach (var item in products)
                {
                    if (item.status == "draft")
                    {
                        products.Remove(item);
                    }
                }

      productsListView.FlowItemsSource = products;

Whats the correct way of doing this?


问:
Is there an agnostic cli for quickly generating new features and projects?
I'm in the process of building some tools but find myself thinking I'm reinventing the wheel. I'm looking for a cli, preferably written in javascript, that has a config file and template engine. The config file would let you specify projects and features and have a path option that would point to the template(s) and create the files/folders at the path specified by the config, or current working directory. Ideally it would not overwrite folders or files that were pre-existing and would handle such cases gracefully.

I started building something like this using oclif for the cli framework. So the responses I get here will determine if I continue that work or save some time by using something that may be more polished. The example below is react, but I would want to use such a tool for Laravel, Vue, Vulcan, etc...

In the end it doesn't matter how it works but here is an example of a possible solution.

config.js

```<code>const commands = {
  react: {
    functionalComponent: {
      argName: 'fc',
      template: '/templates/react/fc.hbs'
    }
  }
}
</code>```

```<code>// console
$ cd ./my-project/src/components
$ gen react -fc
</code>```

答:
You could try the CLI version (https://www.telosys.org/cli.html) of Telosys (https://www.telosys.org/ ) an Open Source code generator.

This code generator is language agnostic, you can generate any kind of text files.

It uses a template engine (https://www.telosys.org/templates.html ) based on Velocity (http://velocity.apache.org/engine/1.7/ ) and each template file can be fed with variables defined for each project and/or entities defined in text files.

This tool is written in Java (not in JS) but it only requires a Java Runtime on your machine (Java 7 or +), that's it.

I use it very often for project bootstrapping and to generate all the boilerplate (and boring) code.

See also :

Telosys CLI Installation : https://www.youtube.com/watch?v=_aYnDPvdPvg

Telosys CLI tutorial (with Python example but it’s the same principle for all languages) : https://www.slideshare.net/lguerin/telosys-tutorial-code-generation-for-a-python-web-application-based-on-bottle-and-sqlalchemy

General presentation : https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/

Body:
I'm in the process of building some tools but find myself thinking I'm reinventing the wheel. I'm looking for a cli, preferably written in javascript, that has a config file and template engine. The config file would let you specify projects and features and have a path option that would point to the template(s) and create the files/folders at the path specified by the config, or current working directory. Ideally it would not overwrite folders or files that were pre-existing and would handle such cases gracefully.

I started building something like this using oclif for the cli framework. So the responses I get here will determine if I continue that work or save some time by using something that may be more polished. The example below is react, but I would want to use such a tool for Laravel, Vue, Vulcan, etc...

In the end it doesn't matter how it works but here is an example of a possible solution.

config.js

const commands = {
  react: {
    functionalComponent: {
      argName: 'fc',
      template: '/templates/react/fc.hbs'
    }
  }
}

// console
$ cd ./my-project/src/components
$ gen react -fc


问:
Acquisition attempt failed during the initializing c3p0 pool
I am new to J2EE technologies and trying to create a basic web application with JSF, Spring and Hibernate. I also use PostgreSQL. During the server startup, I encounter this exception:

```<code>WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@173b4cf -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Dec 09, 2015 11:13:21 AM com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask run
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@173b4cf -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Dec 09, 2015 11:13:21 AM com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask run
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@5e53d -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
</code>```

I gave my configuration files and related class below:

application-context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/SomeDB" />
    <property name="username" value="postgres" />
    <property name="password" value="1234" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="tr.mypackage" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
            <prop key="hibernate.c3p0.acquire_increment">1</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config />
<context:component-scan base-package="tr.mypackage" />

</beans>
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Some Display Name</display-name>

<!-- JSF -->
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

<!-- SPRING -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/application-context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<!-- OTHER -->
<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
</code>```

Person.java

```<code>package tr.mypackage;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.sun.istack.internal.NotNull;

@Entity
@Table(name="person_t")
public class Person {
    @Id
    @NotNull
    @GeneratedValue
    private int id;

    @Column
    private String firstName;

    public Person(){

    }

    public Person(int id, String firstName) {
        super();
        this.id = id;
        this.firstName = firstName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}
</code>```

So, is there any idea about where my error is?

答:
If you are using eclipse and you are facing this error, then you just need to change your mysql connector (which worked totally fine in my case).

The newer versions are using caching_sha2_password.

Body:
I am new to J2EE technologies and trying to create a basic web application with JSF, Spring and Hibernate. I also use PostgreSQL. During the server startup, I encounter this exception:

WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@173b4cf -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Dec 09, 2015 11:13:21 AM com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask run
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@173b4cf -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Dec 09, 2015 11:13:21 AM com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask run
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@5e53d -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

I gave my configuration files and related class below:

application-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/SomeDB" />
    <property name="username" value="postgres" />
    <property name="password" value="1234" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="tr.mypackage" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
            <prop key="hibernate.c3p0.acquire_increment">1</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config />
<context:component-scan base-package="tr.mypackage" />

</beans>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Some Display Name</display-name>

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/application-context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Person.java

package tr.mypackage;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.sun.istack.internal.NotNull;

@Entity
@Table(name="person_t")
public class Person {
    @Id
    @NotNull
    @GeneratedValue
    private int id;

    @Column
    private String firstName;

    public Person(){

    }

    public Person(int id, String firstName) {
        super();
        this.id = id;
        this.firstName = firstName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

So, is there any idea about where my error is?