问:
How to disassemble, modify and then reassemble a Linux executable?
Is there anyway this can be done? I've used objdump but that doesn't produce assembly output that will be accepted by any assembler that I know of. I'd like to be able to change instructions within an executable and then test it afterwards.</p>

答:
miasm

https://github.com/cea-sec/miasm

This appears to be the most promising concrete solution. According to the project description, the library can:

Opening / modifying / generating PE / ELF 32 / 64 LE / BE using Elfesteem

Assembling / Disassembling X86 / ARM / MIPS / SH4 / MSP430

So it should basically:

parse the ELF into an internal representation (disassembly)

modify what you want

generate a new ELF (assembly)

I don't think it generates a textual disassembly representation, you will likely have to walk through Python data structures.

TODO find a minimal example of how to do all of that using the library. A good starting point seems to be example/disasm/full.py, which parses a given ELF file. The key top-level structurei is Container, which reads the ELF file with Container.from_stream. TODO how to reassemble it afterwards? This article seems to do it: http://www.miasm.re/blog/2016/03/24/re150_rebuild.html

This question asks if there are any other such libraries: https://reverseengineering.stackexchange.com/questions/1843/what-are-the-available-libraries-to-statically-modify-elf-executables

Related questions:

https://reverseengineering.stackexchange.com/questions/185/how-do-i-add-functionality-to-an-existing-binary-executable

https://askubuntu.com/questions/617441/how-can-edit-a-executable-file-linux

I think this problem is not automatable

I think the general problem is not fully automatable, and the general solution is basically equivalent to "how to reverse engineer" a binary.

In order to insert or remove bytes in a meaningful way, we would have to ensure that all possible jumps keep jumping to the same locations.

In formal terms, we need to extract the control flow graph of the binary.

However, with indirect branches for example, https://en.wikipedia.org/wiki/Indirect_branch , it is not easy to determine that graph, see also: Indirect jump destination calculation


来源: stackexchange

问:
Dynamically composing a view with Aurelia
I am trying to dynamically compose a view, but at run time i get the error Error: Unable to find module with ID: app/components/customers/customer-type-view-converter.html. I’m using webpack.

Here’s the view converter that i’m using

```<code> import {PLATFORM} from 'aurelia-framework';

export class CustomerTypeViewConverter {
    toView(type: string) {
     return  type  == 'LEGAL' ? PLATFORM.moduleName("createLEGALcustomer.html") : PLATFORM.moduleName("createNATURALcustomer.html")
    }
  }
</code>```

here's the template that calls the convertor

```<code><template>

    <require from="./customer-type-view-converter"></require>
    <ux-dialog style="min-width:500px">

        <ux-dialog-header>
            <h1>Create Customer</h1>
        </ux-dialog-header>

        <ux-dialog-body>
            <form class="form-horizontal">

                <div class="form-group">

                    <label for="name" class="col-sm-4 control-label">Customer Type:</label>
                    <div class="col-sm-8">
                        <select value.bind="customer.customerType">
                            <option value="NATURAL">Person</option>
                            <option value="LEGAL">Company or Organisation</option>
                        </select>

                    </div>

                </div>

                <compose view.bind="customer.customerType | customerTypeView"></compose>

            </form>

        </ux-dialog-body>

        <ux-dialog-footer>
            <button click.trigger="controller.cancel()">Cancel</button>
            <button click.trigger="submit()">Ok</button>
        </ux-dialog-footer>

    </ux-dialog>

</template>
</code>```

答:
Two issues here. Firstly. the class name should have been CustomerTypeViewValueConverter in order for Aurelia to reconise it as a special class that doen't require a view.

And in the Value converter itself the html files should have been prefixed with./ so webpack could find them

updated value converter below

```<code> import {PLATFORM } from 'aurelia-framework';

export class CustomerTypeViewValueConverter  {
    toView(type: string) {
     return  type  == 'LEGAL' ? PLATFORM.moduleName("./createLEGALcustomer.html") : PLATFORM.moduleName("./createNATURALcustomer.html")
    }
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to dynamically compose a view, but at run time i get the error Error: Unable to find module with ID: app/components/customers/customer-type-view-converter.html. I’m using webpack.

Here’s the view converter that i’m using

 import {PLATFORM} from 'aurelia-framework';

export class CustomerTypeViewConverter {
    toView(type: string) {
     return  type  == 'LEGAL' ? PLATFORM.moduleName("createLEGALcustomer.html") : PLATFORM.moduleName("createNATURALcustomer.html")
    }
  }

here's the template that calls the convertor

<template>

    <require from="./customer-type-view-converter"></require>
    <ux-dialog style="min-width:500px">

        <ux-dialog-header>

Create Customer

        </ux-dialog-header>

        <ux-dialog-body>
            <form class="form-horizontal">

                    Customer Type:

                        <select value.bind="customer.customerType">
                            <option value="NATURAL">Person</option>
                            <option value="LEGAL">Company or Organisation</option>
                        </select>

                <compose view.bind="customer.customerType | customerTypeView"></compose>

            </form>

        </ux-dialog-body>

        <ux-dialog-footer>
            <button click.trigger="controller.cancel()">Cancel</button>
            <button click.trigger="submit()">Ok</button>
        </ux-dialog-footer>

    </ux-dialog>

</template>

Body:
Two issues here. Firstly. the class name should have been CustomerTypeViewValueConverter in order for Aurelia to reconise it as a special class that doen't require a view.

And in the Value converter itself the html files should have been prefixed with./ so webpack could find them

updated value converter below

 import {PLATFORM } from 'aurelia-framework';

export class CustomerTypeViewValueConverter  {
    toView(type: string) {
     return  type  == 'LEGAL' ? PLATFORM.moduleName("./createLEGALcustomer.html") : PLATFORM.moduleName("./createNATURALcustomer.html")
    }
  }


问:
operator.setitem problem in python 3
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

```<code>people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}
</code>```

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

答:
In Python 3, the result of map is lazy which can give you headache when debugging stuff that worked flawlessly in older versions of Python. In other words, it is a generator, so you have to consume it in order to set the items in your dictionary.

You should rather do this with a for loop in this case:

```<code>people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
for key, value in zip(*people):
    p_dict[key] = value
# Now p_dict is {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1}
</code>```

or with a simple dict constructor: dict(zip(*people)).

ContentLicense: CC BY-SA 2.5

Title: operator.setitem problem in python 3

Body:
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

Body:
In Python 3, the result of map is lazy which can give you headache when debugging stuff that worked flawlessly in older versions of Python. In other words, it is a generator, so you have to consume it in order to set the items in your dictionary.

You should rather do this with a for loop in this case:

people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
for key, value in zip(*people):
    p_dict[key] = value
# Now p_dict is {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1}

or with a simple dict constructor: dict(zip(*people)).


问:
Instantiate a class collection member with unique_ptr
I have a Snake class which is composed of several SnakeCell

```<code>struct SnakeCell
{
    SnakeCell(size_t x, size_t y) : origin_(x, y) {}

    std::pair<size_t, size_t> origin_;

};

class Snake
{
public:
    Snake(size_t x, size_t y ) : cells_({std::make_unique<SnakeCell>(x, y)}) {}

private:
    std::deque<std::unique_ptr<SnakeCell>> cells_;

};
</code>```

A Snake is initially created with one SnakeCell.

Why using a pointer for snake cells?
Cells will often be modified, e.g. their x and y components. It make sense to modify them directly when it happens rather than creating a copy and reinitialising the entire cells_ deque.

Why using a unique_ptr
That's where I am not sure if it's the right kind of pointer to use. The original idea was to make sure that every cells are deleted from a memory perspective when the snake itself is deleted. From a design perspective, a Snake object would be the only one that manages its cells so it makes sense to use a unique_ptr rather than a shared_ptr but I think this is where my understanding of smart pointers is incorrect.

Anyway, the compiler complains when using unique_ptr

Call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<SnakeCell, std::__1::default_delete<SnakeCell> >'

Thanks for your help,

答:
The following code

```<code>cells_({std::make_unique<SnakeCell>(x, y)})
</code>```

invokes this constructor

```<code>deque( std::initializer_list<T> init,
       const Allocator& alloc = Allocator() );
</code>```

from cppreference

std::initializer_list<T> is a const T[] under the hood. const object cannot be moved - explaining the error you're getting.

Possible fix:

```<code>Snake(size_t x, size_t y)
{
    cells_.emplace_back(std::make_unique<SnakeCell>(x, y));
}
</code>```

I hate initializer_list...

Body:
I have a Snake class which is composed of several SnakeCell

struct SnakeCell
{
    SnakeCell(size_t x, size_t y) : origin_(x, y) {}

    std::pair<size_t, size_t> origin_;

};

class Snake
{
public:
    Snake(size_t x, size_t y ) : cells_({std::make_unique<SnakeCell>(x, y)}) {}

private:
    std::deque<std::unique_ptr<SnakeCell>> cells_;

};

A Snake is initially created with one SnakeCell.

Why using a pointer for snake cells?
Cells will often be modified, e.g. their x and y components. It make sense to modify them directly when it happens rather than creating a copy and reinitialising the entire cells_ deque.

Why using a unique_ptr
That's where I am not sure if it's the right kind of pointer to use. The original idea was to make sure that every cells are deleted from a memory perspective when the snake itself is deleted. From a design perspective, a Snake object would be the only one that manages its cells so it makes sense to use a unique_ptr rather than a shared_ptr but I think this is where my understanding of smart pointers is incorrect.

Anyway, the compiler complains when using unique_ptr

Call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<SnakeCell, std::__1::default_delete<SnakeCell> >'

Thanks for your help,

Body:
The following code

cells_({std::make_unique<SnakeCell>(x, y)})

invokes this constructor

deque( std::initializer_list<T> init,
       const Allocator& alloc = Allocator() );

from cppreference

std::initializer_list<T> is a const T[] under the hood. const object cannot be moved - explaining the error you're getting.

Possible fix:

Snake(size_t x, size_t y)
{
    cells_.emplace_back(std::make_unique<SnakeCell>(x, y));
}

I hate initializer_list...


问:
Formatting a PHP multi line string
I have been trying to create a contact form auto-responder with a select list, one of the main sources I used is this

The only change I did to his code is obviously the variables and changed

```<code>add_action( 'wpcf7_mail_sent', 'contact_form_autoresponders' );
</code>```

to

```<code>add_action( 'wpcf7_mail_sent', array($this, 'contact_form_autoresponders' ), 5);
</code>```

I have been trying to create an automated email responder for any options out of the selected 'select' menu.

I have been importing another file.php which contains all the string variables I need with "<<

all the variables in file.php looks like this:

```<code>$some_variable =<<<EOT multiple
                    lines
                     here
 EOT;
</code>```

Since My email responses are in Hebrew I want the responded mail to be sent right to left and I am looking all over the place for a way to align my string to the right and add some URL marks and can't find it.

I tried adding this to the Headers and String head and it didn't work out for me

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"
direction="rtl">
</code>```

Any help would be appreciated.

答:
If I understand you correctly, if your file.php included an array of posted object properties (i.e. $this->option1, $this->option2) then the code, based on the link you gave, would look something like:

```<code>#our autoresponders function
function contact_form_autoresponders( $contact_form ) {

    if( $contact_form->id==1234 ){ #your contact form ID - you can find this in contact form 7 settings

        #retrieve the details of the form/post
        $submission = WPCF7_Submission::get_instance();
        $posted_data = $submission->get_posted_data();

        $msg = array();
        #set autoresponders based on dropdown choice, in an array
        switch( $this->posteddata){ #your dropdown menu field name
            case 'California':
            $msg+="California email body goes here";
            break;

            case 'Texas':
            $msg+="Texas email body goes here";
            break;

        }
        $msg_str = implode("", $msg);

        #mail it to them
        mail( $posted_data['your-email'], 'Thanks for your enquiry', $msg_str );
    }

}
</code>```

Note the $msg = array(); as a string array, the $msg += "<multiline string>" for each case that matches a posted query variable, and the $msg_str = implode("", $msg) to make a final string (that may be HTML or non-html).

If you are using a HTML email, aligning the options' values right is a matter of css rules. So your final HTML email would look like:

```<code><html>
<head>
    <style>
        .align-right
        {
            text-align: right;
            direction: rtl;
        }
    </style>
</head>
<body>
...
...
...
<table>
    <tbody>
        <tr>
        <td class="option-name">California</td>
        <td class="option-value align-right">THE MULTILINE STRING</td>
        </tr>
        <tr>
        <td class="option-name">Texas</td>
        <td class="option-value align-right">THE MULTILINE STRING</td>
        </tr>
    </tbody>
</table>
</html>
</code>```

Title: Formatting a PHP multi line string

Body:
I have been trying to create a contact form auto-responder with a select list, one of the main sources I used is this

The only change I did to his code is obviously the variables and changed

add_action( 'wpcf7_mail_sent', 'contact_form_autoresponders' );

to

add_action( 'wpcf7_mail_sent', array($this, 'contact_form_autoresponders' ), 5);

I have been trying to create an automated email responder for any options out of the selected 'select' menu.

I have been importing another file.php which contains all the string variables I need with "<<

all the variables in file.php looks like this:

$some_variable =<<<EOT multiple
                    lines
                     here
 EOT;

Since My email responses are in Hebrew I want the responded mail to be sent right to left and I am looking all over the place for a way to align my string to the right and add some URL marks and can't find it.

I tried adding this to the Headers and String head and it didn't work out for me

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Any help would be appreciated.

Body:
If I understand you correctly, if your file.php included an array of posted object properties (i.e. $this->option1, $this->option2) then the code, based on the link you gave, would look something like:

#our autoresponders function
function contact_form_autoresponders( $contact_form ) {

    if( $contact_form->id==1234 ){ #your contact form ID - you can find this in contact form 7 settings

        #retrieve the details of the form/post
        $submission = WPCF7_Submission::get_instance();
        $posted_data = $submission->get_posted_data();

        $msg = array();
        #set autoresponders based on dropdown choice, in an array
        switch( $this->posteddata){ #your dropdown menu field name
            case 'California':
            $msg+="California email body goes here";
            break;

            case 'Texas':
            $msg+="Texas email body goes here";
            break;

        }
        $msg_str = implode("", $msg);

        #mail it to them
        mail( $posted_data['your-email'], 'Thanks for your enquiry', $msg_str );
    }

}

Note the $msg = array(); as a string array, the $msg += "<multiline string>" for each case that matches a posted query variable, and the $msg_str = implode("", $msg) to make a final string (that may be HTML or non-html).

If you are using a HTML email, aligning the options' values right is a matter of css rules. So your final HTML email would look like:

<html>
<head>
    <style>
        .align-right
        {
            text-align: right;
            direction: rtl;
        }
    </style>
</head>
<body>
...
...
...
<table>
    <tbody>
        <tr>
        <td class="option-name">California</td>
        <td class="option-value align-right">THE MULTILINE STRING</td>
        </tr>
        <tr>
        <td class="option-name">Texas</td>
        <td class="option-value align-right">THE MULTILINE STRING</td>
        </tr>
    </tbody>
</table>
</html>


问:
Spring MVC. Tomcat. HTTP Status 404 – Not Found
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

```<code>@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}
</code>```

My WebInitializer

```<code>public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}
</code>```

My controller

```<code>@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("<br>");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("<br>"));
    model.put("msg", sb.toString());
    return "index";
}
}
</code>```

My index.jsp

```<code>    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>
</head>
<body>
    <h4>Spring MVC</h4>
    <span class="blue">${msg}</span>
</body>
</html>
</code>```

My pom.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>
</code>```

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance

答: You should specify value in @RequestMapping.

Body:
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}

My WebInitializer

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}

My controller

@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("
");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("
"));
    model.put("msg", sb.toString());
    return "index";
}
}

My index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>

Spring MVC

    ${msg}

My pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance


问:
Delete Query Inside While Loop
i'm trying to delete database record inside a while loop. I'm showing my user list in a table with while loop. I have a button, bootstrap modal opening a modal window. In that window i have submit to delete button. With while loop.
Problem is, i'm trying to delete this record, but its deleting random record. can you check is there a problem?

Thanks already.
here is my code:

```<code><table class="table table-hover">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Surname</th>
        <th>Email</th>
        <th>Password</th>
        <th>*</th>
      </tr>
    </thead>
    <tbody>

<?php

    $q = "SELECT * FROM users";
    $r = mysqli_query($dbc,$q);
    while($list = mysqli_fetch_assoc($r)){
        if(isset($_POST['del_submit'])){
            $q = "DELETE FROM users WHERE id = '$list[id]' ";
            $r = mysqli_query($dbc, $q);
                 header('Location: index.php?page=7');
            }

        echo '<tr>';
        echo '<td>'.$list['id'].'</td>';
        echo '<td>'.$list['name'].'</td>';
        echo '<td>'.$list['surname'].'</td>';
        echo '<td>'.$list['email'].'</td>';
        echo '<td>'.$list['password'].'</td>';
        echo '<td><button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> ';

        echo '</tr><form method="post" action="#">';
        echo '<div class="modal fade delete'.$list['id'].'">
              <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">Delete <strong class="text-primary">'.$list['name'].' ?</strong></h4>
                    </div>

                    <div class="modal-body">
                    <strong class="text-primary">'.$list['name'].' '.$list['surname'].'</strong><br>
                    Are you Sure?
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
                    </div>
                </div>
              </div>
            </div></form>';

    }
?>

    </tbody>
</table>
</code>```

答:
i will first acknowledge that your script is not safe and efficient this way. Why not handle delete operations with Ajax and call to a different script?

You have to pass the value of the id with the delete button and then use the id value you passed with the button instead.

For your delete button inside the modal add value attribute

```<code><button type="submit" name="del_submit" value="'.$list['id'].'" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
</code>```

Then retrieve the id and use the id. Its should work

```<code>if(isset($_POST['del_submit'])){
    $listItemID = $_POST['del_submit'];
    $q = "DELETE FROM users WHERE id = '$listItemID' ";
    $r = mysqli_query($dbc, $q);
        header('Location: index.php?page=7');
}
</code>```

If where you are redirecting the user is with the id of the deleted element simply use

`header('Location: index.php?page=$listItemID'); instead of header('Location: index.php?page=7');

Full code becomes

```<code><table class="table table-hover">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Surname</th>
            <th>Email</th>
            <th>Password</th>
            <th>*</th>
        </tr>
    </thead>
    <tbody>

        <?php

        $q = "SELECT * FROM users";
        $r = mysqli_query($dbc,$q);
        while($list = mysqli_fetch_assoc($r)){
            if(isset($_POST['del_submit'])){
                $listItemID = $_POST['del_submit'];
                $q = "DELETE FROM users WHERE id = '$listItemID' ";
                $r = mysqli_query($dbc, $q);
                header('Location: index.php?page=7');
            }

            echo '<tr>';
            echo '<td>'.$list['id'].'</td>';
            echo '<td>'.$list['name'].'</td>';
            echo '<td>'.$list['surname'].'</td>';
            echo '<td>'.$list['email'].'</td>';
            echo '<td>'.$list['password'].'</td>';
            echo '<td><button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> ';

            echo '</tr><form method="post" action="#">';
            echo '<div class="modal fade delete'.$list['id'].'">
              <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">Delete <strong class="text-primary">'.$list['name'].' ?</strong></h4>
                    </div>

                    <div class="modal-body">
                    <strong class="text-primary">'.$list['name'].' '.$list['surname'].'</strong><br>
                    Are you Sure?
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" value="'.$list['id'].'" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
                    </div>
                </div>
              </div>
            </div></form>';

        }
        ?>

    </tbody>
</table>
</code>```

Title: Delete Query Inside While Loop

Body:
i'm trying to delete database record inside a while loop. I'm showing my user list in a table with while loop. I have a button, bootstrap modal opening a modal window. In that window i have submit to delete button. With while loop.
Problem is, i'm trying to delete this record, but its deleting random record. can you check is there a problem?

Thanks already.
here is my code:

        Id
        Name
        Surname
        Email
        Password
        *

<?php

    $q = "SELECT * FROM users";
    $r = mysqli_query($dbc,$q);
    while($list = mysqli_fetch_assoc($r)){
        if(isset($_POST['del_submit'])){
            $q = "DELETE FROM users WHERE id = '$list[id]' ";
            $r = mysqli_query($dbc, $q);
                 header('Location: index.php?page=7');
            }

        echo '
';
        echo ''.$list['id'].'	';
        echo ''.$list['name'].'	';
        echo ''.$list['surname'].'	';
        echo ''.$list['email'].'	';
        echo ''.$list['password'].'	';
        echo '<button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"></button> ';

        echo '
<form method="post" action="#">';
        echo '

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete '.$list['name'].' ?

                    '.$list['name'].' '.$list['surname'].'

                    Are you Sure?

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" id="del_submit" class="btn btn-danger"> Delete</button>

</form>';

    }
?>

Body:
i will first acknowledge that your script is not safe and efficient this way. Why not handle delete operations with Ajax and call to a different script?

You have to pass the value of the id with the delete button and then use the id value you passed with the button instead.

For your delete button inside the modal add value attribute

<button type="submit" name="del_submit" value="'.$list['id'].'" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>

Then retrieve the id and use the id. Its should work

if(isset($_POST['del_submit'])){
    $listItemID = $_POST['del_submit'];
    $q = "DELETE FROM users WHERE id = '$listItemID' ";
    $r = mysqli_query($dbc, $q);
        header('Location: index.php?page=7');
}

If where you are redirecting the user is with the id of the deleted element simply use

`header('Location: index.php?page=$listItemID'); instead of header('Location: index.php?page=7');

Full code becomes

<table class="table table-hover">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Surname</th>
            <th>Email</th>
            <th>Password</th>
            <th>*</th>
        </tr>
    </thead>
    <tbody>

        <?php

        $q = "SELECT * FROM users";
        $r = mysqli_query($dbc,$q);
        while($list = mysqli_fetch_assoc($r)){
            if(isset($_POST['del_submit'])){
                $listItemID = $_POST['del_submit'];
                $q = "DELETE FROM users WHERE id = '$listItemID' ";
                $r = mysqli_query($dbc, $q);
                header('Location: index.php?page=7');
            }

            echo '<tr>';
            echo '<td>'.$list['id'].'</td>';
            echo '<td>'.$list['name'].'</td>';
            echo '<td>'.$list['surname'].'</td>';
            echo '<td>'.$list['email'].'</td>';
            echo '<td>'.$list['password'].'</td>';
            echo '<td><button class="btn btn-danger btn-xs" data-toggle="modal" data-target=".delete'.$list['id'].'"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> ';

            echo '</tr><form method="post" action="#">';
            echo '<div class="modal fade delete'.$list['id'].'">
              <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Delete <strong class="text-primary">'.$list['name'].' ?</strong></h4>
                    </div>

                    <div class="modal-body">
                    <strong class="text-primary">'.$list['name'].' '.$list['surname'].'</strong><br>
                    Are you Sure?
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                    <button type="submit" name="del_submit" value="'.$list['id'].'" id="del_submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>
                    </div>
                </div>
              </div>
            </div></form>';

        }
        ?>

    </tbody>
</table>


问:
Get notification when file added to File Share
Is there a way to get notified when a new file is added/modified to Azure File Share?

Similar feature exists with AWS S3 where one can configure an S3 bucket to send message to SQS or SNS or Lambda (or other) when a new File is added.

An alternative (though less preferred) is to be able to query files in a share such that only modified/new files after date X will be returned.

答:
For getting notifications on addition/modification of blobs (not files), you have multiple options available:

Azure Functions (w/ Blob Storage Binding): In this scenario, a function will get invoked when a blob is added or updated. More details about this can be found here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob.

Azure Event Grid (w/ Blob Integration): Currently (at the time of providing this answer), this service is in preview and has limited availability in terms of regions. Currently it only supports Blob Creation (and not blob updation) event. More information about this can be found here: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-event-overview.


问:
How to solve Not Found (HTTP 404) in textaDetectTopics from mscstexta4r in R?
I'm trying mscstexta4r in R and it is working when I use textaSentiment command but, when I try textaDetectTopics it returns:

```<code>[1] "mscstexta4r: Not Found (HTTP 404). - { \"statusCode\": 404, \"message\": \"Resource not found\" }"
</code>```

My .mscskeys.json file configuration is:

```<code>{
"textanalyticsurl": "https://westus.api.cognitive.microsoft.com/texta/analytics/v2.0/",
"textanalyticskey": "--my API key--"
}
</code>```

Any help is appreciated!

答: Topic detection has been deprecated from the Text Analytics API for several months now.  That's why you are getting the 404.</p>

Body:
I'm trying mscstexta4r in R and it is working when I use textaSentiment command but, when I try textaDetectTopics it returns:

[1] "mscstexta4r: Not Found (HTTP 404). - { \"statusCode\": 404, \"message\": \"Resource not found\" }"

My .mscskeys.json file configuration is:

{
"textanalyticsurl": "https://westus.api.cognitive.microsoft.com/texta/analytics/v2.0/",
"textanalyticskey": "--my API key--"
}

Any help is appreciated!


问:
Slide show images it just working one time on next button
I have a slide show consistent of tags and each tag is made up of

collection of images, and I have two buttons (next previous),
I want when I click on next button show first a set of images showing
all in a row and when I click on previous button show
the set of previous images after click next button.

its working fine for one time in only next button but when click
prev did not working and not show the set of  previous images.

```
</div>
</div>
</p>
```

❯
❮

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

```

答:
Change inner html dynamically will not work.
We will implement $ReloadSlides and $AppendSlides api to load new slides dynamically later.

For you case at the moment, I think you can create a new slider and hide previous slider when mouse click.

Note that before you show another slider, you can $Pause and hide the element of the previous slider.

ContentLicense: CC BY-SA 4.0

Body:
I have a slide show consistent of tags and each tag is made up of

collection of images, and I have two buttons (next previous),
I want when I click on next button show first a set of images showing
all in a row and when I click on previous button show
the set of previous images after click next button.

its working fine for one time in only next button but when click
prev did not working and not show the set of  previous images.

❯
❮

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description

                Title

                Slide Description


问:
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

It mentions the following sentence:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Is "constant variables" a correct term to use? Aren't constants different from variables?

Thanks.

答:
It is a variable in the sense that it is an addressable object, as opposed to a literal constant which is not addressable.

It is perhaps contradictory, but the language standard uses the term variable to refer to addressable objects in general, and const to specify a read-only addressable object.


问:
Route to URL helper default parameters
I am using the code found here https://laracasts.com/discuss/channels/laravel/how-to-prefixing-in-routes-for-localization to prefix my routes with a locale.

```<code>Route::prefix('{lang?}')->middleware('locale')->group(function() {

    Route::get('/', function () {
        return view('index');
    })->name('index');
});
</code>```

This locale is optional, but then my question is how am I supposed to reinject the locale when calling the route helper.

```<code>route('index');
</code>```

to generate: /it/ or /, or another, depending on the current locale.

If have tried this with no success :

```<code>Route::resourceParameters(['lang' => 'en']);
</code>```

答:
Actually, I'm a bit unsure about what the question is. I took it as a way to generate URL without setting its dynamic parameters using route helper based on @rahulsm's answer.

So, I just figured out that you can set default parameters to UrlGenerator class. By listening on container url and request rebind event, it's possible to set default parameters there.

Inside AppServiceProvider boot

```<code>$this->app->rebinding('url', function ($url, $app) {
    $url->defaults(['lang' => $app->getLocale()]);
});
$this->app->rebinding('request', function ($app) {
    $app['url']->defaults(['lang' => $app->getLocale()]);
});
</code>```

And then tried to call it,

```<code>route('index') // http://test.dev/en (based on config)
route('index', ['lang' => 'what']) //http://test.dev/what
</code>```

This was tested only on Laravel 5.5, but I'm sure would also working on Laravel 5.4.

To explain a bit more about rebinding method available Laravel container[1], firstly it's good to know how is Laravel request lifecycle works. In a one line simplified words, it should be the same as how an application in general works, which is: receive a request, do the logic, return a response.

At the second part, appear stage commonly said as bootstrapping, which one of its logic is try to store (register) classes (services) that mostly are important for the application[2] to work. Into a container. Thus, intended to be shared or even just for easily to be called, whether for the high-end developers or the framework itself.

Once registered, it will then be booted. This booting process has several actions to call[3]. One of it that suit this case is firing (local) events. Once a service has been resolved, it will try to call all registered rebound functions (listeners) at this stage. I can only assume this purpose is to make the application can be "easily mutate" the currently-resolving instance (service). Thus, defining rebinding method to listen to recalled event is the way to go.

Since Laravel allows to re-resolve (re-instantiate) a service, which means our previous stored value in the class is lost[4], waiting it to be resolved (which then the listener called) is much make sense, right?

Back to rebinding snippet above, I used to listen to both url and request rebound services because url is request's dependent. It waits for request service to be fully resolved and then call setRequest[5] method which flushes the needed instance which is Illuminate\Routing\RouteUrlGenerator that holds default parameter.

And as the name implies, defaults, used to set the default named parameters used by the URL generator[6].

cit

[1] Container here refer to both Illuminate\Foundation\Application also Illuminate\Container\Container

[2] configure error handling, configure logging, detect the application environment

[3] resolving type-hinted dependencies, storing/caching stuffs to buffer, etc

[4] Unless retained like stored in class' static property

[5] Illuminate\Routing\UrlGenerator@setRequest

[6] Illuminate\Routing\UrlGenerator, either calling URL::route('route.name'), url('your-url'), app('url')->route('route.name'), or route('route.name'), they refer to the same class

Title: Route to URL helper default parameters

Body:
I am using the code found here https://laracasts.com/discuss/channels/laravel/how-to-prefixing-in-routes-for-localization to prefix my routes with a locale.

Route::prefix('{lang?}')->middleware('locale')->group(function() {

    Route::get('/', function () {
        return view('index');
    })->name('index');
});

This locale is optional, but then my question is how am I supposed to reinject the locale when calling the route helper.

route('index');

to generate: /it/ or /, or another, depending on the current locale.

If have tried this with no success :

Route::resourceParameters(['lang' => 'en']);

Body:
Actually, I'm a bit unsure about what the question is. I took it as a way to generate URL without setting its dynamic parameters using route helper based on @rahulsm's answer.

So, I just figured out that you can set default parameters to UrlGenerator class. By listening on container url and request rebind event, it's possible to set default parameters there.

Inside AppServiceProvider boot

$this->app->rebinding('url', function ($url, $app) {
    $url->defaults(['lang' => $app->getLocale()]);
});
$this->app->rebinding('request', function ($app) {
    $app['url']->defaults(['lang' => $app->getLocale()]);
});

And then tried to call it,

route('index') // http://test.dev/en (based on config)
route('index', ['lang' => 'what']) //http://test.dev/what

This was tested only on Laravel 5.5, but I'm sure would also working on Laravel 5.4.

To explain a bit more about rebinding method available Laravel container[1], firstly it's good to know how is Laravel request lifecycle works. In a one line simplified words, it should be the same as how an application in general works, which is: receive a request, do the logic, return a response.

At the second part, appear stage commonly said as bootstrapping, which one of its logic is try to store (register) classes (services) that mostly are important for the application[2] to work. Into a container. Thus, intended to be shared or even just for easily to be called, whether for the high-end developers or the framework itself.

Once registered, it will then be booted. This booting process has several actions to call[3]. One of it that suit this case is firing (local) events. Once a service has been resolved, it will try to call all registered rebound functions (listeners) at this stage. I can only assume this purpose is to make the application can be "easily mutate" the currently-resolving instance (service). Thus, defining rebinding method to listen to recalled event is the way to go.

Since Laravel allows to re-resolve (re-instantiate) a service, which means our previous stored value in the class is lost[4], waiting it to be resolved (which then the listener called) is much make sense, right?

Back to rebinding snippet above, I used to listen to both url and request rebound services because url is request's dependent. It waits for request service to be fully resolved and then call setRequest[5] method which flushes the needed instance which is Illuminate\Routing\RouteUrlGenerator that holds default parameter.

And as the name implies, defaults, used to set the default named parameters used by the URL generator[6].

cit

[1] Container here refer to both Illuminate\Foundation\Application also Illuminate\Container\Container

[2] configure error handling, configure logging, detect the application environment

[3] resolving type-hinted dependencies, storing/caching stuffs to buffer, etc

[4] Unless retained like stored in class' static property

[5] Illuminate\Routing\UrlGenerator@setRequest

[6] Illuminate\Routing\UrlGenerator, either calling URL::route('route.name'), url('your-url'), app('url')->route('route.name'), or route('route.name'), they refer to the same class


问:
Cross-Platform iOS/Mac OS X Objective-C development?
I'll be starting  medium-sized iOS project soon, a document-centric app.

Later, the software might get ported to Mac OS X. Of course, the whole UI will need to change; that's not what I'm asking.

Is it possible to write the core logic in such a way that it's cross-platform (Mac/iOS only), or more easily ported? Has anybody done this before, or is the usual way to just write different code for both platforms?

I'm thankful for any tips regarding this, be they about Code, Frameworks, Version Control - anything. I'd hate to realize I've painted myself into a corner only after the fact, so I want to start as well as possible.

答: you could just write in C, then port it to ios, osx, java, android, ...</p>


问:
Is it possible to run kotlin grade plugin using jdk 7
My project uses jdk 7 for compatibility reasons.

bottom portion of build.gradle

```<code>buildscript {
    ext.kotlin_version = '1.2.0'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
</code>```

When I use jdk 7 for gradle, I get this:

```<code>java.lang.UnsupportedClassVersionError: org/jetbrains/kotlin/gradle/KotlinGradleModel : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.gradle.tooling.internal.provider.serialization.DefaultPayloadClassLoaderRegistry$2.resolveClass(DefaultPayloadClassLoaderRegistry.java:91)
    at org.gradle.tooling.internal.provider.serialization.WellKnownClassLoaderRegistry$2.resolveClass(WellKnownClassLoaderRegistry.java:91)
    at org.gradle.tooling.internal.provider.serialization.PayloadSerializerObjectInputStream.readClass(PayloadSerializerObjectInputStream.java:66)
  ... cut
</code>```

If I switch to jdk 8 for running grade while project jdk is still jdk7, the build succeed. Is this expected behaviour?

答:
After hours of research, I finally found this post:

https://blog.jetbrains.com/kotlin/2017/04/kotlin-1-1-2-is-out/

The Kotlin compiler now requires JDK 8 to run. You shouldn’t notice
  any changes, because most other Java development tools such as Gradle
  and the Android toolchain also require JDK 8, so you almost certainly
  already have it installed. For code generated by the compiler, Java
  1.6 compatibility is still the default, and we have no plans to drop support for generating Java 1.6 compatible bytecode.

So, the answer is no.

Body:
My project uses jdk 7 for compatibility reasons.

bottom portion of build.gradle

buildscript {
    ext.kotlin_version = '1.2.0'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

When I use jdk 7 for gradle, I get this:

java.lang.UnsupportedClassVersionError: org/jetbrains/kotlin/gradle/KotlinGradleModel : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.gradle.tooling.internal.provider.serialization.DefaultPayloadClassLoaderRegistry$2.resolveClass(DefaultPayloadClassLoaderRegistry.java:91)
    at org.gradle.tooling.internal.provider.serialization.WellKnownClassLoaderRegistry$2.resolveClass(WellKnownClassLoaderRegistry.java:91)
    at org.gradle.tooling.internal.provider.serialization.PayloadSerializerObjectInputStream.readClass(PayloadSerializerObjectInputStream.java:66)
  ... cut

If I switch to jdk 8 for running grade while project jdk is still jdk7, the build succeed. Is this expected behaviour?


问:
How to remove an object from an array in Immutable?
Given a state like this:

```<code>state = {
  things: [
    { id: 'a1', name: 'thing 1' },
    { id: 'a2', name: 'thing 2' },
  ],
};
</code>```

How can I create a new state where ID "a1" is removed? It's easy enough to push new items:

```<code>return state.set(state.get('things').push(newThing));
</code>```

But I can't figure out how to search for and remove an object by its id property. I tried this:

```<code>return state.set('tracks',
  state.get('tracks').delete(
    state.get('tracks').findIndex(x => x.get('id') === 'a2')
  )
)
</code>```

But it seems messy, plus it only works if the item is found, because if findIndex returns -1, that's a valid value for delete.

答:
Found this thread while looking for a solution to a similar task.
Solved it with update method:

```<code>return state.update('things', (things) => things.filter((t) => t.id !== action.things.id))
</code>```

any idea/comment which one is better/preferred?

Body:
Given a state like this:

state = {
  things: [
    { id: 'a1', name: 'thing 1' },
    { id: 'a2', name: 'thing 2' },
  ],
};

How can I create a new state where ID "a1" is removed? It's easy enough to push new items:

return state.set(state.get('things').push(newThing));

But I can't figure out how to search for and remove an object by its id property. I tried this:

return state.set('tracks',
  state.get('tracks').delete(
    state.get('tracks').findIndex(x => x.get('id') === 'a2')
  )
)

But it seems messy, plus it only works if the item is found, because if findIndex returns -1, that's a valid value for delete.

Body:
Found this thread while looking for a solution to a similar task.
Solved it with update method:

return state.update('things', (things) => things.filter((t) => t.id !== action.things.id))

any idea/comment which one is better/preferred?


问:
How to avoid "Assignment to property of function parameter 'elem'" eslint rule?
I want to understand how you guys avoid the eslint warning "Assignment to property of function parameter 'elem'". I know that is a good pattern do not change function parameters values. This keeps our code decoupled and with high maintenance. However, in some cases, I come across with the following situation.
I need to retrieve all elements with a specific class, and then, change its display style property.
This is my code:

```<code>const setDisplayStyleToElementsArray = (arr, display) => {
  arr.map((elem) => {
    elem.style.display = display;
    return elem;
  });
};

const elements = document.getElementsByClassName('.myClass');

const myFields = [].slice.call(elements, 0);

setDisplayStyleToElementsArray(myFields, 'block');
</code>```

In this case, I'm changing the property "block" of all my .myClass elements. How to do this without side effects? What is the correct way of doing that?
Thanks in advance

答:
I'm changing the property. How to do this without side effects?

You cannot. Changing that DOM property is a side effect. If your linter prevents you from doing that, disable it (on that line at least).

Of course, this specific rule can be avoided by simply not using map or a callback function. Much more idiomatic would be

```<code>function setDisplayStyles(arr, display) {
  for (const elem of arr) {
    elem.style.display = display;
  }
}

const elements = Array.from(document.getElementsByClassName('.myClass'));
setDisplayStyles(elements, 'block');
</code>```

Body:
I want to understand how you guys avoid the eslint warning "Assignment to property of function parameter 'elem'". I know that is a good pattern do not change function parameters values. This keeps our code decoupled and with high maintenance. However, in some cases, I come across with the following situation.
I need to retrieve all elements with a specific class, and then, change its display style property.
This is my code:

const setDisplayStyleToElementsArray = (arr, display) => {
  arr.map((elem) => {
    elem.style.display = display;
    return elem;
  });
};

const elements = document.getElementsByClassName('.myClass');

const myFields = [].slice.call(elements, 0);

setDisplayStyleToElementsArray(myFields, 'block');

In this case, I'm changing the property "block" of all my .myClass elements. How to do this without side effects? What is the correct way of doing that?
Thanks in advance

Body:
I'm changing the property. How to do this without side effects?

You cannot. Changing that DOM property is a side effect. If your linter prevents you from doing that, disable it (on that line at least).

Of course, this specific rule can be avoided by simply not using map or a callback function. Much more idiomatic would be

function setDisplayStyles(arr, display) {
  for (const elem of arr) {
    elem.style.display = display;
  }
}

const elements = Array.from(document.getElementsByClassName('.myClass'));
setDisplayStyles(elements, 'block');


问:
Sort a vector with another vector using lambda function
In the code below, I get segmentation fault. I think the problem is with indexing but I don't understand why. Is it possible to use std::sort and lambda function to sort a vector based on another vector?

```<code>#include<iostream>
#include<algorithm>
#include<vector>
#include<string>

int main()
{
    std::vector<std::string> A = {"b", "a", "c"};
    std::vector<int> B = {2, 1, 3};

    std::sort(std::begin(A), std::end(A),
            [&](const std::string& t1, const std::string& t2)
            {
            return B[&t1-A.data()] > B[&t2-A.data()]; // problem could be here!
            });

    std::cout << A[0] << std::endl;
    std::cout << A[1] << std::endl;
    std::cout << A[2] << std::endl;

    return 0;
}
</code>```

答:
Rather than doing your way to get the index a simple way to do it.

```<code>std::sort(std::begin(A), std::end(A),
        [&](const std::string& t1, const std::string& t2)
        {
          int index1, index2;
          for(int i = 0; i<A.size(); i++) {
            if(&A[i] == &t1) index1 = i;
            if(&A[i] == &t2) index2 = i;
          }
        return B[index1] > B[index2];
        });
</code>```

This way is safe and ensures that it gets the right index. After testing it the output is C \n B \n A which is what I think you want.

Hope this helps.

Body:
In the code below, I get segmentation fault. I think the problem is with indexing but I don't understand why. Is it possible to use std::sort and lambda function to sort a vector based on another vector?

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>

int main()
{
    std::vector<std::string> A = {"b", "a", "c"};
    std::vector<int> B = {2, 1, 3};

    std::sort(std::begin(A), std::end(A),
            [&](const std::string& t1, const std::string& t2)
            {
            return B[&t1-A.data()] > B[&t2-A.data()]; // problem could be here!
            });

    std::cout << A[0] << std::endl;
    std::cout << A[1] << std::endl;
    std::cout << A[2] << std::endl;

    return 0;
}

Body:
Rather than doing your way to get the index a simple way to do it.

std::sort(std::begin(A), std::end(A),
        [&](const std::string& t1, const std::string& t2)
        {
          int index1, index2;
          for(int i = 0; i<A.size(); i++) {
            if(&A[i] == &t1) index1 = i;
            if(&A[i] == &t2) index2 = i;
          }
        return B[index1] > B[index2];
        });

This way is safe and ensures that it gets the right index. After testing it the output is C \n B \n A which is what I think you want.

Hope this helps.


问:
How can I stop <foreach> loop in between in mulesoft
I have an array list values which I loop using foreach and choice. As soon as the first success happens in choice I want to come out of the foreach loop. And I don't want continue to check remaining conditions. In mulesoft flow

Thank you in advance.

答:
There is no component to break the foreach loop. If you only want to process till the success condition, then you could use MEL to execute the foreach on a sublist like this:

```<code><foreach collection="#[payload<condition>]" />
 ...
</foreach>
</code>```

You can also use loops in Groovy.

Example. In a payload i have some HashMap -

```<code>def nap = payload.Result
 for (v in nap)
 {
     if (v.Name == '!!! а папка')
     {
         assert v.Id != null
         flowVars['folderid'] = v.Id
         payload = 'recived Id of folder object is '+v.Id
         break
     }

 }
 return payload
</code>```

Body:
There is no component to break the foreach loop. If you only want to process till the success condition, then you could use MEL to execute the foreach on a sublist like this:

<foreach collection="#[payload<condition>]" />
 ...
</foreach>

You can also use loops in Groovy.

Example. In a payload i have some HashMap -

def nap = payload.Result
 for (v in nap)
 {
     if (v.Name == '!!! а папка')
     {
         assert v.Id != null
         flowVars['folderid'] = v.Id
         payload = 'recived Id of folder object is '+v.Id
         break
     }

 }
 return payload


问:
How to set option ngx-mydatepicker get MM/yyyy
I don't known how to set the option ngx-mydatepicker to get MM/yyyy. Please help me.
Thank you.</p>

```<code><input class="form-control" style="float:none" placeholder="mm/yyyy" ngx-mydatepicker name="mydate"
                  model="buyDate" [options]="myDatePickerOptions" #dp="ngx-mydatepicker" [(ngModel)]="date" [ngModelOptions]="{standalone: true}"/>

 private myDatePickerOptions: INgxMyDpOptions = {
    dateFormat: 'dd/mm/yyyy'
 };
</code>```

答:
Looking at the code for formatting Link to code, the module does not allow you to have dates in that format. You will need to a custom formatting. Take a look at Angular2-moment

What is the initial format of your dates?

Body:
I don't known how to set the option ngx-mydatepicker to get MM/yyyy. Please help me.
Thank you.

<input class="form-control" style="float:none" placeholder="mm/yyyy" ngx-mydatepicker name="mydate"
                  model="buyDate" [options]="myDatePickerOptions" #dp="ngx-mydatepicker" [(ngModel)]="date" [ngModelOptions]="{standalone: true}"/>

 private myDatePickerOptions: INgxMyDpOptions = {
    dateFormat: 'dd/mm/yyyy'
 };


问:
simulating Excel networkdays in sql
I am sure somebody has worked out to simulate Excel networkdays function in other programming language.
I'd appreciate if you could share.
Thanks </p>

答: A SQL solution as per SO question "Equivalent of Excel’s NETWORKDAYS function with Jet ADO"</p>

Title: simulating Excel networkdays in sql


问:
SoapUI/Groovy dynamically compare JSON response against array
I am trying to compare node values from a JSON response to values gathered from an excel spreadsheet which I have built an array for. The array contains values from multiple columns but I want to see if a JSON node value is in the array. Eventually I need to compare multiple node values to the array. I can't seem to get this to work for just one at the moment. What am I doing wrong??

```<code>import com.eviware.soapui.*;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
import groovy.lang.*;
import groovy.util.*;
import groovy.json.JsonSlurper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//Create an array to hold the cell values
def cellValues = [];
//Get the JSON in a format to easily access
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
def ResponseMessage = testRunner.testCase.testSteps["ProductSkuLookupService"].getPropertyValue("response");
def jsonResult = new JsonSlurper().parseText(ResponseMessage);

//Get the number of recommended expressions nodes
def rspnsNumRcmndExprsns = jsonResult.product.recommendedExpressions.size();
//Get the file from the location specified in the test case custom properties
def String dataFilename = context.expand( '${#TestCase#dataFilename}' );

if(dataFilename != null && !dataFilename.equals(""))
{
    XSSFWorkbook wb = new XSSFWorkbook(dataFilename);
    XSSFSheet sheet = wb.getSheet("exprsnList");
    XSSFRow row;
    XSSFCell cell;

    def totalNumRows;
    def numRows;
    //Get the total number of rows with data on the sheet
    totalNumRows = sheet.getPhysicalNumberOfRows();
    //log.info " The total number of rows are " + totalNumRows;
    //Get the number of rows without the header row
    numRows = totalNumRows - 1;
    //log.info " The number of rows to use are " + rows;

    def cols = 0;

    cols = sheet.getRow(0).getPhysicalNumberOfCells();
    //log.info " The total number of columns are " + cols;

    if(numRows == rspnsNumRcmndExprsns)
    {
        for(int i = 1; i < totalNumRows; i++)
        {
            row = sheet.getRow(i);
            //log.info " Row # " + i;

            for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell);
            }

        }

        log.info jsonResult.product["recommendedExpressions"]["imageUrl"].every{it in [cellValues]}

    }

    else
    {
        assert false, "The number of nodes does not match the number of rows.";
    }
}
else
{
    assert false, "The file name is missing.";
}

return;
</code>```

Here's a piece of the JSON (there are multiple sub-arrays in the JSON):

```<code>{
   "responseHeader":    {
      "status": "SUCCESS",
      "messages": []
   },
   "product":    {
      "recommendedExpressions":       [
                  {
            "imageUrl": "/images/products/expressions/ex015.jpg",
            "id": "sku83283exp",
            "description": " ",
            "code": "EX015"
         },
                  {
            "imageUrl": "/images/products/expressions/ex100.jpg",
            "id": "sku81486exp",
            "description": " ",
            "code": "EX100"
         },
                  {
            "imageUrl": "/images/products/expressions/ex036.jpg",
            "id": "sku82518exp",
            "description": " ",
            "code": "EX036"
         }
      ]
   }
}
</code>```

答:
You are pushing Cell to the array. I think your requirement is push cell contents to the array.

In place of this :

```<code>for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell);
            }
</code>```

Use below code

```<code>for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell.getStringCellValue());
            }
</code>```

Body:
I am trying to compare node values from a JSON response to values gathered from an excel spreadsheet which I have built an array for. The array contains values from multiple columns but I want to see if a JSON node value is in the array. Eventually I need to compare multiple node values to the array. I can't seem to get this to work for just one at the moment. What am I doing wrong??

import com.eviware.soapui.*;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
import groovy.lang.*;
import groovy.util.*;
import groovy.json.JsonSlurper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//Create an array to hold the cell values
def cellValues = [];
//Get the JSON in a format to easily access
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
def ResponseMessage = testRunner.testCase.testSteps["ProductSkuLookupService"].getPropertyValue("response");
def jsonResult = new JsonSlurper().parseText(ResponseMessage);

//Get the number of recommended expressions nodes
def rspnsNumRcmndExprsns = jsonResult.product.recommendedExpressions.size();
//Get the file from the location specified in the test case custom properties
def String dataFilename = context.expand( '${#TestCase#dataFilename}' );

if(dataFilename != null && !dataFilename.equals(""))
{
    XSSFWorkbook wb = new XSSFWorkbook(dataFilename);
    XSSFSheet sheet = wb.getSheet("exprsnList");
    XSSFRow row;
    XSSFCell cell;

    def totalNumRows;
    def numRows;
    //Get the total number of rows with data on the sheet
    totalNumRows = sheet.getPhysicalNumberOfRows();
    //log.info " The total number of rows are " + totalNumRows;
    //Get the number of rows without the header row
    numRows = totalNumRows - 1;
    //log.info " The number of rows to use are " + rows;

    def cols = 0;

    cols = sheet.getRow(0).getPhysicalNumberOfCells();
    //log.info " The total number of columns are " + cols;

    if(numRows == rspnsNumRcmndExprsns)
    {
        for(int i = 1; i < totalNumRows; i++)
        {
            row = sheet.getRow(i);
            //log.info " Row # " + i;

            for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell);
            }

        }

        log.info jsonResult.product["recommendedExpressions"]["imageUrl"].every{it in [cellValues]}

    }

    else
    {
        assert false, "The number of nodes does not match the number of rows.";
    }
}
else
{
    assert false, "The file name is missing.";
}

return;

Here's a piece of the JSON (there are multiple sub-arrays in the JSON):

{
   "responseHeader":    {
      "status": "SUCCESS",
      "messages": []
   },
   "product":    {
      "recommendedExpressions":       [
                  {
            "imageUrl": "/images/products/expressions/ex015.jpg",
            "id": "sku83283exp",
            "description": " ",
            "code": "EX015"
         },
                  {
            "imageUrl": "/images/products/expressions/ex100.jpg",
            "id": "sku81486exp",
            "description": " ",
            "code": "EX100"
         },
                  {
            "imageUrl": "/images/products/expressions/ex036.jpg",
            "id": "sku82518exp",
            "description": " ",
            "code": "EX036"
         }
      ]
   }
}

Body:
You are pushing Cell to the array. I think your requirement is push cell contents to the array.

In place of this :

for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell);
            }

Use below code

for(int j = 0; j < cols; j++)
            {
                //log.info "  Cell # " + j;
                cell = row.getCell(j);
                //log.info "  The value in the cell is " + cell;

                cellValues.push(cell.getStringCellValue());
            }


问:
Merge k sorted arrays - comparing two solutions
If I have K sorted arrays of N elements each, e.g.

```<code>[0, 1, 2]
[1, 6, 8]
[10, 11, 12]
</code>```

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?

答:
The first answer is O(KN * log(KN))  The second is O(KN * log(K)) and so is better.  It is impossible to in general do better than that.

That said, you can improve on it sometimes in practice.  Instead of dumping the minimum elements into a heap, create a tree of merges like merge-sort does.  Then add logic to, when you seem to be pulling from one side of the merge, try to jump ahead and look for a run.

The win can be significant if K is large, comparisons are expensive, and your data has lots of runs.

See https://en.wikipedia.org/wiki/Timsort for an example of a sorting algorithm which tries something like this, and has been finely tuned for a lot of real world use cases.

Body:
If I have K sorted arrays of N elements each, e.g.

[0, 1, 2]
[1, 6, 8]
[10, 11, 12]

I know that I can use a heap to merge them by cycling all of the lists and their elements and inserting them into the heap, then getting back the minimum each time in O(KN * log(KN)).

I checked on the internet and another popular solution seems to be using a min heap of only K elements and inserting all the first items of the K lists into the heap, then get the minimum out and advance the pointer to the list that owned that minimum element.

Aside from a more efficient memory requirement (O(K) in the second case), is the second method more efficient time-wise?

Optional bonus points: is there an even better algorithm than the ones above?


问:
WCF error: "The X.509 certificate CN=localhost chain building failed ..."
I'm getting this error while attempting to make my WCF client and server talk to each other.

The X.509 certificate CN=localhost chain building failed. The
  certificate that was used has a trust chain that cannot be verified.
  Replace the certificate or change the certificateValidationMode. A
  certificate chain processed, but terminated in a root certificate
  which is not trusted by the trust.

Everything works perfectly if I turn SSL certificates off.

答:
When deactivating the revocationMode helped, then most likely you are missing a client revocation list for your root CA.

```<code>makecert -crl -n "CN=CARoot" -r -sv CARoot.pvk CARoot.crl
</code>```

This also needs to be imported to the trusted root certification authorities. See also my answer here.

Body:
When deactivating the revocationMode helped, then most likely you are missing a client revocation list for your root CA.

makecert -crl -n "CN=CARoot" -r -sv CARoot.pvk CARoot.crl

This also needs to be imported to the trusted root certification authorities. See also my answer here.


问:
Get the order fee item details in Woocommerce 3
I try to get the name of the fee attached to my order in Woocommerce, I get an array but I don't know how to get the name.

I tried with function get_name () but it does not work.

```<code>$the_order->get_items( array( 'line_item', 'fee', 'shipping' ) );
</code>```

Raw data output:

```<code>[137] => WC_Order_Item_Fee Object
        (
            [extra_data:protected] => Array
                (
                    [tax_class] =>
                    [tax_status] => taxable
                    [amount] =>
                    [total] =>
                    [total_tax] =>
                    [taxes] => Array
                        (
                            [total] => Array
                                (
                                )

                        )

                )

            [data:protected] => Array
                (
                    [order_id] => 7795
                    [name] => Frais de réservation
                    [tax_class] => 0
                    [tax_status] => taxable
                    [amount] =>
                    [total] => 35
                    [total_tax] => 0
                    [taxes] => Array
                        (
                            [total] => Array
                                (
                                )

                        )

                )
</code>```

答:
To access and to use properties on Order Fee items you need to use the WC_Order_Item_Fee methods using first a foreach loop this way:

```<code>// (optional if not defined) An instance of the WC_Order object
$the_order = wc_get_order( $order_id );

// Iterating through order fee items ONLY
foreach( $the_order->get_items('fee') as $item_id => $item_fee ){

    // The fee name
    $fee_name = $item_fee->get_name();

    // The fee total amount
    $fee_total = $item_fee->get_total();

    // The fee total tax amount
    $fee_total_tax = $item_fee->get_total_tax();
}
</code>```

Tested and works

Body:
I try to get the name of the fee attached to my order in Woocommerce, I get an array but I don't know how to get the name.

I tried with function get_name () but it does not work.

$the_order->get_items( array( 'line_item', 'fee', 'shipping' ) );

Raw data output:

[137] => WC_Order_Item_Fee Object
        (
            [extra_data:protected] => Array
                (
                    [tax_class] =>
                    [tax_status] => taxable
                    [amount] =>
                    [total] =>
                    [total_tax] =>
                    [taxes] => Array
                        (
                            [total] => Array
                                (
                                )

                        )

                )

            [data:protected] => Array
                (
                    [order_id] => 7795
                    [name] => Frais de réservation
                    [tax_class] => 0
                    [tax_status] => taxable
                    [amount] =>
                    [total] => 35
                    [total_tax] => 0
                    [taxes] => Array
                        (
                            [total] => Array
                                (
                                )

                        )

                )

Body:
To access and to use properties on Order Fee items you need to use the WC_Order_Item_Fee methods using first a foreach loop this way:

// (optional if not defined) An instance of the WC_Order object
$the_order = wc_get_order( $order_id );

// Iterating through order fee items ONLY
foreach( $the_order->get_items('fee') as $item_id => $item_fee ){

    // The fee name
    $fee_name = $item_fee->get_name();

    // The fee total amount
    $fee_total = $item_fee->get_total();

    // The fee total tax amount
    $fee_total_tax = $item_fee->get_total_tax();
}

Tested and works


问:
How to calculate what the sum of these Strings is?
```<code>import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")
</code>```

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?

答:
You can also use stack like functionality in Python to create your own calculator. Below is a simple example of a calculator which calculates:

sum,

difference,

multiplication

exponentiation

division

It can calculate expressions like these ones:

```<code>"1 - 2 * 3 + 4 * 2 - 1 - 2"
"8 / 2 + 1 / 2 * 2 / 2 - 1"
</code>```

Spaces are used to separate the tokens in this simple implementation. More tests are available below in the source code:

```<code>def calc(str):
    tokens = str.split(" ")
    vals = []
    ops = []
    i = 0
    while i < len(tokens):
        t = tokens[i]
        if t == "+":
            processPlus(ops, vals)
        elif t == "*":
            ops.append(t)
        elif t == "-":
            processPlus(ops, vals)
            i, t = incrementAndGet(i, t, tokens)
            vals.append(float(t) * -1)
        elif t == "^":
            previousVal = vals.pop()
            i, t = incrementAndGet(i, t, tokens)
            vals.append(pow(previousVal, float(t)))
        elif t == "/":
            previousVal = vals.pop()
            i, t = incrementAndGet(i, t, tokens)
            vals.append(previousVal / float(t))
        else:
            vals.append(float(t))
        i += 1
    while len(ops) > 0:
        processOp(vals, ops)
    return sum(vals)

def incrementAndGet(i, t, tokens):
    i += 1
    t = tokens[i]
    return i, t

def processPlus(ops, vals):
    if len(ops) > 0:
        processOp(vals, ops)
    ops.append("+")

def processOp(vals, ops):
    op = ops.pop()
    if op == "+":
        vals.append(vals.pop() + vals.pop())
    elif op == "*":
        vals.append(vals.pop() * vals.pop())

# Test section
def check(expr, expected):
    res = calc(expr)
    print(res)
    assert res == expected

check("8 / 2 / 2 / 2", 1.0)
check("8 / 2 + 1 / 2 / 2", 4.25)
check("8 / 2 + 1 / 2 * 2 / 2", 4.5)
check("8 / 2 + 1 / 2 * 2 / 2 - 1", 3.5)
check("1 + 2", 3)
check("1 - 2", -1)
check("2 * 3", 6)
check("1 + 2 * 2", 5)
check("2 * 3 + 2", 8)
check("1 * 2 + 2 * 3", 8)
check("1 * 2 + 2 * 3 + 1", 9)
check("1 * 2 + 2 * 3 + 1 + 2", 11)
check("1 * 2 + 2 * 3 + 1 + 2 * 2", 13)
check("1 - 2 * 3 + 4 * 2 - 1 - 2", 0.0)
check("1 - 2 * 3 + 4 * 2 - 1 - 2 * 2", -2.0)
check("1 - 2 * 3 + 4 * 2 - 1 - 2 * 2 - 3", -5.0)
check("2 ^ 2", 4.0)
check("2 + 3 ^ 2", 11.0)
check("2 + 3 ^ 2 - 1", 10.0)
check("2 + 3 ^ 2 - 1 * 3", 8.0)
</code>```

Body:
import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?

Body:
You can also use stack like functionality in Python to create your own calculator. Below is a simple example of a calculator which calculates:

sum,

difference,

multiplication

exponentiation

division

It can calculate expressions like these ones:

"1 - 2 * 3 + 4 * 2 - 1 - 2"
"8 / 2 + 1 / 2 * 2 / 2 - 1"

Spaces are used to separate the tokens in this simple implementation. More tests are available below in the source code:

def calc(str):
    tokens = str.split(" ")
    vals = []
    ops = []
    i = 0
    while i < len(tokens):
        t = tokens[i]
        if t == "+":
            processPlus(ops, vals)
        elif t == "*":
            ops.append(t)
        elif t == "-":
            processPlus(ops, vals)
            i, t = incrementAndGet(i, t, tokens)
            vals.append(float(t) * -1)
        elif t == "^":
            previousVal = vals.pop()
            i, t = incrementAndGet(i, t, tokens)
            vals.append(pow(previousVal, float(t)))
        elif t == "/":
            previousVal = vals.pop()
            i, t = incrementAndGet(i, t, tokens)
            vals.append(previousVal / float(t))
        else:
            vals.append(float(t))
        i += 1
    while len(ops) > 0:
        processOp(vals, ops)
    return sum(vals)

def incrementAndGet(i, t, tokens):
    i += 1
    t = tokens[i]
    return i, t

def processPlus(ops, vals):
    if len(ops) > 0:
        processOp(vals, ops)
    ops.append("+")

def processOp(vals, ops):
    op = ops.pop()
    if op == "+":
        vals.append(vals.pop() + vals.pop())
    elif op == "*":
        vals.append(vals.pop() * vals.pop())

# Test section
def check(expr, expected):
    res = calc(expr)
    print(res)
    assert res == expected

check("8 / 2 / 2 / 2", 1.0)
check("8 / 2 + 1 / 2 / 2", 4.25)
check("8 / 2 + 1 / 2 * 2 / 2", 4.5)
check("8 / 2 + 1 / 2 * 2 / 2 - 1", 3.5)
check("1 + 2", 3)
check("1 - 2", -1)
check("2 * 3", 6)
check("1 + 2 * 2", 5)
check("2 * 3 + 2", 8)
check("1 * 2 + 2 * 3", 8)
check("1 * 2 + 2 * 3 + 1", 9)
check("1 * 2 + 2 * 3 + 1 + 2", 11)
check("1 * 2 + 2 * 3 + 1 + 2 * 2", 13)
check("1 - 2 * 3 + 4 * 2 - 1 - 2", 0.0)
check("1 - 2 * 3 + 4 * 2 - 1 - 2 * 2", -2.0)
check("1 - 2 * 3 + 4 * 2 - 1 - 2 * 2 - 3", -5.0)
check("2 ^ 2", 4.0)
check("2 + 3 ^ 2", 11.0)
check("2 + 3 ^ 2 - 1", 10.0)
check("2 + 3 ^ 2 - 1 * 3", 8.0)


问:
How to populate Pandas datetime64[ns] values into MS Access
I have several DataFrames that have Order_date column. In all DataFrames, the Order_date columns' dtypes are datetime64[ns]. Please note that these columns are filled with valid dates and NaT values.

An example of how Order_date column looks like when printed:

```<code>   Order_date
</code>```

1 2017-01-01
 2 NaT
 3 NaT
 4 NaT
 5 2017-10-22

I am trying to populate these columns of DataFrames into MS Access table via pyodbc.

I get the following error:

pyodbc.DataError: ('22008', '[22008] [Microsoft][ODBC Microsoft Access Driver]Datetime field overflow (SQLExecDirectW)')

After research, I noticed that the Date/Time datatype for MS Access 2016 corresponds with ODBC datatype SQL_TIMESTAMP.

So, I tried the following to convert datetime64[ns] to SQL_TIMESTAMP:

```<code>import datetime
cursor.execute("SQL statement...VALUES(?)", datetime.datetime(order_date))
</code>```

However, I get this error: TypeError: an integer is required (got type Timestamp).

What can I do to successfully populate Pandas/Numpy datetime64[ns] values into MS Access table? How can I convert datetime64[ns] values into SQL_TIMESTAMP?

答:
IIUC - you were almost there. You just have to assign a Series returned by pd.to_datetime back to column:

```<code>df['Order_date'] = pd.to_datetime(df['Order_date'], errors='coerce')
</code>```

Body:
I have several DataFrames that have Order_date column. In all DataFrames, the Order_date columns' dtypes are datetime64[ns]. Please note that these columns are filled with valid dates and NaT values.

An example of how Order_date column looks like when printed:

   Order_date

1 2017-01-01
 2 NaT
 3 NaT
 4 NaT
 5 2017-10-22

I am trying to populate these columns of DataFrames into MS Access table via pyodbc.

I get the following error:

pyodbc.DataError: ('22008', '[22008] [Microsoft][ODBC Microsoft Access Driver]Datetime field overflow (SQLExecDirectW)')

After research, I noticed that the Date/Time datatype for MS Access 2016 corresponds with ODBC datatype SQL_TIMESTAMP.

So, I tried the following to convert datetime64[ns] to SQL_TIMESTAMP:

import datetime
cursor.execute("SQL statement...VALUES(?)", datetime.datetime(order_date))

However, I get this error: TypeError: an integer is required (got type Timestamp).

What can I do to successfully populate Pandas/Numpy datetime64[ns] values into MS Access table? How can I convert datetime64[ns] values into SQL_TIMESTAMP?

Body:
IIUC - you were almost there. You just have to assign a Series returned by pd.to_datetime back to column:

df['Order_date'] = pd.to_datetime(df['Order_date'], errors='coerce')