问:
Spring Security: JWT token for API and session for web
I aim to use both security in my Spring Boot app. I already done the API side with JWT, but I don't know how to implement the session for the WEB side. I have already done that in another project but I don't know how to make them work together.

Here is my SecurityConfig:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/api/**")
         .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
         .and()
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated()
         .and()
            .apply(new JWTConfigurer(this.tokenProvider));
}
</code>```

I would like to have something like this :

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
         // For API side something like : .match("/api/**")
         // No CSRF
         .csrf().ignoringAntMatchers("/api/**")
         // STATELESS session
         // Use token filter
         .apply(new JWTConfigurer(this.tokenProvider));

         // For WEB side something like : .match "others"
         // Use CSRF
         .csrf()
         // Use session

         // And the other permit :
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated();
}
</code>```

Can anyone tell me how to do that? (and explain me how it works).
I have not found any good solution on what I am asking.

答:
After 6 hours of searching, here is the solution :
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

EDIT :
Here is how i did that :

```<code>@EnableWebSecurity
public class MultiHttpSecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Configuration
    @Order(1)
    public class ApiSecurityAdapter extends WebSecurityConfigurerAdapter {

        private TokenProvider tokenProvider;

        public ApiSecurityAdapter(TokenProvider tokenProvider) {
            this.tokenProvider = tokenProvider;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**") //<= Security only available for /api/**
                .authorizeRequests()
                    .antMatchers("/api/register").permitAll()
                    .antMatchers("/api/login").permitAll()
                    .antMatchers("/api/public").permitAll()
                    .antMatchers("/api/lost").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .apply(new JWTConfigurer(this.tokenProvider))
                .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    @Configuration
    public class WebSecurityAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http // <= Security available for others (not /api/)
                .authorizeRequests()
                    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                    .antMatchers("/").permitAll()
                    .antMatchers("/login").permitAll()
                    .antMatchers("/resources/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                        .loginPage("/login")
                            .usernameParameter("email")
                            .passwordParameter("password")
                            .defaultSuccessUrl("/central", false)
                            .failureForwardUrl("/login/fail")
                .and()
                    .logout()
                        .invalidateHttpSession(true)
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/")
                .and()
                    .csrf();
        }
    }
}
</code>```

Hope this can help !

Body:
I aim to use both security in my Spring Boot app. I already done the API side with JWT, but I don't know how to implement the session for the WEB side. I have already done that in another project but I don't know how to make them work together.

Here is my SecurityConfig:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/api/**")
         .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
         .and()
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated()
         .and()
            .apply(new JWTConfigurer(this.tokenProvider));
}

I would like to have something like this :

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
         // For API side something like : .match("/api/**")
         // No CSRF
         .csrf().ignoringAntMatchers("/api/**")
         // STATELESS session
         // Use token filter
         .apply(new JWTConfigurer(this.tokenProvider));

         // For WEB side something like : .match "others"
         // Use CSRF
         .csrf()
         // Use session

         // And the other permit :
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated();
}

Can anyone tell me how to do that? (and explain me how it works).
I have not found any good solution on what I am asking.

Body:
After 6 hours of searching, here is the solution :
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

EDIT :
Here is how i did that :

@EnableWebSecurity
public class MultiHttpSecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Configuration
    @Order(1)
    public class ApiSecurityAdapter extends WebSecurityConfigurerAdapter {

        private TokenProvider tokenProvider;

        public ApiSecurityAdapter(TokenProvider tokenProvider) {
            this.tokenProvider = tokenProvider;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**") //<= Security only available for /api/**
                .authorizeRequests()
                    .antMatchers("/api/register").permitAll()
                    .antMatchers("/api/login").permitAll()
                    .antMatchers("/api/public").permitAll()
                    .antMatchers("/api/lost").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .apply(new JWTConfigurer(this.tokenProvider))
                .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    @Configuration
    public class WebSecurityAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http // <= Security available for others (not /api/)
                .authorizeRequests()
                    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                    .antMatchers("/").permitAll()
                    .antMatchers("/login").permitAll()
                    .antMatchers("/resources/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                        .loginPage("/login")
                            .usernameParameter("email")
                            .passwordParameter("password")
                            .defaultSuccessUrl("/central", false)
                            .failureForwardUrl("/login/fail")
                .and()
                    .logout()
                        .invalidateHttpSession(true)
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/")
                .and()
                    .csrf();
        }
    }
}

Hope this can help !


来源: stackexchange

问:
Reading binary file without knowing file format
I'm working on a java project and i have to read some files like these:
- EntryID.data
- EntryID.index
- KeyText.data
- KeyText.index
...

I think these files are used in a dictionary project but i can't find a any document about this. How can i read them or know the format of them ? Sorry for my english =.=

Thanks alot!

答:
This looks like files from a database management system. One file to store the data, another one to store at least one index to speed up queries.

I'd start with a hex editor and look at the file. Sometimes, the content binaries gives a hint.

Another idea: look at the classpath and inspect property and resource files. Maybe you'll find a database driver or some config files with jdbc connect strings.

Google told me, that all four files are used by Apple's Dictionary.app. Have a look at this blog, this can point you in the correct direction.

Last note - reading undocumented binaries is a challenge. I usually start with 010 Editor to analyse the datastructure and develop a java based test tool to read the data. It's some sort of try and error evolutionary process.

ContentLicense: CC BY-SA 2.5


问:
How do I consume a WCF Soap 1.2 Web Service using a CXF Web Service Client?
Does anyone know the trick to calling a WCF (Soap 1.2) web service from CXF?

I've been trying to get a basic hello world client working for a while now and I've had no luck.

It works fine with Soap 1.1.

When I print out the SoapBinding the client is using it's using soap 1.1 even though it's a soap 1.2 service
when I set the soap binding manually to 1.2 it freezes up when you make the web service call and eventually dies with a socket timeout exception (Read timed out).

```<code>public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(ITest.class);
        factory.setAddress("http://localhost/Test/test.svc");
        final Soap12 soap12 = Soap12.getInstance();

        BindingConfiguration config = new BindingConfiguration() {

            @Override
            public String getBindingId() {
                return soap12.getBindingId();
            }
        };
        factory.setBindingConfig(config);
        factory.setBindingId(soap12.getBindingId());
        ITest service = (ITest) factory.create();

        org.apache.cxf.endpoint.Client client = ClientProxy.getClient(service);
        client.getRequestContext().put("ContentType", "text/xml; charset=utf-8");
        SoapBinding binding = (SoapBinding) client.getEndpoint().getBinding();
        System.out.println("[" + binding.getSoapVersion() + "]");
        System.out.println(service.test("World"));
    }
</code>```

This is the soap request that gets sent to the WCF Service.

```<code><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<Test xmlns="http://tempuri.org/" xmlns:ns2="http://schemas.microsoft.com/2003/10/Serialization/">
<s>World</s>
</Test>
</soap:Body>
</soap:Envelope>
</code>```

答:
I think your major issue with the communication between the WCF and CXF is the lack of ws-addressing headers present on the request.  When you enable wsHttpBinding, WCF expects a client that understands ws-addressing.   This is a feature of CXF, but needs to be enabled.  The following code should resolve your issues:

```<code>// add the ws-addressing feature on the proxy factory.
factory.getFeatures().add(new org.apache.cxf.ws.addressing.WSAddressingFeature());
</code>```

This solution works with CXF 3.x.

Body:
Does anyone know the trick to calling a WCF (Soap 1.2) web service from CXF?

I've been trying to get a basic hello world client working for a while now and I've had no luck.

It works fine with Soap 1.1.

When I print out the SoapBinding the client is using it's using soap 1.1 even though it's a soap 1.2 service
when I set the soap binding manually to 1.2 it freezes up when you make the web service call and eventually dies with a socket timeout exception (Read timed out).

public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(ITest.class);
        factory.setAddress("http://localhost/Test/test.svc");
        final Soap12 soap12 = Soap12.getInstance();

        BindingConfiguration config = new BindingConfiguration() {

            @Override
            public String getBindingId() {
                return soap12.getBindingId();
            }
        };
        factory.setBindingConfig(config);
        factory.setBindingId(soap12.getBindingId());
        ITest service = (ITest) factory.create();

        org.apache.cxf.endpoint.Client client = ClientProxy.getClient(service);
        client.getRequestContext().put("ContentType", "text/xml; charset=utf-8");
        SoapBinding binding = (SoapBinding) client.getEndpoint().getBinding();
        System.out.println("[" + binding.getSoapVersion() + "]");
        System.out.println(service.test("World"));
    }

This is the soap request that gets sent to the WCF Service.

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<Test xmlns="http://tempuri.org/" xmlns:ns2="http://schemas.microsoft.com/2003/10/Serialization/">
<s>World</s>
</Test>
</soap:Body>
</soap:Envelope>

Body:
I think your major issue with the communication between the WCF and CXF is the lack of ws-addressing headers present on the request.  When you enable wsHttpBinding, WCF expects a client that understands ws-addressing.   This is a feature of CXF, but needs to be enabled.  The following code should resolve your issues:

// add the ws-addressing feature on the proxy factory.
factory.getFeatures().add(new org.apache.cxf.ws.addressing.WSAddressingFeature());

This solution works with CXF 3.x.

ContentLicense: CC BY-SA 3.0


问:
std::ptr_fun replacement for c++17
I am using std::ptr_fun as follows:

```<code>static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}
</code>```

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

```<code>error C2039: 'ptr_fun': is not a member of 'std'
</code>```

How can this be fixed?

答:
Alternatively, you might use std::not_fn:</p>

```<code>static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
        std::not_fn(static_cast<int(*)(int)>(std::isspace))));
    return s;
}
</code>```

Title: std::ptr_fun replacement for c++17

Body:
I am using std::ptr_fun as follows:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

error C2039: 'ptr_fun': is not a member of 'std'

How can this be fixed?

Body:
Alternatively, you might use std::not_fn:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
        std::not_fn(static_cast<int(*)(int)>(std::isspace))));
    return s;
}


问:
Laravel 5.5 install
When I try to install Laravel 5.5 with laravel new project --dev

```<code>[Symfony\Component\Debug\Exception\FatalThrowableError]
  Parse error: syntax error, unexpected '<<' (T_SL), expecting ']'
</code>```

It is just me or because it is not release yet?

EDIT:
Btw, it is when I try to make php artisan key:generate... If I put any key in .env it works...

Thanks

答:
I had the same problem.
For me even

```<code>php artisan
</code>```

did not work.

I fixed it with a simple

```<code>cd /my/project/folder
composer update
php artisan key:generate
</code>```

in the console.

Hope this helps.

Title: Laravel 5.5 install

Body:
When I try to install Laravel 5.5 with laravel new project --dev

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Parse error: syntax error, unexpected '<<' (T_SL), expecting ']'

It is just me or because it is not release yet?

EDIT:
Btw, it is when I try to make php artisan key:generate... If I put any key in .env it works...

Thanks

Body:
I had the same problem.
For me even

php artisan

did not work.

I fixed it with a simple

cd /my/project/folder
composer update
php artisan key:generate

in the console.

Hope this helps.


问:
Toggle between hiding and showing RowDetails when DataGridRow is clicked
I have a DataGrid that has RowDetailsVisibilityMode set to "VisibleWhenSelected" so that the RowDetailsTemplate displays when I select a particular row. What I want is to be able to toggle the RowDetails visibility when I click the row again. By default, the RowDetails will be visible so long as its selected, but I want to essentially "unselect" the selected row if I click it again.

After trying a lot of things, I've found a sort of wacky solution that at least makes it so that I can toggle the visibility when I click the row:

```<code>private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
    if (DataGrid.SelectedIndex == prevSelectedIndex) { //check if I'm clicking on what's already selected
          DataGrid.SelectedIndex = -1; //collapses everything
    }
    prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
}
</code>```

The delay makes sure that the SelectedIndex property is already updated when I check for the selected index. I wish I didn't have to use it - I would be happy to find a better solution.

The problem now, however, is that whenever I click anything in the RowDetails of the selected row, this event fires and the row details disappear again. I want to be able to somehow check that I only expand/collapse the row when I click the row itself, not when I click whatever's in the RowDetailsTemplate. Is that possible? I don't want to use an extra Expander button for each row.

答:
I think a global boolean variable can do the toggle for you.</p>

```<code>        public bool Visible = false;
        private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (Visible == false)
            {
                await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
                if (DataGrid.SelectedIndex == prevSelectedIndex)
                { //check if I'm clicking on what's already selected
                    DataGrid.SelectedIndex = 1; //collapses everything
                }
                prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
                Visible = true;
            }
            else
            {
                await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
                if (DataGrid.SelectedIndex == prevSelectedIndex)
                { //check if I'm clicking on what's already selected
                    DataGrid.SelectedIndex = -1; //collapses everything
                }
                prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
                Visible = false;
            }
        }
</code>```

Body:
I have a DataGrid that has RowDetailsVisibilityMode set to "VisibleWhenSelected" so that the RowDetailsTemplate displays when I select a particular row. What I want is to be able to toggle the RowDetails visibility when I click the row again. By default, the RowDetails will be visible so long as its selected, but I want to essentially "unselect" the selected row if I click it again.

After trying a lot of things, I've found a sort of wacky solution that at least makes it so that I can toggle the visibility when I click the row:

private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
    if (DataGrid.SelectedIndex == prevSelectedIndex) { //check if I'm clicking on what's already selected
          DataGrid.SelectedIndex = -1; //collapses everything
    }
    prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
}

The delay makes sure that the SelectedIndex property is already updated when I check for the selected index. I wish I didn't have to use it - I would be happy to find a better solution.

The problem now, however, is that whenever I click anything in the RowDetails of the selected row, this event fires and the row details disappear again. I want to be able to somehow check that I only expand/collapse the row when I click the row itself, not when I click whatever's in the RowDetailsTemplate. Is that possible? I don't want to use an extra Expander button for each row.

Body:
I think a global boolean variable can do the toggle for you.

        public bool Visible = false;
        private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (Visible == false)
            {
                await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
                if (DataGrid.SelectedIndex == prevSelectedIndex)
                { //check if I'm clicking on what's already selected
                    DataGrid.SelectedIndex = 1; //collapses everything
                }
                prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
                Visible = true;
            }
            else
            {
                await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
                if (DataGrid.SelectedIndex == prevSelectedIndex)
                { //check if I'm clicking on what's already selected
                    DataGrid.SelectedIndex = -1; //collapses everything
                }
                prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
                Visible = false;
            }
        }


问:
Organising T4 Templates
I have begun using T4 Templates for a few DAL enhancements.

However, I find they quickly get unwieldy and often produce poorly formatted code.

I am wondering if anyone has any good tips on organising these templates, and on getting great formatted code at the end.

So far my experience is:

Stick to what existing published templates do (e.g. SubSonic)

If indentation is playing up attempt a blank line after the closest #>

Lots of comments.

答:
T4 end result indentation

T4 templates will format code as defined in the template. Indents are as defined in the file itself. To have great indented end result, T4 templates will often look strange and odd indented. But code is coloured so template's code is usually just fine.

T4 organization

I usually have a solution folder with all reusable T4 templates (if lots of them they can be put in subfolders as well). I give them the ttinclude file extension. Others just include these and are put in place where needed.

Title: Organising T4 Templates


问:
How to outline the div tag?
I try to outline the div tag. I used border:0.01em solid black but it is not correctly fit.
My script below

```<code><html>
<body>
<div id="color" style="width:100%; height:500px; background:gray;">
<div style="width:50%; height:500px; background:yellow;  float:left;"></div>
<div style="width:50%; height:500px; background:blue; float:left;">    </div>
</div>
<div id="border" style="width:100%; height:500px; background:gray;">
<div style="width:50%; height:500px; border:0.01em solid black;  float:left;"></div>
<div style="width:50%; height:500px; border:0.01em solid black; float:left;"></div>
</div>
</body>
</html>
</code>```

That equal sepration of the div id = color tag is fit into the 100% width.

But equal sepration of the div id = border tag is not fit into the 100%
because i added the border to seprate div tags, so size is increase like 50% + 0.01em.

That the reason div id = border tag's sub div tag is not fit into the 100%, so the second sub div tag is fall in down from 100%.

So i want to outline
the div tag not to border it? How can i do it? But i want to seprate by the 50% i not decrese it.

答:
This is actually the purpose of the outline property:

```<code><div id="border" style="width:100%; height:500px; background:gray;">
    <div style="width:50%; height:500px; outline:0.01em solid black; float:left;"></div>
    <div style="width:50%; height:500px; outline:0.01em solid black; float:left;"></div>
</div>
</code>```

Title: How to outline the div tag?

Body:
I try to outline the div tag. I used border:0.01em solid black but it is not correctly fit.
My script below

That equal sepration of the div id = color tag is fit into the 100% width.

But equal sepration of the div id = border tag is not fit into the 100%
because i added the border to seprate div tags, so size is increase like 50% + 0.01em.

That the reason div id = border tag's sub div tag is not fit into the 100%, so the second sub div tag is fall in down from 100%.

So i want to outline
the div tag not to border it? How can i do it? But i want to seprate by the 50% i not decrese it.

Body:
This is actually the purpose of the outline property:

<div id="border" style="width:100%; height:500px; background:gray;">
    <div style="width:50%; height:500px; outline:0.01em solid black; float:left;"></div>
    <div style="width:50%; height:500px; outline:0.01em solid black; float:left;"></div>
</div>


问:
Scraping multiple web pages with BeautifulSoup when the first page link is different from others
I'm trying to scrape this page! for a project i'm working on. I want to get the details (Price, Mileage, Transmission, and Age) of each car for all the pages. The issues I'm having with my code below are:

The first page link is different from others (No page number 1 <&page=1>)

The price of the car is not inside the table after clicking on each ad to get the details.

I'm wondering if anyone would be kind enough to help me look into this and advise. Thanks

```<code>    from bs4 import BeautifulSoup
    import requests
    import urllib.parse
    import csv

    # the Toyota Camry model page is used
    url = "https://www.olx.com.ng/vehicles/cars/toyota/?search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry"
    r = requests.get(url)
    data = r.text

    soup = BeautifulSoup(data, "html.parser")
    carLinks = set()
    pageLinks = set()
    data_set = []

    parsed = urllib.parse.urlparse(soup.select('a')[0].get('href'))
    nbPage = urllib.parse.parse_qs(parsed.query)['page'][1]
    print("There are " + str(nbPage) + " web pages to process")

    # for each web page that contains a grid of car offers
    for i in range(1, int(nbPage), 1):

    print("Processing web page: " + str(i))

    # each car offer link is saved into the carLinks
    for link in soup.select('#listContainer > div > section > div > tr > a'):
    carLinks.add(link.get('href').replace("//", "http://"))

    # the next url page is set
    url = "https://www.olx.com.ng/vehicles/cars/toyota/?
    search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry&page= + str(i) + "
    r = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data, "html.parser")

    #for each car link
    for carLink in carLinks:

    print("Processing car page: " + carLink)

    # we load the car page
    r = requests.get(carLink)
    data = r.text
    soup = BeautifulSoup(data, "html.parser")
    km = 0
    transmission = ""
    age = 0
    price = 0

    # for each attribute of the car
    for info in soup.select("table.item tr div.pricelabel"):

    # we keep the ones that we need
    if info.select('.item')[0].text == u'Mileage':
        km = int(info.select('.value')[0].text.replace(" ", "").replace("KM", ""))
    if info.select('.item')[0].text == u'Transmission':
        transmission = info.select('.value')[0].text
    if info.select('.item')[0].text == u'Year':
        age = 2017 - int(info.select('.value')[0].text)
    if info.select('.pricelabel')[0].text == u'Price':
        price = int(info.select('.pricelabel')[0].text.replace(" ", "").replace(u"₦", ""))

    # each car is an array of four features added to the data_set
    data_set.append([km, transmission, age, price])

    # the data_set is save into the CSV file
    fl = open('car_features.csv', 'w')
    writer = csv.writer(fl)
    writer.writerow(['km', 'transmission', 'age', 'price'])
    for values in data_set:
    writer.writerow(values)

    fl.close()
</code>```

答:
The site is badly broken, if you keep going to a next page, you eventually hit  a loading loop on the browser, for me page 501 returned to 500 if i pasted it directly, if I used the next from 500 where I can see 501, I get a loading loop that never ends, we use a redirect back to the previous to terminate our loop.

I have also used lxml.html with cssselect, you can use bs4 if preferred, the logic is the same, but I would highly encourage using lxml, the deps are outlined here, you will also need to pip install cssselect:

```<code>import requests
from lxml import html
from typing import Iterator

url = "https://www.olx.com.ng/vehicles/cars/toyota/?search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry"

def parse_data(node_: html.Element, price: str) -> dict:
    """Parses the details section per individual car details page and returns a dict"""

    # Price we pulled from main page.
    details = {"price": price.strip("₦ ")}

    # Details are in a table.
    details_table = node_.cssselect("table.details")[0]

    # The th has the description, the anchor has the value.
    # we lower case and join the description, i.e "Type of car" -> type_of_car.
    data = iter(details_table.cssselect("tr th, .value"))
    details.update(("_".join(th.text.lower().split()), "".join(td.xpath(".//text()")).strip())
                   for th, td in (zip(data, data)))
    return details

def get_link_and_price(s: requests.Session, node_: html.Element) -> Iterator[dict]:
    """Gets the link and the associated price from each tr."""

    for child in node_.cssselect("table.offers td.offer"):
        link, price = child.cssselect("a.link")[0].get("href"), child.cssselect(".price strong")[0].text

        yield (parse_data(html.fromstring(s.get(link).content), price))

def start_request(url: str):
    with requests.Session() as s:
        get_ = s.get(url)
        node = html.fromstring(get_.content)

        # yield from subsequent iterators, i.e a dict of details.
        yield from get_link_and_price(s, node)

        # The site is broken, you click the next page button,
        #  and eventually you get stuck in a loading loop.
        # At some stage the next should disappear,
        # or only go back but it is wrongly implemented.
        # This will stop when we try a next page,
        #  and end up back at the current url i.e ?page=501 -> ?page=500.
        current_url = get_.url
        next_page = node.cssselect("a.pageNextPrev")[-1].get("href")
        get_next = s.get(next_page)
        node = html.fromstring(get_next.content)

        # Keep going through pages till our break condition is met.
        while current_url != get_next.url:
            node = html.fromstring(get_next.content)
            yield from get_link_and_price(s, node)
            current_url = get_next.url
            next_page = node.cssselect("a.pageNextPrev")[-1].get("href")
            get_next = s.get(next_page)

for dict_ in start_request(url):
    print(dict_)
</code>```

A snippet of the output:

```<code>{'price': '3,300,000', 'offer_from': 'Individual', 'year': '2008', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '65000'}
{'price': '3,000,000', 'offer_from': 'Individual', 'year': '2007', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '86500'}
{'price': '4,200,000', 'offer_from': 'Individual', 'year': '2013', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '39011'}
{'price': '4,500,000', 'offer_from': 'Business', 'year': '2010', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '93000'}
{'price': '890,000', 'offer_from': 'Business', 'year': '2001', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '110000'}
{'price': '1,050,000', 'offer_from': 'Individual', 'year': '2005', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': 'Low'}
{'price': '1,500,000', 'offer_from': 'Individual', 'year': '2008', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': 'Low'}
{'price': '1,150,000', 'offer_from': 'Individual', 'year': '2002', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '167'}
{'price': '2,200,000', 'offer_from': 'Individual', 'year': '2010', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '24689'}
{'price': '1,050,000', 'offer_from': 'Individual', 'year': '2004', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '92,000'}
</code>```

Body:
I'm trying to scrape this page! for a project i'm working on. I want to get the details (Price, Mileage, Transmission, and Age) of each car for all the pages. The issues I'm having with my code below are:

The first page link is different from others (No page number 1 <&page=1>)

The price of the car is not inside the table after clicking on each ad to get the details.

I'm wondering if anyone would be kind enough to help me look into this and advise. Thanks

    from bs4 import BeautifulSoup
    import requests
    import urllib.parse
    import csv

    # the Toyota Camry model page is used
    url = "https://www.olx.com.ng/vehicles/cars/toyota/?search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry"
    r = requests.get(url)
    data = r.text

    soup = BeautifulSoup(data, "html.parser")
    carLinks = set()
    pageLinks = set()
    data_set = []

    parsed = urllib.parse.urlparse(soup.select('a')[0].get('href'))
    nbPage = urllib.parse.parse_qs(parsed.query)['page'][1]
    print("There are " + str(nbPage) + " web pages to process")

    # for each web page that contains a grid of car offers
    for i in range(1, int(nbPage), 1):

    print("Processing web page: " + str(i))

    # each car offer link is saved into the carLinks
    for link in soup.select('#listContainer > div > section > div > tr > a'):
    carLinks.add(link.get('href').replace("//", "http://"))

    # the next url page is set
    url = "https://www.olx.com.ng/vehicles/cars/toyota/?
    search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry&page= + str(i) + "
    r = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data, "html.parser")

    #for each car link
    for carLink in carLinks:

    print("Processing car page: " + carLink)

    # we load the car page
    r = requests.get(carLink)
    data = r.text
    soup = BeautifulSoup(data, "html.parser")
    km = 0
    transmission = ""
    age = 0
    price = 0

    # for each attribute of the car
    for info in soup.select("table.item tr div.pricelabel"):

    # we keep the ones that we need
    if info.select('.item')[0].text == u'Mileage':
        km = int(info.select('.value')[0].text.replace(" ", "").replace("KM", ""))
    if info.select('.item')[0].text == u'Transmission':
        transmission = info.select('.value')[0].text
    if info.select('.item')[0].text == u'Year':
        age = 2017 - int(info.select('.value')[0].text)
    if info.select('.pricelabel')[0].text == u'Price':
        price = int(info.select('.pricelabel')[0].text.replace(" ", "").replace(u"₦", ""))

    # each car is an array of four features added to the data_set
    data_set.append([km, transmission, age, price])

    # the data_set is save into the CSV file
    fl = open('car_features.csv', 'w')
    writer = csv.writer(fl)
    writer.writerow(['km', 'transmission', 'age', 'price'])
    for values in data_set:
    writer.writerow(values)

    fl.close()

Body:
The site is badly broken, if you keep going to a next page, you eventually hit  a loading loop on the browser, for me page 501 returned to 500 if i pasted it directly, if I used the next from 500 where I can see 501, I get a loading loop that never ends, we use a redirect back to the previous to terminate our loop.

I have also used lxml.html with cssselect, you can use bs4 if preferred, the logic is the same, but I would highly encourage using lxml, the deps are outlined here, you will also need to pip install cssselect:

import requests
from lxml import html
from typing import Iterator

url = "https://www.olx.com.ng/vehicles/cars/toyota/?search%5Bfilter_enum_model%5D%5B0%5D=toyota%2Fcamry"

def parse_data(node_: html.Element, price: str) -> dict:
    """Parses the details section per individual car details page and returns a dict"""

    # Price we pulled from main page.
    details = {"price": price.strip("₦ ")}

    # Details are in a table.
    details_table = node_.cssselect("table.details")[0]

    # The th has the description, the anchor has the value.
    # we lower case and join the description, i.e "Type of car" -> type_of_car.
    data = iter(details_table.cssselect("tr th, .value"))
    details.update(("_".join(th.text.lower().split()), "".join(td.xpath(".//text()")).strip())
                   for th, td in (zip(data, data)))
    return details

def get_link_and_price(s: requests.Session, node_: html.Element) -> Iterator[dict]:
    """Gets the link and the associated price from each tr."""

    for child in node_.cssselect("table.offers td.offer"):
        link, price = child.cssselect("a.link")[0].get("href"), child.cssselect(".price strong")[0].text

        yield (parse_data(html.fromstring(s.get(link).content), price))

def start_request(url: str):
    with requests.Session() as s:
        get_ = s.get(url)
        node = html.fromstring(get_.content)

        # yield from subsequent iterators, i.e a dict of details.
        yield from get_link_and_price(s, node)

        # The site is broken, you click the next page button,
        #  and eventually you get stuck in a loading loop.
        # At some stage the next should disappear,
        # or only go back but it is wrongly implemented.
        # This will stop when we try a next page,
        #  and end up back at the current url i.e ?page=501 -> ?page=500.
        current_url = get_.url
        next_page = node.cssselect("a.pageNextPrev")[-1].get("href")
        get_next = s.get(next_page)
        node = html.fromstring(get_next.content)

        # Keep going through pages till our break condition is met.
        while current_url != get_next.url:
            node = html.fromstring(get_next.content)
            yield from get_link_and_price(s, node)
            current_url = get_next.url
            next_page = node.cssselect("a.pageNextPrev")[-1].get("href")
            get_next = s.get(next_page)

for dict_ in start_request(url):
    print(dict_)

A snippet of the output:

{'price': '3,300,000', 'offer_from': 'Individual', 'year': '2008', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '65000'}
{'price': '3,000,000', 'offer_from': 'Individual', 'year': '2007', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '86500'}
{'price': '4,200,000', 'offer_from': 'Individual', 'year': '2013', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '39011'}
{'price': '4,500,000', 'offer_from': 'Business', 'year': '2010', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '93000'}
{'price': '890,000', 'offer_from': 'Business', 'year': '2001', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '110000'}
{'price': '1,050,000', 'offer_from': 'Individual', 'year': '2005', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': 'Low'}
{'price': '1,500,000', 'offer_from': 'Individual', 'year': '2008', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': 'Low'}
{'price': '1,150,000', 'offer_from': 'Individual', 'year': '2002', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '167'}
{'price': '2,200,000', 'offer_from': 'Individual', 'year': '2010', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '24689'}
{'price': '1,050,000', 'offer_from': 'Individual', 'year': '2004', 'transmission': 'Automatic', 'model': 'Camry', 'type_of_car': '4 door', 'mileage': '92,000'}


问:
retrieve data from db to form on click (MVC entity framework)
I want to retrieve the selected data from db to a form for "update" operation in mvc. I want to do it with modal.</p>

答:
I think this is what you are looking for: https://cmatskas.com/update-an-mvc-partial-view-with-ajax/

Update: As someone pointed out, i shouldn't just redirect you to an article without giving a "real" answer. So:

You can create an action that returns a partial view containing the updated values and get that partial view using AJAX. You can get a detailed, and propably better, explanation in the link above.

Update 2: For example (not tested):

Your Action:

```<code>public ViewResult GetForm()
{
    //Get some data from your database
    var model = new FormBindingModel
    {
        //Populate this model with data from your database
    };

    return View("_Form", model);
}
</code>```

In your (parent) page:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#something").on("event", function () {
            $("#formcontainer").empty().append('@(Url.Action("GetForm","ControllerName")));
        });
    });
</script>
</code>```

With this example your ajax call retrieves a partial page (your form) populated by an object, but i guess you can make your own implementation to fit your needs.

Body:
I think this is what you are looking for: https://cmatskas.com/update-an-mvc-partial-view-with-ajax/

Update: As someone pointed out, i shouldn't just redirect you to an article without giving a "real" answer. So:

You can create an action that returns a partial view containing the updated values and get that partial view using AJAX. You can get a detailed, and propably better, explanation in the link above.

Update 2: For example (not tested):

Your Action:

public ViewResult GetForm()
{
    //Get some data from your database
    var model = new FormBindingModel
    {
        //Populate this model with data from your database
    };

    return View("_Form", model);
}

In your (parent) page:

<script type="text/javascript">
    $(document).ready(function () {
        $("#something").on("event", function () {
            $("#formcontainer").empty().append('@(Url.Action("GetForm","ControllerName")));
        });
    });
</script>

With this example your ajax call retrieves a partial page (your form) populated by an object, but i guess you can make your own implementation to fit your needs.


问:
Align two buttons that are in two different DIVs
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div>
<div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div></code>```

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

答:
You can use display:table-cell and position. I have taken the liberty of adding a wrapper around the two .directeurs. See it it works for you.

.directeur-wrapper{
display:table;
}
.directeur{
display:table-cell;
width:50%;
padding:20px 20px 80px;
position:relative;
}
.directeur img{max-width:100%;}
.directeur a{position:absolute; bottom:0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeur-wrapper">
<div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
            <img src="http://via.placeholder.com/300x70" alt="">
        </div>
        <div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
            <img src="http://via.placeholder.com/300x70" alt="">
        </div>
        </div></code>```

Body:
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

Body:
You can use display:table-cell and position. I have taken the liberty of adding a wrapper around the two .directeurs. See it it works for you.

.directeur-wrapper{
display:table;
}
.directeur{
display:table-cell;
width:50%;
padding:20px 20px 80px;
position:relative;
}
.directeur img{max-width:100%;}
.directeur a{position:absolute; bottom:0;}

<div class="directeur-wrapper">
<div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
            <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
        </div>
        <div class="directeur">
            <img src="http://via.placeholder.com/500x150" alt="">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
            <a href=""><img src="http://via.placeholder.com/300x70" alt=""></a>
        </div>
        </div>


问:
How to find the entries in one table not like those in another
I have a table called whitelist_email which looks like this

```<code>+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |
</code>```

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

```<code>SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);
</code>```

答:
```<code>SELECT verified_email
from user_info
where   SUBSTRING(verified_email,INSTR(reverse(verified_email),".")+1,length(verified_email))
    not in (select email_suffix from whitelist_email);
</code>```

Body:
I have a table called whitelist_email which looks like this

+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);


答:
Well, this is kinda difficult. data could mean anything.

You could try the UNIX utility file or open the file with a hex editor and look for interesting strings (the utility strings is helpful for that too).

Title: Reading binary file without knowing file format

Body:
I'm working on a java project and i have to read some files like these:
- EntryID.data
- EntryID.index
- KeyText.data
- KeyText.index
...

I think these files are used in a dictionary project but i can't find a any document about this. How can i read them or know the format of them ? Sorry for my english =.=

Thanks alot!


问:
Error installing Tensorflow CPU-only Windows 8.1 Python 3.5.2

I get the following error when I try to import tensorflow after installing it.

What I did:

 1. pip install --upgrade tensorflow

 2. Python version is 3.5.2

 3. I want to install CPU-only tensorflow.

 4. The OS is Windows 8.1

```<code>>>> import tensorflow
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
        return importlib.import_module(mname)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
      File "<frozen importlib._bootstrap>", line 577, in module_from_spec
      File "<frozen importlib._bootstrap_external>", line 906, in create_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
    ImportError: DLL load failed: The specified module could not be found.
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
        from tensorflow.python.pywrap_tensorflow_internal import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
        _pywrap_tensorflow_internal = swig_import_helper()
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
        return importlib.import_module('_pywrap_tensorflow_internal')
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: No module named '_pywrap_tensorflow_internal'
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
        from tensorflow.python import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
        from tensorflow.python import pywrap_tensorflow
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 52, in <module>
        raise ImportError(msg)
    ImportError: Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
        return importlib.import_module(mname)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
      File "<frozen importlib._bootstrap>", line 577, in module_from_spec
      File "<frozen importlib._bootstrap_external>", line 906, in create_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
    ImportError: DLL load failed: The specified module could not be found.
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
        from tensorflow.python.pywrap_tensorflow_internal import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
        _pywrap_tensorflow_internal = swig_import_helper()
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
        return importlib.import_module('_pywrap_tensorflow_internal')
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: No module named '_pywrap_tensorflow_internal'
    Failed to load the native TensorFlow runtime.
    See https://www.tensorflow.org/install/install_sources#common_installation_problems
    for some common reasons and solutions.  Include the entire stack trace
</code>```

答:
Install first anaconda
Then try installing tensor flow using anaconda version from https://www.tensorflow.org/install/install_windows

Then pycharm will automatically detect tensorflow

If problem still exist then try this youtube video which will for sure help you to install in pycharm https://www.youtube.com/watch?v=83vR1Nz3dHA&t=4s

Body:
I get the following error when I try to import tensorflow after installing it.

What I did:

 1. pip install --upgrade tensorflow

 2. Python version is 3.5.2

 3. I want to install CPU-only tensorflow.

 4. The OS is Windows 8.1

>>> import tensorflow
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
        return importlib.import_module(mname)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
      File "<frozen importlib._bootstrap>", line 577, in module_from_spec
      File "<frozen importlib._bootstrap_external>", line 906, in create_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
    ImportError: DLL load failed: The specified module could not be found.
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
        from tensorflow.python.pywrap_tensorflow_internal import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
        _pywrap_tensorflow_internal = swig_import_helper()
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
        return importlib.import_module('_pywrap_tensorflow_internal')
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: No module named '_pywrap_tensorflow_internal'
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
        from tensorflow.python import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
        from tensorflow.python import pywrap_tensorflow
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 52, in <module>
        raise ImportError(msg)
    ImportError: Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
        return importlib.import_module(mname)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
      File "<frozen importlib._bootstrap>", line 577, in module_from_spec
      File "<frozen importlib._bootstrap_external>", line 906, in create_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
    ImportError: DLL load failed: The specified module could not be found.
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
        from tensorflow.python.pywrap_tensorflow_internal import *
      File "C:\Program Files\JetBrains\PyCharm 2017.1.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
        _pywrap_tensorflow_internal = swig_import_helper()
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
        return importlib.import_module('_pywrap_tensorflow_internal')
      File "C:\Users\Student\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: No module named '_pywrap_tensorflow_internal'
    Failed to load the native TensorFlow runtime.
    See https://www.tensorflow.org/install/install_sources#common_installation_problems
    for some common reasons and solutions.  Include the entire stack trace


问:
WEKA's "Class has to be nominal if cost matrix given" error
I am trying to classify a data with 51 features with the command

DecisionTable -X 1 -S "weka.attributeSelection.GreedyStepwise -T -1.79 -N -1 -num-slots 1"

but I am getting the error

What does this error mean about nominal class for cost matrix?

答:
As mentioned by knb, you can solve this problem by changing the non-nominal values to Nominal. You can use Multifilter to have many filters.

You can find the Remove filter in the Multifilter under Filters > Unsupervised > Attribute > Remove.

You can find the NumericToNomial Filters > Unsupervised > Attribute > NumericToNomial

Example showing Multifilter with Remove Filter and NumericToNomial


问:
Multiple top level windows and modal dialog in one of them without blocking the other one
I have an application with two top level windows (i.e. having no parent widget), which are rather independent of each other and I want to enable the users switch between them any time they want. However when one of these windows opens a modal dialog by calling dlg.exec(), it blocks also the other window. The user cannot switch to it at all. I managed to create modal dialogs with dlg.setWindowModality(Qt::WindowModal) and then dlg.show() but his shows the dialog and continues without waiting for the return value from the dialog. So if I want to process the result of the modal dialog (typically querying for some information - e.g. open/save file dialog), I need to move the functionality processing the dialog result some other function (other than the one which opened the dialog) and either use ad hoc signal/slot connection, some callback or let the dialog itself know how to process the result, which in my view is a bad design. And it is especially difficult with built in dialogs like file dialogs or QMessageBox...

So my question is: is there any trick in Qt which would let me have two top level windows, which the user can freely switch between, and at the same time be able to open modal dialogs like with dlg.exec(), which would block only one window and wait for the dialog result but do not block the other window? I think it is not possible but maybe I missed something. I mean for example some magic with threads and QEventLoop which is unknown to me? As far as I know the widgets must reside in the main thread, which is a bit trouble in this case if I wanted to use threads...

PS: to let you have better idea of what I need, imagine Excel in one window and its VB editor in the other one. The user is able to switch to VB at any time.

答:
It works using QDialog::exec().

Here is a working example:

main.cpp

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    MainWindow w2;
    w2.show();

    return a.exec();
}
</code>```

mainwindow.cpp

```<code>// I skipped the rest of the code as it is just the template code from Qt Creator template project.
void MainWindow::on_pushButton_clicked() // mainwindow.ui creates a QPushButton named "pushButton"
{
    QMessageBox mb(this);
    mb.setModal(true);
    mb.setWindowModality(Qt::WindowModal);
    mb.exec();
}
</code>```

It opens 2 windows and I can interact with both independently regardless if the other has its QMessageBox opened or not.

Body:
It works using QDialog::exec().

Here is a working example:

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    MainWindow w2;
    w2.show();

    return a.exec();
}

mainwindow.cpp

// I skipped the rest of the code as it is just the template code from Qt Creator template project.
void MainWindow::on_pushButton_clicked() // mainwindow.ui creates a QPushButton named "pushButton"
{
    QMessageBox mb(this);
    mb.setModal(true);
    mb.setWindowModality(Qt::WindowModal);
    mb.exec();
}

It opens 2 windows and I can interact with both independently regardless if the other has its QMessageBox opened or not.


答:
Just citing an answer found on another thread that is relevant to your problem :

Either error indicates that your system has not installed MSVCP140.DLL,
which TensorFlow requires.

To fix this error:

Determine whether MSVCP140.DLL is in your %PATH% variable.

If MSVCP140.DLL is not in your %PATH%, install the
 Visual C++ 2015 redistributable (x64 version), which contains this DLL.

Original answer : https://stackoverflow.com/a/42011114/4895899

Title: Error installing Tensorflow CPU-only Windows 8.1 Python 3.5.2


问:
Regex to match punctuation followed by space with some exceptions
I am trying to come up with a regex which matches punctuation (!, ?, and .) followed by a space. I want to NOT match periods which are preceded by salutations like "Mr.", "Mrs.", etc...

Doing the first part is simple enough:
r"[\?|!|\.] "

But I am struggling with the second part. Here is what I have so far:
r"(?<=[^(Mr|Ms)])\. "

The second one does NOT match something like "radar. " or "cups. " or "loom. " which is bad. I am also having trouble combining both those regexes into a single one.

Thanks.

答:
This should work:

```<code>(?<!(Mr)|(Ms))(?<!(Mrs))[.!?](?=\s|$)
</code>```

Here's a demo:

```<code>In [19]: re.search(r'(?<!(Mr)|(Ms))(?<!(Mrs))[.](?=\s|$))', 'Mrs. Jones!').group(0)
Out[19]: '!'
</code>```

There's a negative lookbehind for Mr and Mrs, and a positive lookahead for either a space or EOL.

Please note that each separate salutation of different length will needs its own lookbehind.

Edited, as per OP's request:

```<code>In [78]: re.search(r'((?<!(Mr)|(Ms))(?<!(Mrs))[.])|([!?])(?=\s|$)', 'Mrs! Jones').group(0)
Out[78]: '!'
</code>```

Body:
This should work:

(?<!(Mr)|(Ms))(?<!(Mrs))[.!?](?=\s|$)

Here's a demo:

In [19]: re.search(r'(?<!(Mr)|(Ms))(?<!(Mrs))[.](?=\s|$))', 'Mrs. Jones!').group(0)
Out[19]: '!'

There's a negative lookbehind for Mr and Mrs, and a positive lookahead for either a space or EOL.

Please note that each separate salutation of different length will needs its own lookbehind.

Edited, as per OP's request:

In [78]: re.search(r'((?<!(Mr)|(Ms))(?<!(Mrs))[.])|([!?])(?=\s|$)', 'Mrs! Jones').group(0)
Out[78]: '!'


问:
How much performance do you get out a Heroku dynos/workers?
How much traffic can a site with 1 or 2 Dynos handle on www.Heroku.com and would increasing workers improve this? Any help on dynos/workers would be appreciated. </p>

答: I would also suggest installing the New Relic Add-on. It lets you do basic performance monitoring and helps identify bottlenecks.</p>


问:
Combine two regex together
I have this expression from a ps ax list that I want to parse:

```<code>183838 ? myprocess -uuid 0f6309e3-bee2-4747-b76d-7aaf4d0f074e serial=802e7fd9-a2ab-e411-8000-001e67ca95b2
</code>```

I want to match the process id (183838) AND the uuid expression (0f6309e3-bee2-4747-b76d-7aaf4d0f074e).

I have the two regexes that match each of them:

```<code># PID
([0-9]*)
# UUID
(?<=uuid).([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})
</code>```

But I can't find how to combine them together to have this as result with sed:

```<code>183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e
</code>```

awk is not an option since it must be column number independent.

答: You can use the | or operator in regex in between your two regex expressions to combine them.

Title: Combine two regex together

Body:
I have this expression from a ps ax list that I want to parse:

183838 ? myprocess -uuid 0f6309e3-bee2-4747-b76d-7aaf4d0f074e serial=802e7fd9-a2ab-e411-8000-001e67ca95b2

I want to match the process id (183838) AND the uuid expression (0f6309e3-bee2-4747-b76d-7aaf4d0f074e).

I have the two regexes that match each of them:

# PID
([0-9]*)
# UUID
(?<=uuid).([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})

But I can't find how to combine them together to have this as result with sed:

183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e

awk is not an option since it must be column number independent.


问:
Kendo UI - Source code for Demo Service
Kendo UI Online demo use service, is the source code available for these services?

http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products

http://demos.telerik.com/kendo-ui/service

I am interested in looking at service methods to find out how Odata end points are exposed.

答:
Source code of the services are available on Github:

link

Title: Kendo UI - Source code for Demo Service


问:
Parsing a JSON array of values as POJOs
I need to process responses from an external SAP service which returns data as an array of arrays like this:

```<code>{
    "INFO":"",
    "SERVICE_NAME":[["PARAM1","PARAM2","PARAM3","PARAM4"]],
    "RESULTS":[
        ["object1fieldValue1","object1fieldValue2"],
        ["object2fieldValue1","object2fieldValue2"]
    ]
}
</code>```

I would like to process the RESULTS further as a list of DTOs like this:

```<code>public class ResultItemDto {
    private String field1;
    private String field2;
}
</code>```

instead of working with every object as a list of Strings and possibly mapping it manually to DTOs.

What would be the right, concise "Jackson way" of mapping such JSON directly to POJOs?

答:
You can annotate a class with @JsonFormat to indicate that it will appear as an array in JSON:

```<code>@JsonFormat(shape = JsonFormat.Shape.ARRAY)
class ResultItemDto {
    private String field1;
    private String field2;
}
</code>```

To verify the above I created a wrapper class for the full object:

```<code>class ResultWrapper {
    private List<ResultItemDto> results;
}
</code>```

And deserialize like this:

```<code>ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);

ResultWrapper result = mapper.readValue(json, ResultWrapper.class);
</code>```

Where ACCEPT_CASE_INSENSITIVE_PROPERTIES is used because your JSON has fields with upper case names.

Documentation for @JsonFormat and pertinent shapes

Title: Parsing a JSON array of values as POJOs

Body:
I need to process responses from an external SAP service which returns data as an array of arrays like this:

{
    "INFO":"",
    "SERVICE_NAME":[["PARAM1","PARAM2","PARAM3","PARAM4"]],
    "RESULTS":[
        ["object1fieldValue1","object1fieldValue2"],
        ["object2fieldValue1","object2fieldValue2"]
    ]
}

I would like to process the RESULTS further as a list of DTOs like this:

public class ResultItemDto {
    private String field1;
    private String field2;
}

instead of working with every object as a list of Strings and possibly mapping it manually to DTOs.

What would be the right, concise "Jackson way" of mapping such JSON directly to POJOs?

Body:
You can annotate a class with @JsonFormat to indicate that it will appear as an array in JSON:

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
class ResultItemDto {
    private String field1;
    private String field2;
}

To verify the above I created a wrapper class for the full object:

class ResultWrapper {
    private List<ResultItemDto> results;
}

And deserialize like this:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);

ResultWrapper result = mapper.readValue(json, ResultWrapper.class);

Where ACCEPT_CASE_INSENSITIVE_PROPERTIES is used because your JSON has fields with upper case names.

Documentation for @JsonFormat and pertinent shapes


问:
Best practices for using Drools Expert/Flow in a Web Application
I'm currently teaching myself Drools Expert/Flow as well as GWT. I want to use Drools Flow as an event/command bus and business rule engine to achieve loose coupling between different parts of the application.

So far I've gotten both Expert and Flow working from my test cases, but I have a hard time figuring how to best implement Flows within a web container.

Should I put all the scaffolding into an Stateless Session EJB and let each request set up everything from scratch and then run the flows/rules? This seems like a waste of resources to me. Can I instead store a single knowledge session and share that sessions between web requests, accessing it concurrently, would that scenario scale and is it thread safe (my guess is no)? Is pooling knowledge sessions a good idea?

What I'm asking for is basically if there is any best practices for the above? The documentation and examples, while otherwise quite good, are not clear on these particular points.

I did read something about Drools Grid, not sure if that would solve my problem and that seems to be under development. If my questions are unclear, please say so.

BR Magnus

答:
A KnowledgeBase is thread safe and heavy weight (it's not cheap to create), so you 'll probably want to keep that in an application scope.

For now, most people tend to use a stateless architecture and create a StatelessKnowlegdeSession (thread unsafe and cheap to create) for every web request, for example in a stateless session bean (or a seam/CDI bean or a spring bean).
However, if you have the power of stateful EJB's, it can be rewarding to keep use one StafefulKnowlegdeSession to handle all requests in the same conversation.

I am not sure if StatefulKnowlegdeSession is thread safe (don't think so),
so I made an issue: https://issues.jboss.org/browse/JBRULES-2842


问:
How to decrypt a DES encrypted string in iOS?
I used PHP to encrypt a string with PKCS #7 padding in DES algorithm.

I want to know how to use CCCrypt in iOS to decrypt the DES encrypted string. Appreciate it if you could provide some sample codes to help me.

Thanks.

答:
```<code>- (NSData *)encryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;
size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer = malloc(bufferSize);

CCCryptorStatus result = CCCrypt( kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer, bufferSize,
                                 &numBytesEncrypted);
NSData *output = [NSData dataWithBytes:buffer length:numBytesEncrypted];
free(buffer);
if( result == kCCSuccess )
{
    NSLog(@"encoded str %@",[output base64EncodedStringWithOptions:0]);
    return output;
} else {
    NSLog(@"Failed DES encrypt...");
    return nil;
}
}
- (NSData *) decryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;

size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer_decrypt = malloc(bufferSize);
CCCryptorStatus result = CCCrypt( kCCDecrypt , kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer_decrypt, bufferSize,
                                 &numBytesEncrypted );

NSData *output = [NSData dataWithBytes:buffer_decrypt length:numBytesEncrypted];
free(buffer_decrypt);
if( result == kCCSuccess )
{
    NSString *decodedString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
    NSLog(@"decoded str %@",decodedString);
    return output;
} else {
    NSLog(@"Failed DES decrypt ...");
    return nil;
}
}
</code>```

<p>-- Then you can call method like </p>

```<code>  [self decryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:[self encryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:["YOUR--INPUT__STRING" dataUsingEncoding:NSUTF8StringEncoding]]];
</code>```

<p>-- "qwertykey" is the secretkey supplied</p>

Body:
- (NSData *)encryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;
size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer = malloc(bufferSize);

CCCryptorStatus result = CCCrypt( kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer, bufferSize,
                                 &numBytesEncrypted);
NSData *output = [NSData dataWithBytes:buffer length:numBytesEncrypted];
free(buffer);
if( result == kCCSuccess )
{
    NSLog(@"encoded str %@",[output base64EncodedStringWithOptions:0]);
    return output;
} else {
    NSLog(@"Failed DES encrypt...");
    return nil;
}
}
- (NSData *) decryptDESByKey:(NSData *)key data:(NSData *)data
{
size_t numBytesEncrypted = 0;

size_t bufferSize = data.length + kCCBlockSizeDES;
void *buffer_decrypt = malloc(bufferSize);
CCCryptorStatus result = CCCrypt( kCCDecrypt , kCCAlgorithmDES, kCCOptionPKCS7Padding,
                                 key.bytes, kCCKeySizeDES,
                                 NULL,
                                 data.bytes, data.length,
                                 buffer_decrypt, bufferSize,
                                 &numBytesEncrypted );

NSData *output = [NSData dataWithBytes:buffer_decrypt length:numBytesEncrypted];
free(buffer_decrypt);
if( result == kCCSuccess )
{
    NSString *decodedString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
    NSLog(@"decoded str %@",decodedString);
    return output;
} else {
    NSLog(@"Failed DES decrypt ...");
    return nil;
}
}

-- Then you can call method like

  [self decryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:[self encryptDESByKey:[@"qwertykey" dataUsingEncoding:NSUTF8StringEncoding] data:["YOUR--INPUT__STRING" dataUsingEncoding:NSUTF8StringEncoding]]];

-- "qwertykey" is the secretkey supplied


问:
When Long touch on my website image from mobile device come design issue
In my website using desktop to mouse enter and mouse leave on image is working fine,
but when I am using mobile device and tablet a design issue occurs. When I use this web on touch device long press on image it shows design issue.

This is my web site link please check on your mobile or tablet.

easyinnolight.com

答: Adding position: absolute; to #featurecontent seems fix your issue


问:
Access value in controller for ng-if property in html element
I have an existing module which I get, I add a directive which loads an external file containing a modal window and I am setting the initial value of the modal to true:

```<code>var application = angular.module('app');
application.directive("history", function () {
    return {
        templateUrl: "dir/dir/dir/file.html"
    };
});
application.controller("factoryController", function ($scope) {
    $scope.ShowModal = true;
});
</code>```

In my HTML I have my modal window, and I want to create the window when my ShowModal property in my controller is true.  How do I access that property in the HTML?  I've tried this:

```<code><div ng-if="ShowModal" id="modal" class="modal" >
</code>```

but this does not seem to work. It seems very simple, but I'm fairly new to angular js so any help would be great!

答:
To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camel case name, myHistory, but when invoking it, you must use - separated name, my-history .You can invoke a directive by using many methods in view, an element being one. So try this:

JS:

```<code> var application = angular.module('app');
    application.directive('modalDialog', function($rootScope) {
    return {
        restrict: 'E',
        scope: {
            show: '=',
            close: '='
        },
        replace: true,
        transclude: true,
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            scope.dialogStyle.width = '500px';
            if (attrs.width) scope.dialogStyle.width = attrs.width;
            if (attrs.height) scope.dialogStyle.height = attrs.height;
            if (attrs.header) scope.dialogHeader = attrs.header;
            if (attrs.content) scope.dialogContent = attrs.content;
            if (attrs.closeText) scope.closeText = attrs.closeText;
            scope.hideModal = function() {
                scope.show = false;
            };
            scope.$watch('show',function(value){
                if(value==true){
                    $rootScope.noScroll = true;
                }else{
                    $rootScope.noScroll = false;
                }
            })
        },
        template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><span ng-if='close==true' class='ng-modal-close' ng-click='hideModal()'>X</span><h2 class='ng-modal-header' ng-if='dialogHeader'>{{dialogHeader}}</h2><div class='ng-modal-dialog-content'><p ng-if='dialogContent'>{{dialogContent}}</p><ng-transclude></ng-transclude><button type='button' ng-click='hideModal()' ng-if='closeText'>{{closeText}}</button></div></div></div>"
    }
});
    application.controller("factoryController", function ($scope) {
        $scope.ShowModal = true;
    });
</code>```

HTML:

```<code><modal-dialog show="ShowModal" ></modal-dialog>
</code>```

Sample Usage:

```<code><modal-dialog show="fileTypeError" header="Warning" close="true">
    <p>{{fileTypeError}}</p>
    <button type="button" ng-click="closefilePopup()" class="btn_approve1 none">Ok</button>
</modal-dialog>
</code>```

Body:
I have an existing module which I get, I add a directive which loads an external file containing a modal window and I am setting the initial value of the modal to true:

var application = angular.module('app');
application.directive("history", function () {
    return {
        templateUrl: "dir/dir/dir/file.html"
    };
});
application.controller("factoryController", function ($scope) {
    $scope.ShowModal = true;
});

In my HTML I have my modal window, and I want to create the window when my ShowModal property in my controller is true.  How do I access that property in the HTML?  I've tried this:

but this does not seem to work. It seems very simple, but I'm fairly new to angular js so any help would be great!

Body:
To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camel case name, myHistory, but when invoking it, you must use - separated name, my-history .You can invoke a directive by using many methods in view, an element being one. So try this:

JS:

 var application = angular.module('app');
    application.directive('modalDialog', function($rootScope) {
    return {
        restrict: 'E',
        scope: {
            show: '=',
            close: '='
        },
        replace: true,
        transclude: true,
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            scope.dialogStyle.width = '500px';
            if (attrs.width) scope.dialogStyle.width = attrs.width;
            if (attrs.height) scope.dialogStyle.height = attrs.height;
            if (attrs.header) scope.dialogHeader = attrs.header;
            if (attrs.content) scope.dialogContent = attrs.content;
            if (attrs.closeText) scope.closeText = attrs.closeText;
            scope.hideModal = function() {
                scope.show = false;
            };
            scope.$watch('show',function(value){
                if(value==true){
                    $rootScope.noScroll = true;
                }else{
                    $rootScope.noScroll = false;
                }
            })
        },
        template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><span ng-if='close==true' class='ng-modal-close' ng-click='hideModal()'>X</span><h2 class='ng-modal-header' ng-if='dialogHeader'>{{dialogHeader}}</h2><div class='ng-modal-dialog-content'><p ng-if='dialogContent'>{{dialogContent}}</p><ng-transclude></ng-transclude><button type='button' ng-click='hideModal()' ng-if='closeText'>{{closeText}}</button></div></div></div>"
    }
});
    application.controller("factoryController", function ($scope) {
        $scope.ShowModal = true;
    });

HTML:

<modal-dialog show="ShowModal" ></modal-dialog>

Sample Usage:

<modal-dialog show="fileTypeError" header="Warning" close="true">
    <p>{{fileTypeError}}</p>
    <button type="button" ng-click="closefilePopup()" class="btn_approve1 none">Ok</button>
</modal-dialog>


问:
MySQL partition and unique key
We are having a table like this to save login tokens per user sessions. This table was not partitioned earlier but now we decided to partition it to improve performance as it contains over a few millions rows.

```<code>CREATE TABLE `tokens` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned DEFAULT NULL,
  `session` int(10) unsigned DEFAULT '0',
  `token` varchar(128) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `usersession` (`uid`,`session`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PARTITION BY HASH(id) PARTITIONS 101;
</code>```

We plan to partition based on 'id' as it's primarily used for "select" queries and hence can effectively perform pruning.

However the problem is we maintain unique index of (uid, session) and partition requires participating column to be part of unique index. Now in this case unique index of (id, uid, session) doesn't make sense (will always be unique).

is there anyway to get around this issue without manually checking (uid, session).

答:
Presumably your unique uid,sessionkey index enforces some business rule for you.

Do you rely on DBMS enforcement of that rule? Do you use INSERT .... ON DUPLICATE KEY UPDATE... statements, or use error handlers, or some such thing, to handle this uniqueness?  Or is it there just for good measure?

If you rely on that unique index, partitioning this table on id will not work. Fugeddaboudit.

If you can delete that index, or delete its unique constraint, you may be able to proceed with partitioning. But partitioning isn't generally suitable for tables with multiple unique keys.

A 40M-row table is ordinarily not large enough to be a good candidate for partitioning. If you're having performance problems you should investigate improving your indexing instead.

Edit: If you have modern hardware (multi-terabyte storage, plenty of RAM) and well-chosen indexes, partitioning is (I believe) more trouble that it's worth. It's definitely a lot of trouble for tables with fewer than about  10**9 rows. When your autoincrementing id values must be BIGINT rather than INT data types (because int.MaxValue isn't big enough), that's when partitioning starts to be worth considering.

It's most effective when all queries filter based on the partitioning key.  Filtering on other criteria without the partitioning key is slow.

Pro tip: The old saying about regular expressions also applies to partititions.  If you solve a problem with partitioning, now you have two problems.

Title: MySQL partition and unique key

Body:
We are having a table like this to save login tokens per user sessions. This table was not partitioned earlier but now we decided to partition it to improve performance as it contains over a few millions rows.

CREATE TABLE `tokens` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned DEFAULT NULL,
  `session` int(10) unsigned DEFAULT '0',
  `token` varchar(128) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `usersession` (`uid`,`session`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PARTITION BY HASH(id) PARTITIONS 101;

We plan to partition based on 'id' as it's primarily used for "select" queries and hence can effectively perform pruning.

However the problem is we maintain unique index of (uid, session) and partition requires participating column to be part of unique index. Now in this case unique index of (id, uid, session) doesn't make sense (will always be unique).

is there anyway to get around this issue without manually checking (uid, session).


问:
What's the relationship between sed, grep, find, awk, gawk, which one is preferred?
I'm new to Linux/Unix. I find some task can be accomplished by many ways using these commands. Is there some relationship between them? Or which one is preferred? Which one is outdated?

Thanks.

答:
These tools do different things, so which one is preferred depends on what you want to do.

Of the tools you mention, find is a little different than the others -- it works on filesystems to search for files with certain attributes (name, date, permissions...).

sed and grep take text files as input, operate on them, and output the results.  They both heavily use regular expressions.  sed ("Stream EDitor") is generally used for search-and-replace operations.  grep ("Global Regular Expression Print") outputs lines in a text file that match some pattern.

On Linux systems, awk and gawk are generally different names for the same program, the GNU version of AWK (named after its creators "Aho, Weinberger, Kernighan").  awk can also refer to the "classic" version of awk that doesn't have the GNU extensions, and there are other variants nawk ("new awk") and mawk ("Mike's AWK").  awk does far more than pattern matching; it's really a full-blown programming language, though it's geared toward breaking up input text into lines and fields and operating on them (including numeric operations, so it's easy to do things like total up columns or do statistical calculations).