问:
Keep the original order of media elements in angular2-masonry plugin
I'm using an angular2-masonry plugin for an angular project, where I need to display the media without changing its order. There is no option available for the angular2-masonry plugin. So is there any way to make it happen?

Thanks.

答:
It is possible to wait for all the images to be loaded before the brick are added using useImagesLoaded, without the dimensions masonry is unable to maintain the desired arrangement.

To add useImagesLoaded:

Include this in your .angular-cli.json import src or in the index.html

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.1/imagesloaded.pkgd.min.js"></script>
</code>```

Had the use Image attribute set to true:

```<code><masonry [useImagesLoaded]="true"></masonry>
</code>```

Another option would be to use setTimeout to call reloadItems and layout:

One way to do this would be to first reference the component:

```<code>@ViewChild(AngularMasonry) private masonry: AngularMasonry;
</code>```

Then handle the event:

```<code>itemsLoadHandler() {
  setTimeout(() => {
    this.masonry.reloadItems();
    this.masonry.layout();
  });
}
</code>```

You can also listen for these events:

```<code>// Outputs
@Output() layoutComplete: EventEmitter<any[]> = new EventEmitter<any[]>();
@Output() removeComplete: EventEmitter<any[]> = new EventEmitter<any[]>();

ngOnInit() {
  this.masonry.on('layoutComplete', (items: any) => {
    this.layoutComplete.emit(items);
  });
  this.masonry.on('removeComplete', (items: any) => {
    this.removeComplete.emit(items);
  });
}
</code>```

Hope that helps

Body:
It is possible to wait for all the images to be loaded before the brick are added using useImagesLoaded, without the dimensions masonry is unable to maintain the desired arrangement.

To add useImagesLoaded:

Include this in your .angular-cli.json import src or in the index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.1/imagesloaded.pkgd.min.js"></script>

Had the use Image attribute set to true:

<masonry [useImagesLoaded]="true"></masonry>

Another option would be to use setTimeout to call reloadItems and layout:

One way to do this would be to first reference the component:

@ViewChild(AngularMasonry) private masonry: AngularMasonry;

Then handle the event:

itemsLoadHandler() {
  setTimeout(() => {
    this.masonry.reloadItems();
    this.masonry.layout();
  });
}

You can also listen for these events:

// Outputs
@Output() layoutComplete: EventEmitter<any[]> = new EventEmitter<any[]>();
@Output() removeComplete: EventEmitter<any[]> = new EventEmitter<any[]>();

ngOnInit() {
  this.masonry.on('layoutComplete', (items: any) => {
    this.layoutComplete.emit(items);
  });
  this.masonry.on('removeComplete', (items: any) => {
    this.removeComplete.emit(items);
  });
}

Hope that helps


来源: stackexchange

问:
Auto Scanning mappers in mybatis-spring
Our project structure is as follows:

```<code>- basePkg
 |- pkg1
  |- dao1
   |- mybatis-mappers...
  |- classes...
 |- pkg2
  |- dao2
   |- mybatis-mappers...
  |- classes...
</code>```

Right now, whenever we add a mybatis mapper to any of the dao packages, we have to add a new entry like the following to spring context.xml

```<code><bean id="testDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="basePkg.pkg1.dao1.testDao" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</code>```

It's getting cumbersome to keep adding a new entry for every new mapper. An alternative I found was to use <mybatis:scan \>. I'm facing two issues with this approach:

I don't want to give the basePkg directly as it would entail Spring scanning the whole project structure for mappers which would affect performance. This would mean that I would have to have a separate scan element for each basPkg.dao* package. Instead, is there a way to use a single scan element and specify all the dao subpackages using a regular expression?

We use two DataSources (MySQL and RedShift). How do I account for this while addressing the first issue listed above?

答:
I don't have to put this:

```<code><bean id="testDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="basePkg.pkg1.dao1.testDao" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</code>```

libraries used:

```<code><dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>1.3.1</version>
</dependency>

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.4.4</version>
</dependency>
</code>```

And making sure

TestMapper.java interface will have TestMapper.xml

or just TestMapper.java with annotations

if the XML files are in src\main\java, then something like below is required:

```<code>    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
            <execution>
                <id>add-resource</id>
                <phase>generate-resources</phase>
                <goals>
                    <goal>add-resource</goal>
                </goals>
                <configuration>
                    <resources>
                        <resource>
                            <directory>src/main/java</directory>
                            <includes>
                                <include>**/*.xml</include>
                            </includes>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Hope the above helps.

ContentLicense: CC BY-SA 3.0

Title: Auto Scanning mappers in mybatis-spring

Body:
Our project structure is as follows:

- basePkg
 |- pkg1
  |- dao1
   |- mybatis-mappers...
  |- classes...
 |- pkg2
  |- dao2
   |- mybatis-mappers...
  |- classes...

Right now, whenever we add a mybatis mapper to any of the dao packages, we have to add a new entry like the following to spring context.xml

<bean id="testDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="basePkg.pkg1.dao1.testDao" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

It's getting cumbersome to keep adding a new entry for every new mapper. An alternative I found was to use <mybatis:scan \>. I'm facing two issues with this approach:

I don't want to give the basePkg directly as it would entail Spring scanning the whole project structure for mappers which would affect performance. This would mean that I would have to have a separate scan element for each basPkg.dao* package. Instead, is there a way to use a single scan element and specify all the dao subpackages using a regular expression?

We use two DataSources (MySQL and RedShift). How do I account for this while addressing the first issue listed above?

Body:
I don't have to put this:

<bean id="testDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="basePkg.pkg1.dao1.testDao" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

libraries used:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>1.3.1</version>
</dependency>

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.4.4</version>
</dependency>

And making sure

TestMapper.java interface will have TestMapper.xml

or just TestMapper.java with annotations

if the XML files are in src\main\java, then something like below is required:

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
            <execution>
                <id>add-resource</id>
                <phase>generate-resources</phase>
                <goals>
                    <goal>add-resource</goal>
                </goals>
                <configuration>
                    <resources>
                        <resource>
                            <directory>src/main/java</directory>
                            <includes>
                                <include>**/*.xml</include>
                            </includes>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>

Hope the above helps.


问:
Windows UWP c++ code to get local IP and Subnet mask
How to get the local machine's Subnet mask in windows 10 using windows UWP API ?
"NetworkInformation" class gives only IP and not mask   </p>

答:
"NetworkInformation" class gives only IP and not mask

Currently, there is no such api to get subnet mask directly. You could get the PrefixLength instead. And convert PrefixLength to Subnet mask with the following way.

```<code>var hosts = NetworkInformation.GetHostNames();

foreach (var host in hosts)
{
    if (host.Type == HostNameType.Ipv4 && host.IPInformation != null)
    {
        var submask = SubnetMask.CreateByNetBitLength((int)host.IPInformation.PrefixLength);
    }
}
</code>```

Subnet Helper

```<code>public static class SubnetMask
{
    public static readonly IPAddress ClassA = IPAddress.Parse("255.0.0.0");
    public static readonly IPAddress ClassB = IPAddress.Parse("255.255.0.0");
    public static readonly IPAddress ClassC = IPAddress.Parse("255.255.255.0");

    public static IPAddress CreateByHostBitLength(int hostpartLength)
    {
        int hostPartLength = hostpartLength;
        int netPartLength = 32 - hostPartLength;

        if (netPartLength < 2)
            throw new ArgumentException("Number of hosts is to large for IPv4");

        Byte[] binaryMask = new byte[4];

        for (int i = 0; i < 4; i++)
        {
            if (i * 8 + 8 <= netPartLength)
                binaryMask[i] = (byte)255;
            else if (i * 8 > netPartLength)
                binaryMask[i] = (byte)0;
            else
            {
                int oneLength = netPartLength - i * 8;
                string binaryDigit =
                    String.Empty.PadLeft(oneLength, '1').PadRight(8, '0');
                binaryMask[i] = Convert.ToByte(binaryDigit, 2);
            }
        }
        return new IPAddress(binaryMask);
    }

    public static IPAddress CreateByNetBitLength(int netpartLength)
    {
        int hostPartLength = 32 - netpartLength;
        return CreateByHostBitLength(hostPartLength);
    }

    public static IPAddress CreateByHostNumber(int numberOfHosts)
    {
        int maxNumber = numberOfHosts + 1;

        string b = Convert.ToString(maxNumber, 2);

        return CreateByHostBitLength(b.Length);
    }
}
</code>```

Body:
"NetworkInformation" class gives only IP and not mask

Currently, there is no such api to get subnet mask directly. You could get the PrefixLength instead. And convert PrefixLength to Subnet mask with the following way.

var hosts = NetworkInformation.GetHostNames();

foreach (var host in hosts)
{
    if (host.Type == HostNameType.Ipv4 && host.IPInformation != null)
    {
        var submask = SubnetMask.CreateByNetBitLength((int)host.IPInformation.PrefixLength);
    }
}

Subnet Helper

public static class SubnetMask
{
    public static readonly IPAddress ClassA = IPAddress.Parse("255.0.0.0");
    public static readonly IPAddress ClassB = IPAddress.Parse("255.255.0.0");
    public static readonly IPAddress ClassC = IPAddress.Parse("255.255.255.0");

    public static IPAddress CreateByHostBitLength(int hostpartLength)
    {
        int hostPartLength = hostpartLength;
        int netPartLength = 32 - hostPartLength;

        if (netPartLength < 2)
            throw new ArgumentException("Number of hosts is to large for IPv4");

        Byte[] binaryMask = new byte[4];

        for (int i = 0; i < 4; i++)
        {
            if (i * 8 + 8 <= netPartLength)
                binaryMask[i] = (byte)255;
            else if (i * 8 > netPartLength)
                binaryMask[i] = (byte)0;
            else
            {
                int oneLength = netPartLength - i * 8;
                string binaryDigit =
                    String.Empty.PadLeft(oneLength, '1').PadRight(8, '0');
                binaryMask[i] = Convert.ToByte(binaryDigit, 2);
            }
        }
        return new IPAddress(binaryMask);
    }

    public static IPAddress CreateByNetBitLength(int netpartLength)
    {
        int hostPartLength = 32 - netpartLength;
        return CreateByHostBitLength(hostPartLength);
    }

    public static IPAddress CreateByHostNumber(int numberOfHosts)
    {
        int maxNumber = numberOfHosts + 1;

        string b = Convert.ToString(maxNumber, 2);

        return CreateByHostBitLength(b.Length);
    }
}


问:
Vtiger Webservice throwing 406 Error
I am trying to call a vtiger webservice using PHP CURL like this.

```<code>$selectQuery = urlencode("SELECT title,firstname,lastname FROM Contacts;");
            $curl = curl_init($data['url'].'/webservice.php?operation=query&sessionName='.$this->sessionName.'&query='.$selectQuery);
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
            curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0");
            curl_setopt($curl, CURLINFO_HEADER_OUT, true);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            $query = curl_exec($curl);
            //$query = json_decode($query);
            print_r($query);
</code>```

but i am getting the error

```<code>error:The requested URL returned error: 406 Not Acceptable
</code>```

I am just doing all the process as mentioned in the below url

http://community.vtiger.com/help/vtigercrm/developers/third-party-app-integration.html#list-types-operation

Anybody knows the solution for the same ?

答:
Hi Root ingenious please try

my code

```<code>$endURL = 'http://192.168.192.140/vtigercrm71'; //use ur url
$userName = 'admin'; //use ur username
$userAccessKey = 'h3fNwMr0Nc2hNQOL'; //use ur useraccesskey

$url = $endURL . '/webservice.php?operation=getchallenge&username=' . $userName;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 0);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);
$challengeToken = $res->result->token;

$generatedKey = md5($challengeToken . $userAccessKey);
$params = array(
    "operation" => 'login',
    "username" => $userName,
    "accessKey" => $generatedKey,
);

$postData = '';
foreach ($params as $k => $v) {
      $postData .= $k . '=' . $v . '&';
}
$postData = rtrim($postData, '&');
$url = $endURL . '/webservice.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);

$sessionName = $res->result->sessionName;
$userId = $res->result->userId;

$domain_name = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
$selectQuery = urlencode("SELECT title,firstname,lastname FROM Contacts;");
$url = $endURL . '/webservice.php?operation=query&query=' . $selectQuery . '&sessionName=' . $sessionName;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 0);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);
echo "```";
print_r($res);
exit;
```

<p>result</p>

```stdClass Object
(
    [success] => 1
    [result] => Array
        (
            [0] => stdClass Object
                (
                    [title] =>
                    [firstname] => asdfas
                    [lastname] => dfdsafdsf
                    [id] => 12x3
                )

        )

)
```

Title: Vtiger Webservice throwing 406 Error

Body:
I am trying to call a vtiger webservice using PHP CURL like this.

$selectQuery = urlencode("SELECT title,firstname,lastname FROM Contacts;");
            $curl = curl_init($data['url'].'/webservice.php?operation=query&sessionName='.$this->sessionName.'&query='.$selectQuery);
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
            curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0");
            curl_setopt($curl, CURLINFO_HEADER_OUT, true);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            $query = curl_exec($curl);
            //$query = json_decode($query);
            print_r($query);

but i am getting the error

error:The requested URL returned error: 406 Not Acceptable

I am just doing all the process as mentioned in the below url

http://community.vtiger.com/help/vtigercrm/developers/third-party-app-integration.html#list-types-operation

Anybody knows the solution for the same ?

Body:
Hi Root ingenious please try

my code

$endURL = 'http://192.168.192.140/vtigercrm71'; //use ur url
$userName = 'admin'; //use ur username
$userAccessKey = 'h3fNwMr0Nc2hNQOL'; //use ur useraccesskey

$url = $endURL . '/webservice.php?operation=getchallenge&username=' . $userName;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 0);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);
$challengeToken = $res->result->token;

$generatedKey = md5($challengeToken . $userAccessKey);
$params = array(
    "operation" => 'login',
    "username" => $userName,
    "accessKey" => $generatedKey,
);

$postData = '';
foreach ($params as $k => $v) {
      $postData .= $k . '=' . $v . '&';
}
$postData = rtrim($postData, '&');
$url = $endURL . '/webservice.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);

$sessionName = $res->result->sessionName;
$userId = $res->result->userId;

$domain_name = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
$selectQuery = urlencode("SELECT title,firstname,lastname FROM Contacts;");
$url = $endURL . '/webservice.php?operation=query&query=' . $selectQuery . '&sessionName=' . $sessionName;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 0);
$output = curl_exec($ch);
curl_close($ch);
$res = json_decode($output);
echo "<pre>";
print_r($res);
exit;

result

stdClass Object
(
    [success] => 1
    [result] => Array
        (
            [0] => stdClass Object
                (
                    [title] =>
                    [firstname] => asdfas
                    [lastname] => dfdsafdsf
                    [id] => 12x3
                )

        )

)


问:
How to handle gpg-agent in WSL?
I was trying to release a Jar and the gpg-agent was not starting. According to https://www.gnupg.org/documentation/manuals/gnupg-devel/Invoking-GPG_002dAGENT.html it should start automatically on any invocation of a GnuPG program but that doesn't seem to be true in WSL.

```<code>pupeno@DESKTOP-5N8VFOD:~$ gpg-agent
gpg-agent: no gpg-agent running in this session
</code>```

For a moment I thought that maybe GnuPG would just not work in WSL, but I managed to started manually:

```<code>pupeno@DESKTOP-5N8VFOD:~$ eval $(gpg-agent --daemon)
pupeno@DESKTOP-5N8VFOD:~$ gpg-agent
gpg-agent: gpg-agent running and available
</code>```

So, what's missing? Why isn't it starting automatically? or how should I start it?

答:
You want gpg-agent to start automatically, so start it from ~/.bashrc.

```<code>echo 'eval $(gpg-agent --daemon)' >> ~/.bashrc
</code>```

Title: How to handle gpg-agent in WSL?

Body:
I was trying to release a Jar and the gpg-agent was not starting. According to https://www.gnupg.org/documentation/manuals/gnupg-devel/Invoking-GPG_002dAGENT.html it should start automatically on any invocation of a GnuPG program but that doesn't seem to be true in WSL.

pupeno@DESKTOP-5N8VFOD:~$ gpg-agent
gpg-agent: no gpg-agent running in this session

For a moment I thought that maybe GnuPG would just not work in WSL, but I managed to started manually:

pupeno@DESKTOP-5N8VFOD:~$ eval $(gpg-agent --daemon)
pupeno@DESKTOP-5N8VFOD:~$ gpg-agent
gpg-agent: gpg-agent running and available

So, what's missing? Why isn't it starting automatically? or how should I start it?

Body:
You want gpg-agent to start automatically, so start it from ~/.bashrc.

echo 'eval $(gpg-agent --daemon)' >> ~/.bashrc

ContentLicense: CC BY-SA 4.0


问:
dplyr filter on a vector rather than a dataframe in R
This seems like a simple question, but I have not come across a clean solution for it yet. I have a vector in R and I want to remove certain elements from the vector, however I want to avoid the vector[vector != "thiselement"] notation for a variety of reasons. In particular, here is what I am trying to do:

```<code># this doesnt work
all_states = gsub(" ", "-", tolower(state.name)) %>% filter("alaska")

# this doesnt work either
all_states = gsub(" ", "-", tolower(state.name)) %>% filter(!= "alaska")

# this does work but i want to avoid this approach to filtering
all_states = gsub(" ", "-", tolower(state.name))
all_states = all_states[all_states != "alaska"]
</code>```

can this be done in a simple manner? Thanks in advance for the help!

EDIT - the reason I'm struggling with this is because I'm only finding things online regarding filtering based on a column of a dataframe, for example:

```<code>my_df %>% filter(col != "alaska")
</code>```

however I'm working with a vector not a dataframe here

答:
Update

As @r_31415 noted in the comments, packages such as stringr provide functions that can better address this question.

With str_subset(string, pattern, negate=FALSE), one could filter character vectors like

library(stringr)

# Strings that have at least one character that is neither "A" nor "B".
> c("AB", "BA", "ab", "CA") %>% str_subset("[^AB]")
[1] "ab" "CA"

# Strings that do not include characters "A" or "B".
> c("AB", "BA", "ab", "CA") %>% str_subset("[AB]", negate=TRUE)
[1] "ab"
```
<p>By default, the <code>pattern</code> is interpreted as a regular expression. Therefore, to search literal patterns that contains special characters like <code>(</code>, <code>*</code>, and <code>?</code>, one could enclose the pattern string with the modifier function <code>fixed(literal_string)</code> instead of escaping with double-backslash escape or the raw-string since R 4.0.0</p>
<pre class="lang-r prettyprint-override"><code># escape special character with "\\" (has to escape `\` with itself in a string literal).
> c("(123.5)", "12345") %>% str_subset("\\(123\\.5\\)")
[1] "(123.5)"

# R 4.0.0 supports raw-string, which is handy for regex strings
> c("(123.5)", "12345") %>% str_subset(r"{\(123\.5\)}")
[1] "(123.5)"

# use the fixed() modifier
> c("(123.5)", "12345") %>% str_subset(fixed("(123.5)"))
[1] "(123.5)"

## unexpected results if without escaping or the "fixed()" modifier
> c("(123.5)", "12345") %>% str_subset("(123.5)")
[1] "(123.5)" "12345"
</code>```

Original Answer

Sorry for posting on a 5-month-old question to archive a simpler solution.

Package dplyr can filter character vectors in following ways:

```<code>> c("A", "B", "C", "D") %>% .[matches("[^AB]", vars=.)]
[1] "C" "D"
> c("A", "B", "C", "D") %>% .[.!="A"]
[1] "B" "C" "D"
</code>```

The first approach allows you to filter with regular expression, and the second approach uses fewer words. It works because package dplyr imports package magrittr albeit masks its functions like extract, but not the placeholder ..

Details of placeholder . can be found on within help of forward-pipe operator %>%, and this placeholder has mainly three usage:

Using the dot for secondary purposes

Using lambda expressions with %>%

Using the dot-place holder as lhs

Here we are taking advantage of its 3rd usage.

Body:
This seems like a simple question, but I have not come across a clean solution for it yet. I have a vector in R and I want to remove certain elements from the vector, however I want to avoid the vector[vector != "thiselement"] notation for a variety of reasons. In particular, here is what I am trying to do:

# this doesnt work
all_states = gsub(" ", "-", tolower(state.name)) %>% filter("alaska")

# this doesnt work either
all_states = gsub(" ", "-", tolower(state.name)) %>% filter(!= "alaska")

# this does work but i want to avoid this approach to filtering
all_states = gsub(" ", "-", tolower(state.name))
all_states = all_states[all_states != "alaska"]

can this be done in a simple manner? Thanks in advance for the help!

EDIT - the reason I'm struggling with this is because I'm only finding things online regarding filtering based on a column of a dataframe, for example:

my_df %>% filter(col != "alaska")

however I'm working with a vector not a dataframe here

Body:
Update

As @r_31415 noted in the comments, packages such as stringr provide functions that can better address this question.

With str_subset(string, pattern, negate=FALSE), one could filter character vectors like

library(stringr)

# Strings that have at least one character that is neither "A" nor "B".
> c("AB", "BA", "ab", "CA") %>% str_subset("[^AB]")
[1] "ab" "CA"

# Strings that do not include characters "A" or "B".
> c("AB", "BA", "ab", "CA") %>% str_subset("[AB]", negate=TRUE)
[1] "ab"

By default, the pattern is interpreted as a regular expression. Therefore, to search literal patterns that contains special characters like (, *, and ?, one could enclose the pattern string with the modifier function fixed(literal_string) instead of escaping with double-backslash escape or the raw-string since R 4.0.0

# escape special character with "\\" (has to escape `\` with itself in a string literal).
> c("(123.5)", "12345") %>% str_subset("\\(123\\.5\\)")
[1] "(123.5)"

# R 4.0.0 supports raw-string, which is handy for regex strings
> c("(123.5)", "12345") %>% str_subset(r"{\(123\.5\)}")
[1] "(123.5)"

# use the fixed() modifier
> c("(123.5)", "12345") %>% str_subset(fixed("(123.5)"))
[1] "(123.5)"

## unexpected results if without escaping or the "fixed()" modifier
> c("(123.5)", "12345") %>% str_subset("(123.5)")
[1] "(123.5)" "12345"

Original Answer

Sorry for posting on a 5-month-old question to archive a simpler solution.

Package dplyr can filter character vectors in following ways:

> c("A", "B", "C", "D") %>% .[matches("[^AB]", vars=.)]
[1] "C" "D"
> c("A", "B", "C", "D") %>% .[.!="A"]
[1] "B" "C" "D"

The first approach allows you to filter with regular expression, and the second approach uses fewer words. It works because package dplyr imports package magrittr albeit masks its functions like extract, but not the placeholder ..

Details of placeholder . can be found on within help of forward-pipe operator %>%, and this placeholder has mainly three usage:

Using the dot for secondary purposes

Using lambda expressions with %>%

Using the dot-place holder as lhs

Here we are taking advantage of its 3rd usage.


问:
How do I make my site background change every X seconds?
I have a simple page, with a background using the tag
body { background-image: url("bgimage.jpg"); }

How do I make that image switch to a different image every (x) seconds?

I want the background to be kind of a slide show in a way..

答:
Check this. I've used this plugin a lot of time and it's very good.

It also has a lot of options and a good  API reference.

Otherwise, if you want to write it yourself, check other answers.


问:
Getting the disk signature as negative
```<code>import wmi
wmi_connector = wmi.WMI()
def get_win_drive_mappings_locally(drivemappings):

        for physical_disk in wmi_connector.Win32_DiskDrive():
            for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
                for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
                 print (physical_disk.Signature)
</code>```

I am using wmi to get information of disks and signature.
when i print the instance of physical_disk the output is as below:

```<code>instance of Win32_DiskDrive
{
        BytesPerSector = 512;
        Capabilities = {3, 4};
        CapabilityDescriptions = {"Random Access", "Supports Writing"};
        Caption = "XXXXX SCSI Disk Device";
        ConfigManagerErrorCode = 0;
        ConfigManagerUserConfig = FALSE;
        CreationClassName = "Win32_DiskDrive";
        Description = "Disk drive";
        DeviceID = "\\\\.\\PHYSICALDRIVE1";
        FirmwareRevision = "0   ";
        Index = 1;
        InterfaceType = "SCSI";
        Manufacturer = "(Standard disk drives)";
        MediaLoaded = TRUE;
        MediaType = "Fixed hard disk media";
        Model = "XXXX  SCSI Disk Device";
        Name = "\\\\.\\PHYSICALDRIVE1";
        Partitions = 1;
        PNPDeviceID = "SCSI\\DISK&XXXXX&PROD_K\\4&5393C0A&0&000100";
        SCSIBus = 0;
        SCSILogicalUnit = 0;
        SCSIPort = 2;
        SCSITargetId = 1;
        SectorsPerTrack = 63;
        SerialNumber = "XXXXX";
        Signature = **3908409726**;
        Size = "107372805120";
        Status = "OK";
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "SQLSERVER";
        TotalCylinders = "13054";
        TotalHeads = 255;
        TotalSectors = "209712510";
        TotalTracks = "3328770";
        TracksPerCylinder = 255;
};
</code>```

But when i print physical_disk.Signature the output is:
-386557570, i am not able to understand where its going wrong,expected output is 3908409726

答:
-386557570 is indeed 3908409726 interpreted as a 32 bit signed integer (in 2's complement arithmetic); probably the Python WMI connector interprets all 32 bit values as signed.

To interpret it as an unsigned value, check if it's negative, and in that case add 1<<32.

```<code>def as_uint32(v):
    if v<0:
        return v + (1<<32)
    return v

# ...
print (as_uint32(physical_disk.Signature))
</code>```

Title: Getting the disk signature as negative

Body:
import wmi
wmi_connector = wmi.WMI()
def get_win_drive_mappings_locally(drivemappings):

        for physical_disk in wmi_connector.Win32_DiskDrive():
            for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
                for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
                 print (physical_disk.Signature)

I am using wmi to get information of disks and signature.
when i print the instance of physical_disk the output is as below:

instance of Win32_DiskDrive
{
        BytesPerSector = 512;
        Capabilities = {3, 4};
        CapabilityDescriptions = {"Random Access", "Supports Writing"};
        Caption = "XXXXX SCSI Disk Device";
        ConfigManagerErrorCode = 0;
        ConfigManagerUserConfig = FALSE;
        CreationClassName = "Win32_DiskDrive";
        Description = "Disk drive";
        DeviceID = "\\\\.\\PHYSICALDRIVE1";
        FirmwareRevision = "0   ";
        Index = 1;
        InterfaceType = "SCSI";
        Manufacturer = "(Standard disk drives)";
        MediaLoaded = TRUE;
        MediaType = "Fixed hard disk media";
        Model = "XXXX  SCSI Disk Device";
        Name = "\\\\.\\PHYSICALDRIVE1";
        Partitions = 1;
        PNPDeviceID = "SCSI\\DISK&XXXXX&PROD_K\\4&5393C0A&0&000100";
        SCSIBus = 0;
        SCSILogicalUnit = 0;
        SCSIPort = 2;
        SCSITargetId = 1;
        SectorsPerTrack = 63;
        SerialNumber = "XXXXX";
        Signature = **3908409726**;
        Size = "107372805120";
        Status = "OK";
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "SQLSERVER";
        TotalCylinders = "13054";
        TotalHeads = 255;
        TotalSectors = "209712510";
        TotalTracks = "3328770";
        TracksPerCylinder = 255;
};

But when i print physical_disk.Signature the output is:
-386557570, i am not able to understand where its going wrong,expected output is 3908409726

Body:
-386557570 is indeed 3908409726 interpreted as a 32 bit signed integer (in 2's complement arithmetic); probably the Python WMI connector interprets all 32 bit values as signed.

To interpret it as an unsigned value, check if it's negative, and in that case add 1<<32.

def as_uint32(v):
    if v<0:
        return v + (1<<32)
    return v

# ...
print (as_uint32(physical_disk.Signature))


问:
two shared_ptr from same enable_shared_from_this instance
Given this class which is enable_shared_from_this:

```<code>class connection : public std::enable_shared_from_this<connection>
{
   //...
};
</code>```

Suppose I create two instances of std::shared_ptr from the same connection* as follows:

```<code>std::shared_ptr<connection> rc(new connection);

std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
                                   std::cout << "fake delete" << std::endl;
                               });
</code>```

So far its good, as  the resource { connection* } is owned by a single shared_ptr — rc to be precise, and fc just have a fake deleter.

After that, I do this:

```<code>auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!
</code>```

Now which shared_ptr — rc or fc — would sc  share its reference-count with? In other words,

```<code>std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;
</code>```

What should these print? I tested this code and found rc seems to have 2 references while fc just 1.

My question is, why is that? and what should be the correct behavior and its rationale?

I'm using C++11 and GCC 4.7.3.

答:
The raw pointer overloads assume ownership of the pointed-to object. Therefore, constructing a shared_ptr using the raw pointer overload for an object that is already managed by a shared_ptr, such as by shared_ptr(ptr.get()) is likely to lead to undefined behavior, even if the object is of a type derived from std::enable_shared_from_this.
  -- http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

In your case you get to shared pointers that have two different ownership information blocks but always increment the ref count of the first shared pointer instance of the class.

If you remove the 'fake deleter' you'l get a double free problem.

Body:
Given this class which is enable_shared_from_this:

class connection : public std::enable_shared_from_this<connection>
{
   //...
};

Suppose I create two instances of std::shared_ptr from the same connection* as follows:

std::shared_ptr<connection> rc(new connection);

std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
                                   std::cout << "fake delete" << std::endl;
                               });

So far its good, as  the resource { connection* } is owned by a single shared_ptr — rc to be precise, and fc just have a fake deleter.

After that, I do this:

auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!

Now which shared_ptr — rc or fc — would sc  share its reference-count with? In other words,

std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;

What should these print? I tested this code and found rc seems to have 2 references while fc just 1.

My question is, why is that? and what should be the correct behavior and its rationale?

I'm using C++11 and GCC 4.7.3.


问:
How to set NSImage to NSView Using CALayer in Cocoa swift
When I try to set NSimage to NSView my application gets crashed.

Application crashed at below line in ClockMainview controller:
  QuizDetailVC1.clockView.layer?.contents  = a1 // here its a crash

```<code>class ViewController: NSViewController
    {
        var abc1 = ClockMain()
        @IBOutlet var clock view: NSView!
        let layer = CALayer()
        func ClockApp()
        {
            layer.contents =  abc1.a1
            layer.contentsGravity = kCAGravityResizeAspectFill
            clockView?.layer = layer
            clockView?.wantsLayer = true
        }
    }

    class ClockMain: NSViewController,NSCollectionViewDelegate,NSCollectionViewDataSource
    {
     var a1 = NSImage(named:"\(UserDefaults.standard.value(forKey: "ImageName")!).jpg")!

      func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>)
        {
            let mainWC1 = view.window?.windowController as? Window
            let QuizDetailVC1 = storyboard?.instantiateController(withIdentifier: "ViewController") as! ViewController
            QuizDetailVC1.clockView.layer?.contents  = a1 // here its a crash
            QuizDetailVC1.layer.contentsGravity = kCAGravityResizeAspectFill
            mainWC1?.contentViewController = QuizDetailVC1
            print("click")
         }
    }
</code>```

答:
Try first setting this the line before:</p>

```<code>QuizDetailVC1.clockView.wantsLayer = true
QuizDetailVC1.clockView.layer?.contents = a1
</code>```

Body:
When I try to set NSimage to NSView my application gets crashed.

Application crashed at below line in ClockMainview controller:
  QuizDetailVC1.clockView.layer?.contents  = a1 // here its a crash

class ViewController: NSViewController
    {
        var abc1 = ClockMain()
        @IBOutlet var clock view: NSView!
        let layer = CALayer()
        func ClockApp()
        {
            layer.contents =  abc1.a1
            layer.contentsGravity = kCAGravityResizeAspectFill
            clockView?.layer = layer
            clockView?.wantsLayer = true
        }
    }

    class ClockMain: NSViewController,NSCollectionViewDelegate,NSCollectionViewDataSource
    {
     var a1 = NSImage(named:"\(UserDefaults.standard.value(forKey: "ImageName")!).jpg")!

      func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>)
        {
            let mainWC1 = view.window?.windowController as? Window
            let QuizDetailVC1 = storyboard?.instantiateController(withIdentifier: "ViewController") as! ViewController
            QuizDetailVC1.clockView.layer?.contents  = a1 // here its a crash
            QuizDetailVC1.layer.contentsGravity = kCAGravityResizeAspectFill
            mainWC1?.contentViewController = QuizDetailVC1
            print("click")
         }
    }

Body:
Try first setting this the line before:

QuizDetailVC1.clockView.wantsLayer = true
QuizDetailVC1.clockView.layer?.contents = a1


问:
CSS - can't get two divs to center within containing div
I need to get divs stacked on top of each other, horizontally aligned center -- within the black box.

I have this much:

.notification-dot-layer {
    margin: auto;
    width: 48px;
    height: 60px;
    position: relative;
    text-align: center;
    border: 1px solid black;
        text-align: center;
}

    .test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
width: 0px;
  }

.notificationbluedot {
    height: 48px;
    width: 48px;
    background-color: #3a3b7e;
    border-radius: 50%;
    margin: 0 auto;
 }

.notification-dot-text {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="notification-dot-layer">
<div class="test">
<div class="notificationbluedot">
<div class="notification-dot-text">
55
</div>
</div>
</div>
</div></code>```

Run the code snippet to see the results. Unfortunately, I can't get the blue circle with the "55" on it on top of the green line, centered. When the circle with the 55 is over the green line, only the portions of the green line that would be exposed should show.

What am I missing?

I need this to work in IE11 and Chrome.

答:
Use position:absolute in the circle also to make it centered, while the green is also behind. I also made the circle as a sibling to the line to remove the small gap in the left side

.notification-dot-layer {
  margin: auto;
  width: 48px;
  height: 60px;
  position: relative;
  text-align: center;
  border: 1px solid black;
  text-align: center;
}

.test {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
}

.notificationbluedot {
  height: 48px;
  width: 48px;
  background-color: #3a3b7e;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.notification-dot-text {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="notification-dot-layer">
  <div class="test">
  </div>
  <div class="notificationbluedot">
    <div class="notification-dot-text">
      55
    </div>
  </div>
</div></code>```

Body:
I need to get divs stacked on top of each other, horizontally aligned center -- within the black box.

I have this much:

.notification-dot-layer {
    margin: auto;
    width: 48px;
    height: 60px;
    position: relative;
    text-align: center;
    border: 1px solid black;
        text-align: center;
}

    .test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
width: 0px;
  }

.notificationbluedot {
    height: 48px;
    width: 48px;
    background-color: #3a3b7e;
    border-radius: 50%;
    margin: 0 auto;
 }

.notification-dot-text {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
 }

55

Run the code snippet to see the results. Unfortunately, I can't get the blue circle with the "55" on it on top of the green line, centered. When the circle with the 55 is over the green line, only the portions of the green line that would be exposed should show.

What am I missing?

I need this to work in IE11 and Chrome.

Body:
Use position:absolute in the circle also to make it centered, while the green is also behind. I also made the circle as a sibling to the line to remove the small gap in the left side

.notification-dot-layer {
  margin: auto;
  width: 48px;
  height: 60px;
  position: relative;
  text-align: center;
  border: 1px solid black;
  text-align: center;
}

.test {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
}

.notificationbluedot {
  height: 48px;
  width: 48px;
  background-color: #3a3b7e;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.notification-dot-text {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

<div class="notification-dot-layer">
  <div class="test">
  </div>
  <div class="notificationbluedot">
    <div class="notification-dot-text">
      55
    </div>
  </div>
</div>


问:
Julia is not working for loading large data in docker container [Bus error]
I have a Julia program which loads 8 GB of data. It is working fine in my local machine.

But when I try it in docker container it is not loading data and giving bus error. It is working fine with small data like 20 MB in docker container.

Dockerfile

```<code>FROM ubuntu:16.04

WORKDIR /julia

RUN apt-get -y update

RUN apt-get -y install unzip

RUN apt-get -y install cmake

RUN apt-get -y install clang

RUN apt-get -y install wget

RUN cd /tmp/

RUN wget "https://julialang.s3.amazonaws.com/bin/linux/x64/0.5/julia-0.5.0-linux-x86_64.tar.gz"

RUN tar -xzvf julia-0.5.0-linux-x86_64.tar.gz

RUN mv julia-3c9d75391c/ ~/julia

ENV PATH="/root/julia/bin:${PATH}"

RUN julia --eval 'Pkg.add("JSON")'

RUN julia --eval 'Pkg.add("HttpServer")'

RUN julia --eval 'Pkg.add("URIParser")'

RUN julia --eval 'Pkg.clone("https://github.com/deep-compute/AdaGram.jl.git")'

RUN julia --eval 'Pkg.build("AdaGram")'

CMD ["julia", "/tmp/adagram_server.jl", "80", "/julia/full.embed"]
</code>```

docker-compose.yml

```<code>version: "3.1"
services:
    julia:
        image: ramidavalapati/julia:v-1
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
        ports:
            - 8080:80
        command: ["sleep", "1h"]
</code>```

Next I am doing

```<code>sudo docker-compose up
sudo docker exec -it $(sudo docker-compose ps -q julia) bash
root@3748d5958f77:/julia# julia
julia> using AdaGram
julia> AdaGram.load_model("/julia/full.embed")
</code>```

Error

```<code>signal (7): Bus error
while loading no file, in expression starting on line 0
macro expansion at ./cartesian.jl:62 [inlined]
macro expansion at ./multidimensional.jl:429 [inlined]
_unsafe_batchsetindex! at ./multidimensional.jl:421
_setindex! at ./multidimensional.jl:370 [inlined]
setindex! at ./abstractarray.jl:832 [inlined]
#9 at /root/.julia/v0.5/AdaGram/src/AdaGram.jl:64
#600 at ./multi.jl:1030
run_work_thunk at ./multi.jl:1001
run_work_thunk at ./multi.jl:1010 [inlined]
#597 at ./event.jl:68
unknown function (ip: 0x7fe1822db16f)
jl_call_method_internal at /home/centos/buildbot/slave/package_tarball64/build/src/julia_internal.h:189 [inlined]
jl_apply_generic at /home/centos/buildbot/slave/package_tarball64/build/src/gf.c:1942
jl_apply at /home/centos/buildbot/slave/package_tarball64/build/src/julia.h:1392 [inlined]
start_task at /home/centos/buildbot/slave/package_tarball64/build/src/task.c:253
unknown function (ip: 0xffffffffffffffff)
Allocations: 9661042 (Pool: 9659980; Big: 1062); GC: 16
Bus error (core dumped)
</code>```

Docker version

```<code>Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:18 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:40:56 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

Docker info

```<code>Containers: 24
 Running: 0
 Paused: 0
 Stopped: 24
Images: 24
Server Version: 17.09.0-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: active
 NodeID: jlkmigmtyjhz6yvi3zuvkobu7
 Is Manager: true
 ClusterID: rqt03ulgvvnym235m1qm8vd17
 Managers: 4
 Nodes: 15
 Orchestration:
  Task History Retention Limit: 5
 Raft:
  Snapshot Interval: 10000
  Number of Old Snapshots to Retain: 0
  Heartbeat Tick: 1
  Election Tick: 3
 Dispatcher:
  Heartbeat Period: 5 seconds
 CA Configuration:
  Expiry Duration: 3 months
  Force Rotate: 0
 Autolock Managers: false
 Root Rotation In Progress: false
 Node Address: X.X.X.X
  Manager Addresses:
   X.X.X.X:2377
   X.X.X.X:2377
   X.X.X.X:2377
   X.X.X.X:2377
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 06b9cb35161009dcb7123345749fef02f7cea8e0
 runc version: 3f2f8b84a77f73d38244dd690525642a72156c64
 init version: 949e6fa
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 4.10.0-35-generic
 Operating System: Ubuntu 16.04.3 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 12
 Total Memory: 251.8GiB
 Name: ram
 ID: 3OGG:275C:Q3IW:O4HX:DPLP:DPI3:5TIT:AG5J:EDMK:7NK3:L4UZ:BTQH
 Docker Root Dir: /var/lib/docker
 Debug Mode (client): false
 Debug Mode (server): false
 Username: ramidavalapati
 Registry: https://index.docker.io/v1/
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

 WARNING: No swap limit support
</code>```

Thanks in advance for any kind of help

link to 40MBfull.embed file

答:
The problem is, there is no sufficient shared memory in docker container(default is 64 MB).

The problem was solved by giving the option --shm-size while running docker image.

Run : sudo docker run --shm-size 1G sample:latest

docker-compose file

```<code>version: "3.1"
services:
    julia:
        image: ramidavalapati/julia:v-1
        shm_size: 1g
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
        ports:
            - 8080:80
        command: ["sleep", "1h"]
</code>```

If we want to work in swarm mode, we need to refer shared memory in volume section.

```<code>version: "3.3"
services:
    julia:
        image: ramidavalapati/julia:v-1
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
            - /dev/shm:/dev/shm
        ports:
            - 8080:80
        command: ["sleep", "1h"]
</code>```

Here container uses shared memory of the host in which it is running.

Body:
I have a Julia program which loads 8 GB of data. It is working fine in my local machine.

But when I try it in docker container it is not loading data and giving bus error. It is working fine with small data like 20 MB in docker container.

Dockerfile

FROM ubuntu:16.04

WORKDIR /julia

RUN apt-get -y update

RUN apt-get -y install unzip

RUN apt-get -y install cmake

RUN apt-get -y install clang

RUN apt-get -y install wget

RUN cd /tmp/

RUN wget "https://julialang.s3.amazonaws.com/bin/linux/x64/0.5/julia-0.5.0-linux-x86_64.tar.gz"

RUN tar -xzvf julia-0.5.0-linux-x86_64.tar.gz

RUN mv julia-3c9d75391c/ ~/julia

ENV PATH="/root/julia/bin:${PATH}"

RUN julia --eval 'Pkg.add("JSON")'

RUN julia --eval 'Pkg.add("HttpServer")'

RUN julia --eval 'Pkg.add("URIParser")'

RUN julia --eval 'Pkg.clone("https://github.com/deep-compute/AdaGram.jl.git")'

RUN julia --eval 'Pkg.build("AdaGram")'

CMD ["julia", "/tmp/adagram_server.jl", "80", "/julia/full.embed"]

docker-compose.yml

version: "3.1"
services:
    julia:
        image: ramidavalapati/julia:v-1
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
        ports:
            - 8080:80
        command: ["sleep", "1h"]

Next I am doing

sudo docker-compose up
sudo docker exec -it $(sudo docker-compose ps -q julia) bash
root@3748d5958f77:/julia# julia
julia> using AdaGram
julia> AdaGram.load_model("/julia/full.embed")

Error

signal (7): Bus error
while loading no file, in expression starting on line 0
macro expansion at ./cartesian.jl:62 [inlined]
macro expansion at ./multidimensional.jl:429 [inlined]
_unsafe_batchsetindex! at ./multidimensional.jl:421
_setindex! at ./multidimensional.jl:370 [inlined]
setindex! at ./abstractarray.jl:832 [inlined]
#9 at /root/.julia/v0.5/AdaGram/src/AdaGram.jl:64
#600 at ./multi.jl:1030
run_work_thunk at ./multi.jl:1001
run_work_thunk at ./multi.jl:1010 [inlined]
#597 at ./event.jl:68
unknown function (ip: 0x7fe1822db16f)
jl_call_method_internal at /home/centos/buildbot/slave/package_tarball64/build/src/julia_internal.h:189 [inlined]
jl_apply_generic at /home/centos/buildbot/slave/package_tarball64/build/src/gf.c:1942
jl_apply at /home/centos/buildbot/slave/package_tarball64/build/src/julia.h:1392 [inlined]
start_task at /home/centos/buildbot/slave/package_tarball64/build/src/task.c:253
unknown function (ip: 0xffffffffffffffff)
Allocations: 9661042 (Pool: 9659980; Big: 1062); GC: 16
Bus error (core dumped)

Docker version

Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:18 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:40:56 2017
 OS/Arch:      linux/amd64
 Experimental: false

Docker info

Containers: 24
 Running: 0
 Paused: 0
 Stopped: 24
Images: 24
Server Version: 17.09.0-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: active
 NodeID: jlkmigmtyjhz6yvi3zuvkobu7
 Is Manager: true
 ClusterID: rqt03ulgvvnym235m1qm8vd17
 Managers: 4
 Nodes: 15
 Orchestration:
  Task History Retention Limit: 5
 Raft:
  Snapshot Interval: 10000
  Number of Old Snapshots to Retain: 0
  Heartbeat Tick: 1
  Election Tick: 3
 Dispatcher:
  Heartbeat Period: 5 seconds
 CA Configuration:
  Expiry Duration: 3 months
  Force Rotate: 0
 Autolock Managers: false
 Root Rotation In Progress: false
 Node Address: X.X.X.X
  Manager Addresses:
   X.X.X.X:2377
   X.X.X.X:2377
   X.X.X.X:2377
   X.X.X.X:2377
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 06b9cb35161009dcb7123345749fef02f7cea8e0
 runc version: 3f2f8b84a77f73d38244dd690525642a72156c64
 init version: 949e6fa
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 4.10.0-35-generic
 Operating System: Ubuntu 16.04.3 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 12
 Total Memory: 251.8GiB
 Name: ram
 ID: 3OGG:275C:Q3IW:O4HX:DPLP:DPI3:5TIT:AG5J:EDMK:7NK3:L4UZ:BTQH
 Docker Root Dir: /var/lib/docker
 Debug Mode (client): false
 Debug Mode (server): false
 Username: ramidavalapati
 Registry: https://index.docker.io/v1/
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

 WARNING: No swap limit support

Thanks in advance for any kind of help

link to 40MBfull.embed file

Body:
The problem is, there is no sufficient shared memory in docker container(default is 64 MB).

The problem was solved by giving the option --shm-size while running docker image.

Run : sudo docker run --shm-size 1G sample:latest

docker-compose file

version: "3.1"
services:
    julia:
        image: ramidavalapati/julia:v-1
        shm_size: 1g
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
        ports:
            - 8080:80
        command: ["sleep", "1h"]

If we want to work in swarm mode, we need to refer shared memory in volume section.

version: "3.3"
services:
    julia:
        image: ramidavalapati/julia:v-1
        volumes:
            - /home/ram/adagram_data/40MBfull.embed:/julia/full.embed
            - /dev/shm:/dev/shm
        ports:
            - 8080:80
        command: ["sleep", "1h"]

Here container uses shared memory of the host in which it is running.


问:
What happens to Java runtime errors
Following on from this question https://softwareengineering.stackexchange.com/questions/37294/logging-why-and-what

I was wondering what actually happens to an error that occurs during the runtime of a Java Enterprise Edition applicaiton.
Does the JVM store a log of all the errors?
Or are the errors forgotten?

答: Application servers usually have a big catch-all net to mop up any unhandled exceptions. However, if an exception is allowed to bubble up without it ever hitting a catch close, the thread it came from will die and the exception will be passed to the thread's UncaughtExceptionHandler, if one exists.

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Title: What happens to Java runtime errors


问:
requestAlwaysAuthorization not showing permission alert
I'm trying to use some fancy iBeacons without success, kCLAuthorizationStatusNotDetermined all time.
According to other questions it's a requirement to add those keys to info.plist (some questions says one, other says both). According to an article for iBeacons I need the Always option.

```<code><key>NSLocationWhenInUseUsageDescription</key>
<string>Nothing to say</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Permiso para acceder siempre</string>
</code>```

At viewDidAppear:

```<code>self.locManager = [[CLLocationManager alloc]init];
self.locManager.delegate = self;
[self.locManager requestAlwaysAuthorization];
NSUUID* region1UUID = [[NSUUID alloc]initWithUUIDString:@""]; //ibeacon real UUID between "". Checked it's not nil.

self.beaconRegion = [[CLBeaconRegion alloc]
                                initWithProximityUUID:proximityUUID
                                identifier:@"myCoolString"];

self.beaconRegion.notifyEntryStateOnDisplay = YES;
self.beaconRegion.notifyOnEntry = YES;
self.beaconRegion.notifyOnExit = NO;
[self.locManager startMonitoringForRegion:self.beaconRegion];
[self.locManager startRangingBeaconsInRegion:self.beaconRegion];
</code>```

Icon didn't appear at Settings/Privacy/Location until it was executed one of the two last methods. The Alert View to approve permissions never appears.
If I perform a manual change at Location Settings and check it it will change status but at a few moments later Location at Settings will delete "Always" status for my app and will leave it blank again. Later I check with no luck

```<code>-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
</code>```

Any ideas what is missing or wrong? Thank you

答:
Please check this Reference link

It has described all the changes regarding iOS 11. Your issue is also seems to be one among the cases it described. It might give you an idea what changes you need to make in your code to correct the issue.

Body:
I'm trying to use some fancy iBeacons without success, kCLAuthorizationStatusNotDetermined all time.
According to other questions it's a requirement to add those keys to info.plist (some questions says one, other says both). According to an article for iBeacons I need the Always option.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Nothing to say</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Permiso para acceder siempre</string>

At viewDidAppear:

self.locManager = [[CLLocationManager alloc]init];
self.locManager.delegate = self;
[self.locManager requestAlwaysAuthorization];
NSUUID* region1UUID = [[NSUUID alloc]initWithUUIDString:@""]; //ibeacon real UUID between "". Checked it's not nil.

self.beaconRegion = [[CLBeaconRegion alloc]
                                initWithProximityUUID:proximityUUID
                                identifier:@"myCoolString"];

self.beaconRegion.notifyEntryStateOnDisplay = YES;
self.beaconRegion.notifyOnEntry = YES;
self.beaconRegion.notifyOnExit = NO;
[self.locManager startMonitoringForRegion:self.beaconRegion];
[self.locManager startRangingBeaconsInRegion:self.beaconRegion];

Icon didn't appear at Settings/Privacy/Location until it was executed one of the two last methods. The Alert View to approve permissions never appears.
If I perform a manual change at Location Settings and check it it will change status but at a few moments later Location at Settings will delete "Always" status for my app and will leave it blank again. Later I check with no luck

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

Any ideas what is missing or wrong? Thank you


问:
AWS Autoscaling updating
You can create new Launch Configuration (updating AMI or whatever) and attach this with an existing Autoscaling Group. Per AWS Docs: After you change the launch configuration for an Auto Scaling group, any new instances are launched using the new configuration options, but existing instances are not affected.

How do you force this? Meaning relaunch all new instances now (with the new AMI). Do I have to delete the existing Autoscaling Group and create a new Autoscaling Group (with new Config)? Or I simple delete existing instances (one by one manually) and then ASG relaunch with new AMI. Any best practices/gotchas?
CloudFormation has the RollingUpdate flag (not sure of this outside of CF)

Thanks

答:
AWS has some OOTB solutions for this, CloudFormation (like you say), Elastic Beanstalk (built on top of CF), and CodeDeploy blue-green deployments (I've not tried this).

Personally for our SQS polling ASG, we do a "cold deploy" i.e. only "deploy" when there are no messages to process (and hence, due a scaling policy, no instances).  It's been really effective.

A deploy can be done safely whilst there are messages, provided that you set scale-in-protection on the instance during message processing (and remove it and wait briefly before polling):

set desired-capacity to 0

wait a bit (for there to be no instances running)

set desired-capacity back to N.

Note: you can do this all in the console.

You can code a solution yourself that does this... but I probably wouldn't.

Be careful:

simple delete existing instances (one by one manually)

Whether you can do this, or depends on whether the instances are still handling requests/processing (usually you can't simply terminate an instance without dropping service).

I recommend Elastic Beanstalk which gives a rolling update feature for free and is very easy to get started. I've not tried the CodeDeploy blue-green but it looks interesting. If you want more advanced behavior (or are already using it) look into Cloud Formation... do not code your own solution for rolling deployments: just use CloudFormation.

Title: AWS Autoscaling updating


问:
How can i operate two mongodb query synchronously in nodejs?
I am writing a shortenUrl API with Node.js and MongoDB.

I am using a collection for storing the incrementing ID.

Every time user asks for a shortened URL,

The server will ask the database for the newest available numberID,

Then do a base62 transformation.

However, because of the async feature of Nodejs, the finish time of obtaining incrementing ID and inserting new URL pair is not sure. Sometimes the server inserts the URL pair without the incrementing ID.

```<code>  app.post("/" , function(req , res) {
            const curLongUrl = req.body.longUrl;
            const data = {
                longUrl : curLongUrl,
                shortUrl : ""
            };
     const IDurl = "https://shortenurl-rustyblade.c9users.io/";

        mongo.connect(url , function(err , db) {
        if(err) {
            return console.log(err);
        }

        const increment = db.collection("autoIncrement");
        increment.findOne({"function" : "incrementKey"} , function(err , docs) {
            if(err) {
                return console.log(err);
            }
            const curID = docs.increment;
            console.log(curID);
            const curShortUrl = IDurl + curID;
            data.shortUrl = curShortUrl;
            db.close();
        });
    });

    mongo.connect(url , function(err , db) {
        if(err) {
            return console.log(err);
        }
        const col = db.collection("urlTable");
        col.insert(data , function(err , document) {
            if(err) {
                return console.log(err);
            }
            console.log(JSON.stringify(data));
            db.close();
            res.send(JSON.stringify(data));
        });
    });
    //res.send(JSON.stringify(data));
});
</code>```

答:
It seems like:

```<code>yourAPI("/", function () {
    // ...

    increment(function () {
        // ...

        // if increase success

        urlTableInsert(..., function () {
            // ...

            //  if insert success
            db.close();
            res.send(JSON.stringify(data));
        })
    })
})
</code>```

And you could use Promise, co or Async/await etc. to solve the Callback Hell problem.

Body:
I am writing a shortenUrl API with Node.js and MongoDB.

I am using a collection for storing the incrementing ID.

Every time user asks for a shortened URL,

The server will ask the database for the newest available numberID,

Then do a base62 transformation.

However, because of the async feature of Nodejs, the finish time of obtaining incrementing ID and inserting new URL pair is not sure. Sometimes the server inserts the URL pair without the incrementing ID.

  app.post("/" , function(req , res) {
            const curLongUrl = req.body.longUrl;
            const data = {
                longUrl : curLongUrl,
                shortUrl : ""
            };
     const IDurl = "https://shortenurl-rustyblade.c9users.io/";

        mongo.connect(url , function(err , db) {
        if(err) {
            return console.log(err);
        }

        const increment = db.collection("autoIncrement");
        increment.findOne({"function" : "incrementKey"} , function(err , docs) {
            if(err) {
                return console.log(err);
            }
            const curID = docs.increment;
            console.log(curID);
            const curShortUrl = IDurl + curID;
            data.shortUrl = curShortUrl;
            db.close();
        });
    });

    mongo.connect(url , function(err , db) {
        if(err) {
            return console.log(err);
        }
        const col = db.collection("urlTable");
        col.insert(data , function(err , document) {
            if(err) {
                return console.log(err);
            }
            console.log(JSON.stringify(data));
            db.close();
            res.send(JSON.stringify(data));
        });
    });
    //res.send(JSON.stringify(data));
});

Body:
It seems like:

yourAPI("/", function () {
    // ...

    increment(function () {
        // ...

        // if increase success

        urlTableInsert(..., function () {
            // ...

            //  if insert success
            db.close();
            res.send(JSON.stringify(data));
        })
    })
})

And you could use Promise, co or Async/await etc. to solve the Callback Hell problem.


问:
Jest Enzyme test a React component that returns null in render method
I have a component that returns null in render under certain conditions:

```<code>render() {
  if (this.props.isHidden) {
      return null;
  }

  return <div>test</div>;
}
</code>```

I want to check if the component is null when isHidden is true with jest and enzyme:

```<code>describe('myComp', () => {
    it('should not render if isHidden is true', () => {
        const comp = shallow(<myComp isHidden={true} />);
        expect(comp.children().length).toBe(0);
    });
});
</code>```

This works but is there a more idiomatic way to write this test ? Testing for components that render as null is quite a common scenario.

答:
expect(comp.type()).toEqual(null)
```
<p>That's it!</p>
<p>or:</p>
<pre class="lang-js prettyprint-override"><code>expect(comp.get(0)).toBeFalsy()
</code>```

Body:
I have a component that returns null in render under certain conditions:

render() {
  if (this.props.isHidden) {
      return null;
  }

  return
test
;
}

I want to check if the component is null when isHidden is true with jest and enzyme:

describe('myComp', () => {
    it('should not render if isHidden is true', () => {
        const comp = shallow(<myComp isHidden={true} />);
        expect(comp.children().length).toBe(0);
    });
});

This works but is there a more idiomatic way to write this test ? Testing for components that render as null is quite a common scenario.

Body:
expect(comp.type()).toEqual(null)

That's it!

or:

expect(comp.get(0)).toBeFalsy()


问:
How to reload page on new Heroku deploy (using node.js)
I have a website running on a node.js (via express) server that's hosted on Heroku. Currently if I'm on the website and I deploy a new build, my webpage will not automatically refresh once the deploy is built. I have to manually refresh the page.

How can I make any pages that are open reload automatically when a new deploy is built?

答:
The client would need to get data from the server on the current app version or start time.

```<code>{
  "version": "1.1.0",
  "start_time": 1510548486047
}
</code>```

An API endpoint like GET /api/v1/status polled with AJAX or a websocket message could be sent out on connection to return the data. Socket.IO is probably the easiest to get started with as it takes care of the client side.

The client side javascript can then decide on what criteria in the response warrants a page reload.

There's a lengthier answer if you want to hot reload javascript in particular.

Body:
The client would need to get data from the server on the current app version or start time.

{
  "version": "1.1.0",
  "start_time": 1510548486047
}

An API endpoint like GET /api/v1/status polled with AJAX or a websocket message could be sent out on connection to return the data. Socket.IO is probably the easiest to get started with as it takes care of the client side.

The client side javascript can then decide on what criteria in the response warrants a page reload.

There's a lengthier answer if you want to hot reload javascript in particular.


问:
Reactjs POST request through fetch
Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

Failed to load http://localhost:8083/students: Response for preflight has invalid HTTP status code 403

Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />

     </div>
         </form>

   );
 }

}
</code>```

Even though here my form values also hard-coded.

答:
I can see you use FormData, with Content-Type header application/json which is wrong.

```<code>var data = new FormData();
</code>```

Another point to raise here is you can't set JSON inside FormData like this.

```<code>data.append("myjsonkey", JSON.stringify(payload));
</code>```

Firstly what kind of payload do you need to send. Use multipart FormData only if you need to send files to the server. If you do so, make sure you remove the Content-Type header from your request.

Or else, if you want to send JSON data create a proper JSON payload and send it instead of FormData. That should work.

Title: Reactjs POST request through fetch

Body:
Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

Failed to load http://localhost:8083/students: Response for preflight has invalid HTTP status code 403

Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>

     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />

     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />

     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />

     <input type="submit" />

         </form>

   );
 }

}

Even though here my form values also hard-coded.

Body:
I can see you use FormData, with Content-Type header application/json which is wrong.

var data = new FormData();

Another point to raise here is you can't set JSON inside FormData like this.

data.append("myjsonkey", JSON.stringify(payload));

Firstly what kind of payload do you need to send. Use multipart FormData only if you need to send files to the server. If you do so, make sure you remove the Content-Type header from your request.

Or else, if you want to send JSON data create a proper JSON payload and send it instead of FormData. That should work.


问:
500.21 internal serve error bad module has a bad module "ManagedPipelineHandler" in its module list
we have a website which runs under v4.0 , Classic Mode. We have recently created new httphandler and when we request to this handler we receive
500.21 internal serve error - bad module has a bad module "ManagedPipelineHandler" in its module list.

WebSite works fine with no issues.  I have tried all possible solution given in google like regiis & add entry of handler to system.webserver but nothing has worked for me.

Can someone give some idea on the same?

答:
Run the following command, which will install and register ASP.NET 4.5 in IIS:

dism /online /enable-feature /featurename:IIS-ASPNET45 /all


问:
Remove view controllers from stack
I have a view controller(called FirstVC) which goes to another view controller(called SecondVC) with a segue. In SecondVC, I have a PagingMenuController which is a paging menu library. pagingMenuController itself has view controllers to show.
code to add view controllers to pagingMenuController:

```<code>fileprivate var pagingControllers: [UIViewController] {
    return [viewControllerList,viewControllerMap]
}
</code>```

code to add pagingMenuController to SecondVC:

```<code>addChildViewController(pagingMenuController)
view.addSubview(pagingMenuController.view)
pagingMenuController.didMove(toParentViewController: self)
</code>```

code to go back to FirstVC:

```<code>self.navigationController?.popViewController(animated: true)
</code>```

Every time I go to SecondVC and come back to FirstVC, there are 20MB extra memory loaded. lets suppose I'm doing this:

In FirstVC --- Memory: 20MB

go to SecondVC --- Memory: 40MB

go back to FirstVC --- Memory: 40MB

go to SecondVC --- Memory: 60MB

go back to FirstVC --- Memory: 60MB

Although I pop view controller(SecondVC) from navigation controller, memory doesn't go free. what should I do and what is wrong I'm doing?

答:
Let's start with obvious. Check your SecondVC for so called retain cycles or strong reference cycles. It might be one of these cases:

You use self in some closure in SecondVC without weak or onowned reference. So the closure has a strong reference to the view controller and vice versa.

You have some property (with strong reference) in SecondVC which through some other entities (with strong references too) points to SecondVC.

Because of this SecondVC can not be deallocate from the memory. And you get a memory leak. You need to break retain cycle if this is the case. Usually we do this by making one of references weak.

For more information read Resolving Strong Reference Cycles Between Class Instances.

For more help please show full code of view controllers.

Title: Remove view controllers from stack

Body:
I have a view controller(called FirstVC) which goes to another view controller(called SecondVC) with a segue. In SecondVC, I have a PagingMenuController which is a paging menu library. pagingMenuController itself has view controllers to show.
code to add view controllers to pagingMenuController:

fileprivate var pagingControllers: [UIViewController] {
    return [viewControllerList,viewControllerMap]
}

code to add pagingMenuController to SecondVC:

addChildViewController(pagingMenuController)
view.addSubview(pagingMenuController.view)
pagingMenuController.didMove(toParentViewController: self)

code to go back to FirstVC:

self.navigationController?.popViewController(animated: true)

Every time I go to SecondVC and come back to FirstVC, there are 20MB extra memory loaded. lets suppose I'm doing this:

In FirstVC --- Memory: 20MB

go to SecondVC --- Memory: 40MB

go back to FirstVC --- Memory: 40MB

go to SecondVC --- Memory: 60MB

go back to FirstVC --- Memory: 60MB

Although I pop view controller(SecondVC) from navigation controller, memory doesn't go free. what should I do and what is wrong I'm doing?


问:
AWS S3 Bucket copy function
We are trying to push +1.5 Million files via AWS CLI to a Bucket. We tried it on staging first and the task is still running (we iterate through folders). This is ongoing for 5 days now...

Is there a faster way to push that many file from a online server to the S3 bucket?

FYI: All the files are in special folders hashed in subfolders, depending on the name.

答:
Below things you can try:

Enable S3 Transfer Acceleration Detail

you can use AWS Import/Export

use AWS DirectConnect, which establishes a dedicated private network connection (1Gbps or 10Gbps ports) between AWS and your premises. You can also make use of APN network[2] if you do not have preexisting infra at Direct Connect locations.

Title: AWS S3 Bucket copy function


问:
cURL GET request function is not returning a string
I am writing a program in OS X which requires to run the users HWID through a PHP script, which will then echo a value which will be read using a function in my code.

This PHP script, basically checks the IP that the GET request was made from, checks if the IP exists in a table, if it does, then check for other values such as if the given HWID is correct, or if the user is premium and then returns a string according to this.

This is the function here;

```<code>string pullResult(string hwid) {
    CURL* curl;
    string result;

    curl = curl_easy_init();
    std::string url = "removed/usercheck.php?hwid=" + hwid;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    result = curl_easy_perform(curl);

    return result;
}
</code>```

And this is where it is called;

```<code>if(al.pullResult(hwid) == "no such user")
    cout << "no such user" << endl;
</code>```

However, using this function does not work. I can go into my browser and make the GET request and the script returns the right strings, but this just doesn't return the string.

Now, I know for a fact I am checking for the right string as I have everything setup for this string to be the outcome.

EDIT: I've actually read the manual now, lol, and found out that this won't return a string or what is read from the webpage, rather it's own flag-ish thing. If someone can tell me what I'm doing wrong in my function, that'd be great.

答:
You can use something like this. It passes a pointer to a std::string object to the callback function that appends the returned data to the passed in std::string. There is very little in the way of error checking. In real code every function call should be checked for errors.

```<code>#include <memory>
#include <stdexcept>
#include <string>
#include <curl/curl.h>

std::size_t http_write(void* buf, std::size_t size, std::size_t nmemb, void* userp)
{
    if(auto page_data_ptr = static_cast<std::string*>(userp))
    {
        page_data_ptr->append(static_cast<char*>(buf), size * nmemb);
        return size * nmemb;
    }

    return 0;
}

std::string http_get(std::string const& url)
{
    // I use a unique_ptr to automatically call the cleanup function
    // so we don't need to do it later after the call
    std::unique_ptr<CURL, void(*)(CURL*)> curl{curl_easy_init(), curl_easy_cleanup};

    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &http_write);
    curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);

    std::string page_data; // collect the results
    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &page_data);
    curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());

    CURLcode code = curl_easy_perform(curl.get());

    if(code != CURLE_OK)
        throw std::runtime_error(curl_easy_strerror(code));

    return page_data;
}
</code>```

NOTE: Don't forget to call curl_global_init(CURL_GLOBAL_DEFAULT); once before calling this function.

Body:
I am writing a program in OS X which requires to run the users HWID through a PHP script, which will then echo a value which will be read using a function in my code.

This PHP script, basically checks the IP that the GET request was made from, checks if the IP exists in a table, if it does, then check for other values such as if the given HWID is correct, or if the user is premium and then returns a string according to this.

This is the function here;

string pullResult(string hwid) {
    CURL* curl;
    string result;

    curl = curl_easy_init();
    std::string url = "removed/usercheck.php?hwid=" + hwid;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    result = curl_easy_perform(curl);

    return result;
}

And this is where it is called;

if(al.pullResult(hwid) == "no such user")
    cout << "no such user" << endl;

However, using this function does not work. I can go into my browser and make the GET request and the script returns the right strings, but this just doesn't return the string.

Now, I know for a fact I am checking for the right string as I have everything setup for this string to be the outcome.

EDIT: I've actually read the manual now, lol, and found out that this won't return a string or what is read from the webpage, rather it's own flag-ish thing. If someone can tell me what I'm doing wrong in my function, that'd be great.

Body:
You can use something like this. It passes a pointer to a std::string object to the callback function that appends the returned data to the passed in std::string. There is very little in the way of error checking. In real code every function call should be checked for errors.

#include <memory>
#include <stdexcept>
#include <string>
#include <curl/curl.h>

std::size_t http_write(void* buf, std::size_t size, std::size_t nmemb, void* userp)
{
    if(auto page_data_ptr = static_cast<std::string*>(userp))
    {
        page_data_ptr->append(static_cast<char*>(buf), size * nmemb);
        return size * nmemb;
    }

    return 0;
}

std::string http_get(std::string const& url)
{
    // I use a unique_ptr to automatically call the cleanup function
    // so we don't need to do it later after the call
    std::unique_ptr<CURL, void(*)(CURL*)> curl{curl_easy_init(), curl_easy_cleanup};

    curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &http_write);
    curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
    curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);

    std::string page_data; // collect the results
    curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &page_data);
    curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());

    CURLcode code = curl_easy_perform(curl.get());

    if(code != CURLE_OK)
        throw std::runtime_error(curl_easy_strerror(code));

    return page_data;
}

NOTE: Don't forget to call curl_global_init(CURL_GLOBAL_DEFAULT); once before calling this function.


问:
How we can implement the new push view controller animation which have come in App Store's Today feature in IOS 11
What is the best way to create a custom UIViewController transition that on the first VC for example there is an image, and when you tap on it, it rises to the top of the screen and some other UI components (like labels and textViews) are added to the screen?

I want to achieve something like what Apple did on the new "Today" tab on the App Store.

答:
If this is what you want, I will update both this answer and the demo serveral hours later.
I write the demo in a hurry, so apologize for the ugly UI and the code style.

The demo project is on Github.

If you are familiar with the transition, then the key trick here is you just need to add an animation view to the top of the UIViewControllerContextTransitioning.container and move it to the position where it would be displayed in destination view controller. When you complete the transition, just remove this animation view directly or by animation.


问:
Android Webview Autofill Information like address, passwords, personal information
I want to create Autofill functionality for my Android demo app same as Chromium does. I have information like address, personal information, passwords. How can I integrate all this stuff on my custom browser? Please advice me.</p>

答:
You can follow these steps,

Collect each keywords(words) which user tries to search.

Store in database with priorities

Number of time particular keyword is searched.

How much time user has spent on particular search.

Base on user likes.

If your database on cloud, you can also return what other user likes most.

Build searching patterns to identify priorities.

Try to return data based on priorities when user types a word.


问:
IIS on Windows 7: 400 bad request when requesting XML files
I have a website running under IIS on Windows 7.
Everytime the webpage requests an XML file I receive a 400 Bad Request (diagnosed through firebug).  If I request the XML file directly by typing it into my browser it works.

This not only happens for .xml file extensions but .xsl too; both of which contain XML data.

答:
Is your xml file static or dynamically generated?

If static then check the following:

Your (successful) browser request would be using a GET request. Is your webpage request using POST? If so, POST may not be an accepted verb for a static xml file.

Check the IIS configuration settings for .xml suffix files.


问:
Android Quick shortcuts [passing intent extra(or some data) in shortcuts.xml ]
While implementing the static Shortcuts using shortcut.xml, i would like to pass few bundle extras with my intent.

need the passed extras to decide on few functionality in the target class after launching the app.

is it possible to access the extras? how and where to access it?

Any leads would be highly appreciated

答:
I'm not sure if there is another way, but I use this:

```<code><intent
        android:action="android.intent.action.VIEW"
        android:targetPackage="target.package"
        android:targetClass="activity.with.package">
        <extra android:name="extraID" android:value="extravalue" />
</intent>
</code>```

Then you can access extras as usual.

Body:
I'm not sure if there is another way, but I use this:

<intent
        android:action="android.intent.action.VIEW"
        android:targetPackage="target.package"
        android:targetClass="activity.with.package">
        <extra android:name="extraID" android:value="extravalue" />
</intent>

Then you can access extras as usual.


问:
How to right-align form input boxes?
I have a seemingly easy problem to solve, but am struggling. How do I get these two inputs to align to the right of the form, without using the BR element ?

```<code><!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    form {
        text-align: right;
    }
    input {
        width: 100px;
    }
    </style>
</head>

<body>
    <form>
         <input name="declared_first" value="above" />

         <br/> <!-- I want to get rid of this -->

         <input name="declared_second" value="below" />
    </form>
</body>
</html>
</code>```

I just want the first input to appear above the second input, both on the right hand side.

答:
Try use this:</p>

```<code>input {
  clear: both;
  float: right;
  margin-bottom: 10px;
  width: 100px;
}
</code>```

Title: How to right-align form input boxes?

Body:
I have a seemingly easy problem to solve, but am struggling. How do I get these two inputs to align to the right of the form, without using the BR element ?

<!DOCTYPE html>

    <form>
         <input name="declared_first" value="above" />

         <input name="declared_second" value="below" />
    </form>

I just want the first input to appear above the second input, both on the right hand side.

Body:
Try use this:

input {
  clear: both;
  float: right;
  margin-bottom: 10px;
  width: 100px;
}


问:
How to remove or hide Image Description field in TinyMCE image popup
First disclaimer, I am stuck in TinyMCE v4.2 as because of some stability and business issue.

What I want to do is, hide the Image Description field from the Image upload popup, thats something comes with their image plugin.

Here is a fiddle I created with my code so far I done for attaching data images in richtext.

NB: I know there is a option for disabling this in updated version of TinyMCE. I already read their doc and its as simple as having just a option

```<code>tinymce.init({
    image_description: false
});
</code>```

But what about the earlier version. I find no proper documentation for their older versions.

Any kind of help or idea is appreciatable. Thanks.

答:
Not great but might help you out - hide it with css</p>

```<code>#mce_41-body {
  display:none;
}
</code>```

Body:
First disclaimer, I am stuck in TinyMCE v4.2 as because of some stability and business issue.

What I want to do is, hide the Image Description field from the Image upload popup, thats something comes with their image plugin.

Here is a fiddle I created with my code so far I done for attaching data images in richtext.

NB: I know there is a option for disabling this in updated version of TinyMCE. I already read their doc and its as simple as having just a option

tinymce.init({
    image_description: false
});

But what about the earlier version. I find no proper documentation for their older versions.

Any kind of help or idea is appreciatable. Thanks.

Body:
Not great but might help you out - hide it with css

#mce_41-body {
  display:none;
}


问:
JSON stub string delivered via php
I would like to make a web service stub where I can test my client. I have written down
some JSON like this:

```<code>{
    "response": {
        "success": true,
        "meta" : "tags",
        "data": [
            {
                "first_name" : "John",
                "last_name" : "Doe",
                "age" : 30
            },
            {
                "first_name" : "Jane",
                "last_name" : "Doe",
                "age" : 25
            }
        ]
    }
}
</code>```

I have no PHP experience to talk about.
How can I make a

webserver.com/get_names.php?first_name=john&last_name=doe&age=30

script that returns the above JSON.

It should not do any evaluation on the parameters, that is just how it will end up being called when implemented against a server, I would just like it to return the JSON string correctly so my JSON parser can run through it as if it was the actual server response.

Hope someone can help me out, thank you in advance.

答:
This is usually referred to as an API, and can be developed on many levels.

First level would be standard streamline php, where you would have code that follows the general php coding.

```<code>$Action = isset($_GET["action"]) ? $_GET["action"] : false;

switch($Action)
{
    case 'get_names':
        //fetch data and display.
    break;
}
</code>```

The next method and the simplest would be to use an MVC Application Framework, I would recommend Code Igniter for this as tis bigginner friendly and the URI Structure is similar to an API Soap Server.

After copying your CI Files to your /api/ path, you would go threw the guide and configure your database,libraries,helpers etc, you would also use mod_rewrite to set up the URI Convention to get urls such as /api/get/games/API_KEY

your class would look like so:

```<code>class Get extends Controller
{
    public function __construct()
    {
        parent::Controller();
    }

    public function games($Api = false,$limit = 10, $offset = 0)
    {
        if(!$Api)
        {
            show_error("API Key require to fetch games");
        }
        if(your_api_check($api) === true)
        {
             //Load the games
             $games = $this->models->games->get($limit,$offset);
             $this->output->send(json_encode($games));
        }
    }
}
</code>```

Obviously more extensive checking with the validation of the params but you will get the gist of it.

The next level would be very complex for your self but if you wish to persue the idea then you may want to look into Simple Object Access Protocol but ill leave that for you to decide.

Links:

Codeigniter

RESTful with Codeigniter

Restful with CodeIgniter #2

Codeigniter XMLRPC Services

Title: JSON stub string delivered via php

Body:
I would like to make a web service stub where I can test my client. I have written down
some JSON like this:

{
    "response": {
        "success": true,
        "meta" : "tags",
        "data": [
            {
                "first_name" : "John",
                "last_name" : "Doe",
                "age" : 30
            },
            {
                "first_name" : "Jane",
                "last_name" : "Doe",
                "age" : 25
            }
        ]
    }
}

I have no PHP experience to talk about.
How can I make a

webserver.com/get_names.php?first_name=john&last_name=doe&age=30

script that returns the above JSON.

It should not do any evaluation on the parameters, that is just how it will end up being called when implemented against a server, I would just like it to return the JSON string correctly so my JSON parser can run through it as if it was the actual server response.

Hope someone can help me out, thank you in advance.

Body:
This is usually referred to as an API, and can be developed on many levels.

First level would be standard streamline php, where you would have code that follows the general php coding.

$Action = isset($_GET["action"]) ? $_GET["action"] : false;

switch($Action)
{
    case 'get_names':
        //fetch data and display.
    break;
}

The next method and the simplest would be to use an MVC Application Framework, I would recommend Code Igniter for this as tis bigginner friendly and the URI Structure is similar to an API Soap Server.

After copying your CI Files to your /api/ path, you would go threw the guide and configure your database,libraries,helpers etc, you would also use mod_rewrite to set up the URI Convention to get urls such as /api/get/games/API_KEY

your class would look like so:

class Get extends Controller
{
    public function __construct()
    {
        parent::Controller();
    }

    public function games($Api = false,$limit = 10, $offset = 0)
    {
        if(!$Api)
        {
            show_error("API Key require to fetch games");
        }
        if(your_api_check($api) === true)
        {
             //Load the games
             $games = $this->models->games->get($limit,$offset);
             $this->output->send(json_encode($games));
        }
    }
}

Obviously more extensive checking with the validation of the params but you will get the gist of it.

The next level would be very complex for your self but if you wish to persue the idea then you may want to look into Simple Object Access Protocol but ill leave that for you to decide.

Links:

Codeigniter

RESTful with Codeigniter

Restful with CodeIgniter #2

Codeigniter XMLRPC Services