问:
A more efficent way of implementing if-statement related to class-type
At the moment I have an ArrayDeque of a Tuple as follows (I thought having a class in this might help), which is currently serialized and sent over a network:

```<code>private ArrayDeque<Triple<Integer, Object, Class>> paramList = new ArrayDeque<>();
</code>```

The object types in the Tuple can be primitive such as ints, bool or real classes such as Date, time (none of which are my implementations).

Right now I'm iterating through the list and calling the method depending on what class type it is, obviously this becomes tedious modify and update when.
For example (st is PreparedStatement):

```<code>for (Triple<Integer, Object, Class> param : paramList) {
    if(param.getMiddle() instanceof String){
        st.setString(parm.getLeft(),param.getMiddle());
    }else if(param.getMiddle() instanceof Integer){
        st.setInt(parm.getLeft(),param.getMiddle());
    } //... more class type checks doing the same thing
}
</code>```

I came across this https://stackoverflow.com/a/5579385/5858208 post but as it's not classes I've implemented I can't really do much.

So my question is, is there a more efficient and maintainable way of implementing this idea since I have exactly what class-type it is in the tuple object?

答:
You could create a Map that contains as keys all the classes that your code supports and as values lambda expressions that call the correct setter.

Something along these lines:

```<code>@FunctionalInterface
interface PSConsumer<T,U> {
    void accept(T t, U u) throws SQLException;
}

private Map<Class<?>, PSConsumer<PreparedStatement, Triple<Integer, Object, Class<?>>>> setters = new HashMap<>();
{
    setters.put(String.class, (st, param) -> st.setString(param.getLeft(), (String) param.getMiddle()));
    setters.put(Integer.class, (st, param) -> st.setInt(param.getLeft(), (Integer) param.getMiddle()));
    // add here code for all the classes that you support
}

for (Triple<Integer, Object, Class<?>> param : paramList) {
    // this will throw an NPE if param.getMiddle() returns null or it's class is not in the map:
    setters.get(param.getMiddle().getClass()).accept(st, param);
}
</code>```

To extract values in a similar way you could use definitions likes these:

```<code>@FunctionalInterface
interface RSExtractor<T,U,R> {
    R apply(T t, U u) throws SQLException;
}
private Map<Class<?>, RSExtractor<ResultSet, Triple<Integer, Object, Class<?>>, Object>> getters = new HashMap<>();
{
    getters.put(String.class, (rs, param) -> rs.getString(param.getLeft()));
    getters.put(Integer.class, (rs, param) -> rs.getInt(param.getLeft()));
}

public List<Object> get(ResultSet rs) throws SQLException {
    List<Object> results = new ArrayList<>();
    for (Triple<Integer, Object, Class<?>> param : paramList) {
        results.add(getters.get(param.getRight()).apply(rs, param));
    }
    return results;
}
</code>```

Please note that the interface RSExtractor looks much like the interface java.util.function.BiFunction, except that this interface allows the implementing method to throw an SQLException

Body:
At the moment I have an ArrayDeque of a Tuple as follows (I thought having a class in this might help), which is currently serialized and sent over a network:

private ArrayDeque<Triple<Integer, Object, Class>> paramList = new ArrayDeque<>();

The object types in the Tuple can be primitive such as ints, bool or real classes such as Date, time (none of which are my implementations).

Right now I'm iterating through the list and calling the method depending on what class type it is, obviously this becomes tedious modify and update when.
For example (st is PreparedStatement):

for (Triple<Integer, Object, Class> param : paramList) {
    if(param.getMiddle() instanceof String){
        st.setString(parm.getLeft(),param.getMiddle());
    }else if(param.getMiddle() instanceof Integer){
        st.setInt(parm.getLeft(),param.getMiddle());
    } //... more class type checks doing the same thing
}

I came across this https://stackoverflow.com/a/5579385/5858208 post but as it's not classes I've implemented I can't really do much.

So my question is, is there a more efficient and maintainable way of implementing this idea since I have exactly what class-type it is in the tuple object?

Body:
You could create a Map that contains as keys all the classes that your code supports and as values lambda expressions that call the correct setter.

Something along these lines:

@FunctionalInterface
interface PSConsumer<T,U> {
    void accept(T t, U u) throws SQLException;
}

private Map<Class<?>, PSConsumer<PreparedStatement, Triple<Integer, Object, Class<?>>>> setters = new HashMap<>();
{
    setters.put(String.class, (st, param) -> st.setString(param.getLeft(), (String) param.getMiddle()));
    setters.put(Integer.class, (st, param) -> st.setInt(param.getLeft(), (Integer) param.getMiddle()));
    // add here code for all the classes that you support
}

for (Triple<Integer, Object, Class<?>> param : paramList) {
    // this will throw an NPE if param.getMiddle() returns null or it's class is not in the map:
    setters.get(param.getMiddle().getClass()).accept(st, param);
}

To extract values in a similar way you could use definitions likes these:

@FunctionalInterface
interface RSExtractor<T,U,R> {
    R apply(T t, U u) throws SQLException;
}
private Map<Class<?>, RSExtractor<ResultSet, Triple<Integer, Object, Class<?>>, Object>> getters = new HashMap<>();
{
    getters.put(String.class, (rs, param) -> rs.getString(param.getLeft()));
    getters.put(Integer.class, (rs, param) -> rs.getInt(param.getLeft()));
}

public List<Object> get(ResultSet rs) throws SQLException {
    List<Object> results = new ArrayList<>();
    for (Triple<Integer, Object, Class<?>> param : paramList) {
        results.add(getters.get(param.getRight()).apply(rs, param));
    }
    return results;
}

Please note that the interface RSExtractor looks much like the interface java.util.function.BiFunction, except that this interface allows the implementing method to throw an SQLException


来源: stackexchange

问:
Horizontal scrollbar ever visible
I'm develping a webapp using Angular + Lumx.
I'm implementing a dialog in which there are a table with a lot of columns and a lot of rows so it scrolls even horizontally even vertically.

The problem is that the horizontal scrollbar is visible only at the end of the page. But in this way it is not clear that the user can also scrolls horizontally.

Is there a way to make the horizontal scrollbar always visible?

Thanks a lot!

As you can see in the screens below, the horizontal scrollbar is visibile only if I'm at the end of the page

After scrolling vertically at the end of the page, I can see it

答:
On Mac OS the scrollbars hide! There is a system preference for this.

There is also a long thread concerning this here: https://news.ycombinator.com/item?id=6246777

ContentLicense: CC BY-SA 3.0

Title: Horizontal scrollbar ever visible


问:
PHP cURL HTTP PUT
I am trying to create a HTTP PUT request with cURL and I can't make it work. I've read many tutorials but none of them actually worked. Here's my current code:

```<code>$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);

if (curl_error($ch))
{
    print curl_error($ch);
}
else
{
    print 'ret: ' .$returned;
}
</code>```

I've also tried using PHP PEAR but got the same result. The problem is that the repository says that no metadata has been set. I really need help! Thanks!

答:
Using Postman for Chrome, selecting CODE you get this...  And works

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://blablabla.com/comorl",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"jordi@correo.es\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/json",
    "x-api-key: whateveriyouneedinyourheader"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>```

Title: PHP cURL HTTP PUT

Body:
I am trying to create a HTTP PUT request with cURL and I can't make it work. I've read many tutorials but none of them actually worked. Here's my current code:

$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);

if (curl_error($ch))
{
    print curl_error($ch);
}
else
{
    print 'ret: ' .$returned;
}

I've also tried using PHP PEAR but got the same result. The problem is that the repository says that no metadata has been set. I really need help! Thanks!


问:
java - iterating a linked list
if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?</p>

答: Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)</p>

ContentLicense: CC BY-SA 2.5

Title: java - iterating a linked list


问:
What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis in env laravel?
I use laravel 5.3

In my localhost, the env like this :

```<code>CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

In my production, the env like this :

```<code>CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

Almost all the same, just SESSION_DRIVER different

What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis?

答:
session driver file stores session data in a file, redis driver stores session data in redis, redis driver is obviously faster. For example</p>

```<code>Session::set('user', $user); //this is stored in file or redis
Session::get('user'); //this is get from file or redis
</code>```

Body:
I use laravel 5.3

In my localhost, the env like this :

CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

In my production, the env like this :

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Almost all the same, just SESSION_DRIVER different

What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis?

Body:
session driver file stores session data in a file, redis driver stores session data in redis, redis driver is obviously faster. For example

Session::set('user', $user); //this is stored in file or redis
Session::get('user'); //this is get from file or redis

ContentLicense: CC BY-SA 4.0


问:
Using array to find HCF, getting unknown output (C++)
So no matter what I input, I get the result 176 when for my last output.

My logic is that I can make an Array(comfactors) and placing common factors in it. After that, I take the highest number and place it in comfactors[0] and output it.

If anyone else has any other recommendation to do it, do tell. Always looking to learn.

```<code>#include <iostream>
using namespace std;
typedef int integer;
void generate_factors(integer factor1[], int a, integer factor2[], int b);
void findHCF(int[], int[], int, int);
int main()
{
int x, y;

cout << "Enter first integer: " << endl;
cin >> x;

cout << "Enter second integer: " << endl;
cin >> y;

integer *integerArray1 = new integer[x], *integerArray2 = new integer[y];

generate_factors(integerArray1, x, integerArray2, y);
findHCF(integerArray1, integerArray2, x, y);

return 0;
}

void generate_factors(integer factor1[], int a, integer factor2[], int b)
{
int i, j;
cout << "\n" << endl;
cout << "Factors of " << a << " are: " << endl;
for (i = 1; i <= a; i++)
{
    if ((a%i) == 0)
    {
        factor1[i - 1] = i;
        cout << factor1[i - 1] << " ";
    }

}

cout << "\n" << endl;

cout << "Factors of " << b << " are: " << endl;
for (j = 1; j <= b; j++)
{
    if ((b%j) == 0)
    {
        factor2[j - 1] = j;
        cout << factor2[j - 1] << " ";
    }

}

}

void findHCF(integer Array1[], integer Array2[], int a, int b)
{
int i, j, k;
int comfactors[1024];

for (i = 0; i <= a; i++)
{
    for(j = 0; j <= b; j++)
    {

        if (Array1[j] == Array2[i])
        {
            comfactors[i] = i;
        }

    }

}

for (k = 0;k < a+b; ++k)
{
    if (comfactors[0] < comfactors[k])
    {
    comfactors[0] = comfactors[k];}
}
cout << "\n\nThe Highest Common Factor is " << comfactors[0];
}
</code>```

答:
You are getting wrong answer because here your arrays are filled with garbade values at random spots ,
 for example in your function generate_factors only those spots are filled for which the condition is being satisfied. So because of that when you search common values in functionfindHCF those garbage value comes and cause unexpected output to occur.
So you should initialize the arrays with 1

Although a simple way to calculate the HCF of two numbers is the use of Euclid's Algorithm.

Here's an implementation of Euclid's algorithm in C++:

```<code>int hcf(int a, int b) {
   if (b == 0) {
      return a;
   } else {
      return hcf(b, a % b);
   }
}
</code>```

Body:
So no matter what I input, I get the result 176 when for my last output.

My logic is that I can make an Array(comfactors) and placing common factors in it. After that, I take the highest number and place it in comfactors[0] and output it.

If anyone else has any other recommendation to do it, do tell. Always looking to learn.

#include <iostream>
using namespace std;
typedef int integer;
void generate_factors(integer factor1[], int a, integer factor2[], int b);
void findHCF(int[], int[], int, int);
int main()
{
int x, y;

cout << "Enter first integer: " << endl;
cin >> x;

cout << "Enter second integer: " << endl;
cin >> y;

integer *integerArray1 = new integer[x], *integerArray2 = new integer[y];

generate_factors(integerArray1, x, integerArray2, y);
findHCF(integerArray1, integerArray2, x, y);

return 0;
}

void generate_factors(integer factor1[], int a, integer factor2[], int b)
{
int i, j;
cout << "\n" << endl;
cout << "Factors of " << a << " are: " << endl;
for (i = 1; i <= a; i++)
{
    if ((a%i) == 0)
    {
        factor1[i - 1] = i;
        cout << factor1[i - 1] << " ";
    }

}

cout << "\n" << endl;

cout << "Factors of " << b << " are: " << endl;
for (j = 1; j <= b; j++)
{
    if ((b%j) == 0)
    {
        factor2[j - 1] = j;
        cout << factor2[j - 1] << " ";
    }

}

}

void findHCF(integer Array1[], integer Array2[], int a, int b)
{
int i, j, k;
int comfactors[1024];

for (i = 0; i <= a; i++)
{
    for(j = 0; j <= b; j++)
    {

        if (Array1[j] == Array2[i])
        {
            comfactors[i] = i;
        }

    }

}

for (k = 0;k < a+b; ++k)
{
    if (comfactors[0] < comfactors[k])
    {
    comfactors[0] = comfactors[k];}
}
cout << "\n\nThe Highest Common Factor is " << comfactors[0];
}

Body:
You are getting wrong answer because here your arrays are filled with garbade values at random spots ,
 for example in your function generate_factors only those spots are filled for which the condition is being satisfied. So because of that when you search common values in functionfindHCF those garbage value comes and cause unexpected output to occur.
So you should initialize the arrays with 1

Although a simple way to calculate the HCF of two numbers is the use of Euclid's Algorithm.

Here's an implementation of Euclid's algorithm in C++:

int hcf(int a, int b) {
   if (b == 0) {
      return a;
   } else {
      return hcf(b, a % b);
   }
}


问:
Unit testing of potential concurrency problems
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

```<code>@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}
</code>```

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?

答:
Ignoring all practical reasons, this is also why it's theoretically hard to achieve a complete set of concurrency safety tests:

Assuming there are n threads operating on the same data structure. Then any thread i has a sequence of Si atomic operations on this datastructure, where each sequence may have a different length. Now what you need to make sure in an ideal environment is that every possible iteration sequence across all threads through these operation is covered by your tests. Even for relatively small operation sequences and only 2 threads this number grows quite fast.

But now the difficult part is to translate these findings to a real computer. Identifying such atomic operations itself is a complex task of its own, given the freedom of how jvms can be implemented and the java memory model. Then there is also thread scheduling controlled by os. So it's usually out of your control what actual operation sequence takes place on the data structure.

Body:
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?


问:
regex for .aspx? to modify query string
I need to modify the query string,

from:   http://server/test/default.aspx

to:   http://server/test/default.aspx?videoplay=20

or

from  :   http://server/test/default.aspx?toolPlay=1233136844420765

to    :   http://server/test/default.aspx?videoplay=20&toolPlay=1233136844420765

ie. add videoplay=20& in between the query string

through jQuery. I have tried the .replace function but there is problem - I cannot find the correct regex. Can anyone provide a better approach or provide a regex for ".aspx?"

答:
You need to escape both the . and the ? as they are special regex characters:

```<code>\.aspx\?
</code>```

However, you can simply append &videoplay=20 to the end of the URL. The effect will be the same, unless the serverside code is looking at the index of querystring variables (which is very poor practice).

Title: regex for .aspx? to modify query string

Body:
You need to escape both the . and the ? as they are special regex characters:

\.aspx\?

However, you can simply append &videoplay=20 to the end of the URL. The effect will be the same, unless the serverside code is looking at the index of querystring variables (which is very poor practice).


问:
How to write JavaPairDStream to Redis?
I am using spark 1.5.0 and java 7.

Input is from kafka in form of different json objects with a type field. Eg:

```<code>{'type': 'alpha', ...}
{'type': 'beta', ...}
...
</code>```

I am creating a JavaPairDStream<String, Integer> from this input data corresponding to counts of each event type.

I want to store this data to redis. How can I go about doing this?

答:
Creating a new connection pool for every single RDD is very inefficient. I suggest creating one connection for each partition:</p>

```<code>wordCount.mapPartitions(p->{
 Jedis jd = new Jedis(getJedisConfig());
 while (p->hasNext()) {
   Tuple2<String,Integer> data = p.next();
   String word = data._1();
   Integer cnt = data._2();
   jd.set(word,count); // or any other format of save to Redis
 }
}
)
</code>```

Title: How to write JavaPairDStream to Redis?

Body:
I am using spark 1.5.0 and java 7.

Input is from kafka in form of different json objects with a type field. Eg:

{'type': 'alpha', ...}
{'type': 'beta', ...}
...

I am creating a JavaPairDStream<String, Integer> from this input data corresponding to counts of each event type.

I want to store this data to redis. How can I go about doing this?

Body:
Creating a new connection pool for every single RDD is very inefficient. I suggest creating one connection for each partition:

wordCount.mapPartitions(p->{
 Jedis jd = new Jedis(getJedisConfig());
 while (p->hasNext()) {
   Tuple2<String,Integer> data = p.next();
   String word = data._1();
   Integer cnt = data._2();
   jd.set(word,count); // or any other format of save to Redis
 }
}
)


问:
Just started coding in html and css but i'm stuck at making the picture seeable through the navigation bar
As you saw above i can't get the picture seeable through the navigation bar. Keep in mind i just started and i got no experience. This is what i got and don't know where to go from here.

HTML:

```<code><body>
  <nav>
    <ul>
      <li>
        <a class="active" href="index.html">Home</a>
      </li>
      <li>
        <a href="about.html">About</a>
      </li>
      <li>
        <a href="sights.html">Sights</a>
      </li>
      <li>
        <a href="sakura.html">Sakura</a>
      </li>
    </ul>
  </nav>
</body>
</code>```

CSS:

```<code>body {
  background-image: url(pic1.jpg);
}
* {
  padding: 0;
  margin: 0;
}
nav {
  height: 70px;
  text-align: center;
  background-color: rgba(255, 10, 173, 0.27);
  padding: 20px;
}
nav li {
  display: inline-block;
  margin: 0;
  padding-top: 20px;
}
nav li a {
  text-decoration: none;
  color: #FFF;
  padding-left: 150px;
  padding-right: 150px;
  padding-top: 20px;
  padding-bottom: 20px;
  font-family: arial;
  text-align: center;
  background-color: rgba(170, 19, 120, 1);
}
nav li a:hover, .active {
  background-color: rgba(255, 77, 181, 0.87);
}
</code>```

Here is a screenshot of the expected output:

答:
I think what you are lookging for is the opacity attribute.

Try adding:

opacity: 0.5;

to your nav li a CSS and see if that helps!

Body:
As you saw above i can't get the picture seeable through the navigation bar. Keep in mind i just started and i got no experience. This is what i got and don't know where to go from here.

HTML:

        Home

        About

        Sights

        Sakura

CSS:

body {
  background-image: url(pic1.jpg);
}
* {
  padding: 0;
  margin: 0;
}
nav {
  height: 70px;
  text-align: center;
  background-color: rgba(255, 10, 173, 0.27);
  padding: 20px;
}
nav li {
  display: inline-block;
  margin: 0;
  padding-top: 20px;
}
nav li a {
  text-decoration: none;
  color: #FFF;
  padding-left: 150px;
  padding-right: 150px;
  padding-top: 20px;
  padding-bottom: 20px;
  font-family: arial;
  text-align: center;
  background-color: rgba(170, 19, 120, 1);
}
nav li a:hover, .active {
  background-color: rgba(255, 77, 181, 0.87);
}

Here is a screenshot of the expected output:


问:
Attempting to construct a Pivot table-like item in SQL
I am trying to create a result that shows a breakdown of industries in an area. The end result will look something like this.

```<code>  Area          Industry                    Number of sites
 000000       All industries                        250
 000001       Industry 1(11 and 21)                 22
 000001       Industry 2(23)                        25
 ......
 000001       Industry 10 (81)                      120
</code>```

Some background so that the above makes sense. In the original data set, there are 6 digit codes for the industry. We break them down based on the first two digits and then make custom groups. 11 and 21 are one group and so on. I can figure how to get individual rows of this but struggling to find out how to get all 11 rows in one result. I can write and execute 11 separate queries but am hoping to get it one result.  Below is the code for getting one of the rows. Is this the place for using a JOIN or UNION command or operator?

```<code>SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '11%' or code like '21%')
GROUP BY
[area]
</code>```

答:
I thought it was something simple but the internet results were confusing. All it is putting a "UNION ALL" between each query. </p>

```<code>SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '11%' or code like '21%')
GROUP BY
[area]
UNION ALL
SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '23%')
GROUP BY
[area]
UNION ALL
SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '31%' or code like '32%' or code like
'33%')
GROUP BY
[area]
</code>```

Body:
I am trying to create a result that shows a breakdown of industries in an area. The end result will look something like this.

  Area          Industry                    Number of sites
 000000       All industries                        250
 000001       Industry 1(11 and 21)                 22
 000001       Industry 2(23)                        25
 ......
 000001       Industry 10 (81)                      120

Some background so that the above makes sense. In the original data set, there are 6 digit codes for the industry. We break them down based on the first two digits and then make custom groups. 11 and 21 are one group and so on. I can figure how to get individual rows of this but struggling to find out how to get all 11 rows in one result. I can write and execute 11 separate queries but am hoping to get it one result.  Below is the code for getting one of the rows. Is this the place for using a JOIN or UNION command or operator?

SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '11%' or code like '21%')
GROUP BY
[area]

Body:
I thought it was something simple but the internet results were confusing. All it is putting a "UNION ALL" between each query.

SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '11%' or code like '21%')
GROUP BY
[area]
UNION ALL
SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '23%')
GROUP BY
[area]
UNION ALL
SELECT
[Area],
COUNT(*) AS [Number of Sites]
FROM
dbo.sizeclassreport
Where area='000001' and (code like '31%' or code like '32%' or code like
'33%')
GROUP BY
[area]


问:
Make NetBeans(ant) generate multiple jar files for one project
i have a project in netbeans that include two main classes, one starts a client and other starts a server.

I need to create two jar file to wrap into two exe file, one for client and one for server, how can i do this?

Thanks.

NB: im using ant.

答:
You can have two mains in the same jar file. (Only one if you want an executable jar)

To create two jars you need two maven modules/pom.xml


问:
Match "any string" in Haskell record in HSpec test
I have a data class Entity which is defined like this:

```<code>data Entity = Entity { id :: String, name :: String }
</code>```

and a function that returns IO Entity:

```<code>newPersistentEntity :: String -> IO Entity
</code>```

And I'd like to write an HSpec test for this:

```<code>spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}
</code>```

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

答:
The id of an Entity can't not be a String, because static typing. But you probably do want to force its evaluation to ensure that it isn't bottom.

```<code>spec :: Spec
spec = describe "newPersistentEntity function" $
    it "returns a new Entity with a generated id and the specified name" $ do
        x <- newPersistentEntity "myName"
        pure $! id x  -- Force evaluation of the `id` field to ensure that
                      -- the database actually did return a string here
        name x `shouldBe` "myName"
</code>```

Body:
I have a data class Entity which is defined like this:

data Entity = Entity { id :: String, name :: String }

and a function that returns IO Entity:

newPersistentEntity :: String -> IO Entity

And I'd like to write an HSpec test for this:

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

Body:
The id of an Entity can't not be a String, because static typing. But you probably do want to force its evaluation to ensure that it isn't bottom.

spec :: Spec
spec = describe "newPersistentEntity function" $
    it "returns a new Entity with a generated id and the specified name" $ do
        x <- newPersistentEntity "myName"
        pure $! id x  -- Force evaluation of the `id` field to ensure that
                      -- the database actually did return a string here
        name x `shouldBe` "myName"


问:
file handling I/O c++ error

this is the code which i am trying to run.The compiler shows some warning that the variable 'p' may be possible to be used uninitialized.
  And ..on running it has a problem ..i will show..below.
  please correct me and explain .
  Thank you.
  execution of code
  *
  code
  that error is that..the first two elements of the character array being output are somewhat messed up!!!*

```<code>#include<bits/stdc++.h>
using namespace std;
class file{
public:int a;
char* name;
public:
file(int x,char* b):a(x){name=b;}
void printfile(){cout<<a<<" "<<name<<endl;}
};
int main(){
char *p;
int x=10;
cout<<"enter a name"<<endl;
cin>>p;
file k(x,p);
ofstream f("file",ios::out|ios::binary);
f.write((char*)&k,sizeof(class file));
f.close();
ifstream of("file",ios::in|ios::binary);
file o(0,'\0');
of.read((char*)&o,sizeof(class file));
o.printfile();
of.close();
return 1;
}
</code>```

答:
You have p as some pointer. Who is going to allocate the memory that pointer points to?

In C it is almost always the responsibility of the caller to allocate any buffers before the call.

If you don't want to, then use a std::string instead.

Title: file handling I/O c++ error

Body:
this is the code which i am trying to run.The compiler shows some warning that the variable 'p' may be possible to be used uninitialized.
  And ..on running it has a problem ..i will show..below.
  please correct me and explain .
  Thank you.
  execution of code
  *
  code
  that error is that..the first two elements of the character array being output are somewhat messed up!!!*

#include<bits/stdc++.h>
using namespace std;
class file{
public:int a;
char* name;
public:
file(int x,char* b):a(x){name=b;}
void printfile(){cout<<a<<" "<<name<<endl;}
};
int main(){
char *p;
int x=10;
cout<<"enter a name"<<endl;
cin>>p;
file k(x,p);
ofstream f("file",ios::out|ios::binary);
f.write((char*)&k,sizeof(class file));
f.close();
ifstream of("file",ios::in|ios::binary);
file o(0,'\0');
of.read((char*)&o,sizeof(class file));
o.printfile();
of.close();
return 1;
}


问:
extends could not be found with AsyncTask android Xamarin?
I want to use AsyncTask in class ContactsAdapter: RecyclerView.Adapter, View.IOnClickListener, but in Xamarin give me error:
enter image description here

Could please help!

答:
extends is not a key word in C#. In C# you would use : which will alter your code to:

public class DownloadImageTask : AsyncTask<...>


问:
Does Keen.io have a limit keyword or equivalent?
All,

Using Keen.io to pull some analytics.  I allow user input to specify start and end times, but I'm not able to find something equivalent to a "limit" parameter such as can be found for SQL queries.  If a user specifies a large enough range, this can result in way too much data coming back.

Does Keen.io have a way to pull back the first "x" records?

bower.json

"keen-js": "^3.4.1",

答:
There is a new  Keen IO API feature released today which allows you to limit your query result to get your "top x results" and have the results ordered by ascending or descending as well. order_by works similar to the currently existing group_by feature -- you will call order_by in your query.

Define a direction to sort all of your query's results in either ASC or descending order (default ordering is ascending). And use limit to tell the API the number of results you'd like returned - whether that is your top 5 or bottom 5 results.

Order By Docs: https://keen.io/docs/api/#order-by

Here's sample JavaScript to illustrate the newly added order_by API feature:

import Keen from 'keen-js';

const client = new Keen({
  projectId: 'PROJECT_ID',
  readKey: 'READ_KEY'
});

client
  .query('count', {
    event_collection: 'logins',
    group_by: 'user.email',
    order_by: {'property_name': 'result', 'direction': 'DESC'},
    limit: '5', //this limits your number of results
    timeframe: 'this_14_days'
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });```

order_by and limit has been a top requested by customers - thank you for feedback to help with creating tools and features to Keen IO's API.

Body:
There is a new  Keen IO API feature released today which allows you to limit your query result to get your "top x results" and have the results ordered by ascending or descending as well. order_by works similar to the currently existing group_by feature -- you will call order_by in your query.

Define a direction to sort all of your query's results in either ASC or descending order (default ordering is ascending). And use limit to tell the API the number of results you'd like returned - whether that is your top 5 or bottom 5 results.

Order By Docs: https://keen.io/docs/api/#order-by

Here's sample JavaScript to illustrate the newly added order_by API feature:

import Keen from 'keen-js';

const client = new Keen({
  projectId: 'PROJECT_ID',
  readKey: 'READ_KEY'
});

client
  .query('count', {
    event_collection: 'logins',
    group_by: 'user.email',
    order_by: {'property_name': 'result', 'direction': 'DESC'},
    limit: '5', //this limits your number of results
    timeframe: 'this_14_days'
  })
  .then(res => {
    // Handle results
  })
  .catch(err => {
    // Handle errors
  });

order_by and limit has been a top requested by customers - thank you for feedback to help with creating tools and features to Keen IO's API.


问:
seam-gen, netbeans and completion
How can I make seam-gen work with NetBeans 6.5 so that completion of tags (s:, ui:, rich:, ...) works? In the free-form project that seam-gen creates, this does not seam to work. If I create a standard NetBeans web application (File -> New Project), completion does work though.

Thanks,
m.

答: check your netbeans log. it's propobly facelet parser crashing on richaces taglib. i had this problem with RF v3.2.2, older release worked fine. </p>

OwnerDisplayName: msdfs

LastEditorDisplayName: Simucal

Title: seam-gen, netbeans and completion

OwnerDisplayName: yabcok


问:
How to get full URL on the address bar using PHP

Possible Duplicate:

  Get entire URL, including query string and anchor

I have my url like www.domain.com/#!/username (just like in twitter).

How can I retrieve the full URL (the whole string above) including the substring after '#!' in the address using PHP or Javascript??

答: The part after the hash  (#) is never sent to the server so you will never receive the "full" url back to PHP. The part after the # is only used on the client side and can only be sent from a server to the client.</p>


问:
Typescript React Error
I have the below webpack.config.js file :

```<code>module.exports = {
entry: "./Scripts/src/index.tsx",
output: {
    filename: "./wwwroot/Scripts/dist/bundle.js",
},

// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",

resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".scss",".css", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},

module: {
    rules: [
        // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
        { test: /\.tsx?$/, loader: "ts-loader" },
      {
  test: /\.s?css$/,
  use: [
    { loader: 'style-loader' },
    {
      loader: 'typings-for-css-modules-loader',
      options: {
        sass: false,
        modules: true,
        camelCase: true,
        importLoaders: 1,
        namedExport: true,
        localIdentName: '[name]__[local]__[hash:base64:5]',
      }
    },

  ]
},
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve('url-loader'),
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      { test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
      { test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
    ],

}
}
</code>```

I have the below tsconfig.json file:

```<code>{
"compilerOptions": {
"outDir": "./Scripts/",
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"lib": [ "es5", "es6", "dom" ]
},
"exclude": [
"node_modules",
"wwwroot"
]
</code>```

}

My Package.json looks like:

```<code>{
"name": "react-typescript-vs",
"version": "1.0.0",
"description": "React TypeScript VS 2017",
"main": "index.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "webpack"
},
"keywords": [
  "abhilash",
  "react",
  "typescript",
  "vs2017"
],
"author": "Abhilash D K",
"license": "ISC",
"dependencies": {
  "react": "^16.2.0",
  "react-dom": "^16.2.0",
  "react-scripts-ts": "2.8.0",
  "typed-css-modules-loader": "0.0.11",
  "typescript": "^2.6.2",
  "webpack": "^3.10.0"
},
"devDependencies": {
  "@types/jest": "^21.1.8",
  "@types/node": "^8.0.54",
  "@types/react": "^16.0.27",
  "@types/react-dom": "^16.0.3",
  "autoprefixer": "7.1.6",
  "case-sensitive-paths-webpack-plugin": "2.1.1",
  "chalk": "1.1.3",
  "css-loader": "0.28.7",
  "dotenv": "4.0.0",
  "eslint": "4.10.0",
  "eslint-config-react-app": "^2.0.1",
  "eslint-loader": "1.9.0",
  "eslint-plugin-flowtype": "2.39.1",
  "eslint-plugin-import": "2.8.0",
  "eslint-plugin-jsx-a11y": "5.1.1",
  "eslint-plugin-react": "7.4.0",
  "extract-text-webpack-plugin": "3.0.2",
  "file-loader": "1.1.5",
  "fs-extra": "3.0.1",
  "html-webpack-plugin": "2.29.0",
  "jest": "20.0.4",
  "object-assign": "4.1.1",
  "postcss-flexbugs-fixes": "3.2.0",
  "postcss-loader": "2.0.8",
  "promise": "8.0.1",
  "prop-types": "^15.6.0",
  "radium": "^0.19.6",
  "raf": "3.4.0",
  "react": "^16.1.0",
  "react-dev-utils": "^4.2.1",
  "react-dom": "^16.1.0",
  "sass-loader": "^6.0.6",
  "source-map-loader": "^0.2.3",
  "style-loader": "0.19.0",
  "sw-precache-webpack-plugin": "0.11.4",
  "ts-loader": "^3.2.0",
  "typings-for-css-modules-loader": "^1.7.0",
  "url-loader": "0.6.2",
  "webpack-manifest-plugin": "1.3.2",
  "whatwg-fetch": "2.0.3"
}
}
</code>```

I have a Scripts/src folder. Under which I have a components folder with Hello.tsx with below content :

```<code>import * as React from "react";
export interface IHelloProps {
    text: string;
}

export class Hello extends React.Component<IHelloProps, {}> {
    render() {
        return(<div>{this.props.text}</div>);
    }
}
</code>```

Under Scripts/src folder I have a index.tsx file with below content:

```<code>import * as React from "react";
import * as ReactDOM from "react-dom";
import { Hello } from "./components/Hello";

ReactDOM.render(
    <div>
        <Hello text="Hello from React Typescript...." />
    </div>,
    document.getElementById('app')
);
</code>```

Everything works fine. Now I will add Hello.css file with .textColor { color: azure } as it's content and i don't even use it. When I run webpack and try to access index.html I get the below error :

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

I tried adding module: commonjs as well as module : es6 to tsconfig.json. Still same error.

Could somebody explain me what is the problem and give me a solution for the same.

Thanks in Advance.

答:
Could have something to do with the way you are trying to import Hello.

Try:

```<code>import * as Hello from './components/Hello';
</code>```

Edit:

Sorry I just saw what is wrong here. What you are importing from hello is not a React Component, it is an object that holds all your classes. so in your case it would look something like:

```<code>{
  textColor: "referenceToActualClassName"
}
</code>```

So you wouldn't use it as:

```<code><Hello>
</code>```

but instead as

```<code><div className={Hello.textColor}></div>
</code>```

Let me know if that fixes it.

ANOTHER EDIT:

No...you probably do have a component there. The problem is your component file and styles file are both named Hello.

```<code>extensions: [".scss",".css", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
</code>```

Order matters here. So you are trying to import Hello from the css file. Be explicit with file extensions or rename the styles file to styles.css or theme.css or something.

Title: Typescript React Error

Body:
I have the below webpack.config.js file :

module.exports = {
entry: "./Scripts/src/index.tsx",
output: {
    filename: "./wwwroot/Scripts/dist/bundle.js",
},

// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",

resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".scss",".css", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},

module: {
    rules: [
        // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
        { test: /\.tsx?$/, loader: "ts-loader" },
      {
  test: /\.s?css$/,
  use: [
    { loader: 'style-loader' },
    {
      loader: 'typings-for-css-modules-loader',
      options: {
        sass: false,
        modules: true,
        camelCase: true,
        importLoaders: 1,
        namedExport: true,
        localIdentName: '[name]__[local]__[hash:base64:5]',
      }
    },

  ]
},
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve('url-loader'),
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      { test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
      { test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
    ],

}
}

I have the below tsconfig.json file:

{
"compilerOptions": {
"outDir": "./Scripts/",
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"lib": [ "es5", "es6", "dom" ]
},
"exclude": [
"node_modules",
"wwwroot"
]

}

My Package.json looks like:

{
"name": "react-typescript-vs",
"version": "1.0.0",
"description": "React TypeScript VS 2017",
"main": "index.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "webpack"
},
"keywords": [
  "abhilash",
  "react",
  "typescript",
  "vs2017"
],
"author": "Abhilash D K",
"license": "ISC",
"dependencies": {
  "react": "^16.2.0",
  "react-dom": "^16.2.0",
  "react-scripts-ts": "2.8.0",
  "typed-css-modules-loader": "0.0.11",
  "typescript": "^2.6.2",
  "webpack": "^3.10.0"
},
"devDependencies": {
  "@types/jest": "^21.1.8",
  "@types/node": "^8.0.54",
  "@types/react": "^16.0.27",
  "@types/react-dom": "^16.0.3",
  "autoprefixer": "7.1.6",
  "case-sensitive-paths-webpack-plugin": "2.1.1",
  "chalk": "1.1.3",
  "css-loader": "0.28.7",
  "dotenv": "4.0.0",
  "eslint": "4.10.0",
  "eslint-config-react-app": "^2.0.1",
  "eslint-loader": "1.9.0",
  "eslint-plugin-flowtype": "2.39.1",
  "eslint-plugin-import": "2.8.0",
  "eslint-plugin-jsx-a11y": "5.1.1",
  "eslint-plugin-react": "7.4.0",
  "extract-text-webpack-plugin": "3.0.2",
  "file-loader": "1.1.5",
  "fs-extra": "3.0.1",
  "html-webpack-plugin": "2.29.0",
  "jest": "20.0.4",
  "object-assign": "4.1.1",
  "postcss-flexbugs-fixes": "3.2.0",
  "postcss-loader": "2.0.8",
  "promise": "8.0.1",
  "prop-types": "^15.6.0",
  "radium": "^0.19.6",
  "raf": "3.4.0",
  "react": "^16.1.0",
  "react-dev-utils": "^4.2.1",
  "react-dom": "^16.1.0",
  "sass-loader": "^6.0.6",
  "source-map-loader": "^0.2.3",
  "style-loader": "0.19.0",
  "sw-precache-webpack-plugin": "0.11.4",
  "ts-loader": "^3.2.0",
  "typings-for-css-modules-loader": "^1.7.0",
  "url-loader": "0.6.2",
  "webpack-manifest-plugin": "1.3.2",
  "whatwg-fetch": "2.0.3"
}
}

I have a Scripts/src folder. Under which I have a components folder with Hello.tsx with below content :

import * as React from "react";
export interface IHelloProps {
    text: string;
}

export class Hello extends React.Component<IHelloProps, {}> {
    render() {
        return(
{this.props.text}
);
    }
}

Under Scripts/src folder I have a index.tsx file with below content:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { Hello } from "./components/Hello";

ReactDOM.render(

        <Hello text="Hello from React Typescript...." />

,
    document.getElementById('app')
);

Everything works fine. Now I will add Hello.css file with .textColor { color: azure } as it's content and i don't even use it. When I run webpack and try to access index.html I get the below error :

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

I tried adding module: commonjs as well as module : es6 to tsconfig.json. Still same error.

Could somebody explain me what is the problem and give me a solution for the same.

Thanks in Advance.

Body:
Could have something to do with the way you are trying to import Hello.

Try:

import * as Hello from './components/Hello';

Edit:

Sorry I just saw what is wrong here. What you are importing from hello is not a React Component, it is an object that holds all your classes. so in your case it would look something like:

{
  textColor: "referenceToActualClassName"
}

So you wouldn't use it as:

<Hello>

but instead as

<div className={Hello.textColor}></div>

Let me know if that fixes it.

ANOTHER EDIT:

No...you probably do have a component there. The problem is your component file and styles file are both named Hello.

extensions: [".scss",".css", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]

Order matters here. So you are trying to import Hello from the css file. Be explicit with file extensions or rename the styles file to styles.css or theme.css or something.


问:
how to download file with SFTP in Node from browser
I am trying to download some files using SFTP in Node. I know I have to handle the stream but I am not sure how I should do this and save the file in my local machine (in the downloads folder).

```<code>app.get('/download', (req, res) => {
    var Client = require('ssh2-sftp-client');
    var sftp = new Client();

    var config = {
        host: 'host123',
        port: '22',
        username: 'username',
        password: 'secretpassword'
    };

    sftp.connect(config).then((data) => {
        res.download(data);
    });
});
</code>```

Thanks!

答:
reference Download a file from NodeJS Server using Express

sftp.connect allow you stream data. you can pipe it to response

```<code>app.get('/download', (req, res) => {
                var Client = require('ssh2-sftp-client');
                var sftp = new Client();

    var config = {
            host: 'host123',
            port: '22',
            username: 'username',
            password: 'secretpassword'
    };

    sftp.connect(config)
    .then(()=>{
        return sftp.get(remoteFilePath, [useCompression], [encoding]);
    })
    .then((data) => {
            fs.createWriteStream(data).pipe(res);
    });
});
</code>```

Body:
I am trying to download some files using SFTP in Node. I know I have to handle the stream but I am not sure how I should do this and save the file in my local machine (in the downloads folder).

app.get('/download', (req, res) => {
    var Client = require('ssh2-sftp-client');
    var sftp = new Client();

    var config = {
        host: 'host123',
        port: '22',
        username: 'username',
        password: 'secretpassword'
    };

    sftp.connect(config).then((data) => {
        res.download(data);
    });
});

Thanks!

Body:
reference Download a file from NodeJS Server using Express

sftp.connect allow you stream data. you can pipe it to response

app.get('/download', (req, res) => {
                var Client = require('ssh2-sftp-client');
                var sftp = new Client();

    var config = {
            host: 'host123',
            port: '22',
            username: 'username',
            password: 'secretpassword'
    };

    sftp.connect(config)
    .then(()=>{
        return sftp.get(remoteFilePath, [useCompression], [encoding]);
    })
    .then((data) => {
            fs.createWriteStream(data).pipe(res);
    });
});


问:
Opening less connections with rethinkDB
My question is; Can i have less connections open when using rethindb? Right now I'm opening a new one every time I want to insert or get some data. Im afraid that this is not a right thing to do. Is there any way I can open just one and use it instead? I'm using nodejs.</p>

答:
I havent looked into the opensource connection pools for rethink, but I have a node app that uses rethink, and it will have a limited number of users, So I save my one connection to rethink as a global var and then use it for all queries.

```<code>'use strict';
var r = require('rethinkdb);
var rethinkConnect = null;
r.connect(
    {
        'host': 'localhost',
        'port': '28015',
        'password': 'noneya',
    },
    function(err, conn) {
        if (err) {
            console.log(err);
        } else {
            rethinkConnect = conn;
        }
    }
);
</code>```

Now all queries the node.js server makes can use the connection. Keep in mind this code is async so you could not immediately make a query the next line after r.connect(). You could, however, use the payload of an inbound socket.io event as the params of a rethink query.

Title: Opening less connections with rethinkDB

Body:
I havent looked into the opensource connection pools for rethink, but I have a node app that uses rethink, and it will have a limited number of users, So I save my one connection to rethink as a global var and then use it for all queries.

'use strict';
var r = require('rethinkdb);
var rethinkConnect = null;
r.connect(
    {
        'host': 'localhost',
        'port': '28015',
        'password': 'noneya',
    },
    function(err, conn) {
        if (err) {
            console.log(err);
        } else {
            rethinkConnect = conn;
        }
    }
);

Now all queries the node.js server makes can use the connection. Keep in mind this code is async so you could not immediately make a query the next line after r.connect(). You could, however, use the payload of an inbound socket.io event as the params of a rethink query.


问:
Converting List of Vectors to Data Frame in R
I'm trying to convert a list of vectors into a data frame, with there being a column for Company Names and column for the MPE. My list is generated by running the following code for each company:

```<code>MPE[[2]] <- c("Google", abs(((forecasted - goog[nrow(goog),]$close)
/ goog[nrow(goog),]$close)*100))
</code>```

Now, i'm having trouble making it into the appropriate data frame for further manipulation. What's the easiest way to do this?

This is an example list of vectors that I would want to manipulate into a dataframe with the company names in one column and the number in the second column.

```<code>test <- list(c("Google", 2))
test[[2]] <- c("Microsoft", 3)
test[[3]] <- c("Apple", 4)
</code>```

答:
I was actually able to achieve what I wanted with the following:</p>

```<code>MPE_df <- data.frame(Reduce(rbind ,MPE))
colnames(MPE_df) <- c("Company", "MPE")
MPE_df
</code>```

Body:
I'm trying to convert a list of vectors into a data frame, with there being a column for Company Names and column for the MPE. My list is generated by running the following code for each company:

MPE[[2]] <- c("Google", abs(((forecasted - goog[nrow(goog),]$close)
/ goog[nrow(goog),]$close)*100))

Now, i'm having trouble making it into the appropriate data frame for further manipulation. What's the easiest way to do this?

This is an example list of vectors that I would want to manipulate into a dataframe with the company names in one column and the number in the second column.

test <- list(c("Google", 2))
test[[2]] <- c("Microsoft", 3)
test[[3]] <- c("Apple", 4)

Body:
I was actually able to achieve what I wanted with the following:

MPE_df <- data.frame(Reduce(rbind ,MPE))
colnames(MPE_df) <- c("Company", "MPE")
MPE_df


问:
How do I get 2 different width divs right next to each other in a row?
I need to have an email layout where it has a header, and in the body will be two divs where one is 2/3rds the width of the main container div, and the other right next to it that will be 1/3rd the total width.

I also would like to know if there's a trick for making vertical rules, similar to horizontal rules we classically see.

Here's the code I was told to try, but I am not getting two divs next to each other inside the main container div:

```<code><html>
<head>
<meta charset="UTF-8">
<title>AUSA email</title>
</head>

<body style="font-family:sans-serif;"
      #wrapper {
    width: 500px;
    border: 1px solid black;
}
#first {
    width: 400px;
    border: 1px solid red;
}
#second {
    width: 200px;
    border: 1px solid green;
}></style>
    <div id="wrapper">
    <div id="first">Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.</div>
    <div id="second">Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.</div>
</div>
</body>

</html>
</code>```

答:
I think you're refering to setting the display to inline-block?</p>

```<code>#wrapper {
  width: 500px;
  border: 1px solid black;
}

#first {
  width: 300px;
  border: 1px solid red;
  display: inline-block;
}

#second {
  width: 200px;
  border: 1px solid green;
  display: inline-block;
}
</code>```

Body:
I need to have an email layout where it has a header, and in the body will be two divs where one is 2/3rds the width of the main container div, and the other right next to it that will be 1/3rd the total width.

I also would like to know if there's a trick for making vertical rules, similar to horizontal rules we classically see.

Here's the code I was told to try, but I am not getting two divs next to each other inside the main container div:

<meta charset="UTF-8">
<title>AUSA email</title>

</style>

Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.

Sample text. Sample text. Sample text. Sample text. Sample text. Sample text. Sample text.

Body:
I think you're refering to setting the display to inline-block?

#wrapper {
  width: 500px;
  border: 1px solid black;
}

#first {
  width: 300px;
  border: 1px solid red;
  display: inline-block;
}

#second {
  width: 200px;
  border: 1px solid green;
  display: inline-block;
}


问:
Why won't my Custom React Native Component Import Correctly
Currently, I have a simple React Native Expo app setup. I have two components App and QRreader.

I am trying to import the QRreader component into my main App component.

The Main App component code...

```<code>import React, { Component } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { Constants, WebBrowser } from 'expo';
import QRreader from './qr';

export default class App extends Component {
  state = {
    result: null,
  };

  render() {
    return (
      <View style={styles.container}>
        <QRreader/>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});
</code>```

The QR component code...

```<code>import React, { Component } from 'react';
import { Text, View, StyleSheet, Alert } from 'react-native';
import { Constants, BarCodeScanner, Permissions } from 'expo';

export default class QRreader extends Component {
  state = {
    hasCameraPermission: null
  };

  componentDidMount() {
    this._requestCameraPermission();
  }

  _requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  };

  _handleBarCodeRead = data => {
    Alert.alert(
      'Scan successful!',
      JSON.stringify(data)
    );
  };

  render() {
    return (
      <View style={styles.container}>
        {this.state.hasCameraPermission === null ?
          <Text>Requesting for camera permission</Text> :
          this.state.hasCameraPermission === false ?
            <Text>Camera permission is not granted</Text> :
            <BarCodeScanner
              onBarCodeRead={this._handleBarCodeRead}
              style={{ height: 200, width: 200 }}
            />
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  }
});
</code>```

I tried different variations of the import using "./" "." "qr.js" "qr"

Im getting an error Unable to resolve module "qr.js" Module does not exist in the main module map.

My file structure is Here

答:
You haven't registered your main module yet.

AppRegistry.registerComponent('Main', () => App); Please add this line to the bottom of your class and check if the problem persists.

Body:
Currently, I have a simple React Native Expo app setup. I have two components App and QRreader.

I am trying to import the QRreader component into my main App component.

The Main App component code...

import React, { Component } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { Constants, WebBrowser } from 'expo';
import QRreader from './qr';

export default class App extends Component {
  state = {
    result: null,
  };

  render() {
    return (
      <View style={styles.container}>
        <QRreader/>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

The QR component code...

import React, { Component } from 'react';
import { Text, View, StyleSheet, Alert } from 'react-native';
import { Constants, BarCodeScanner, Permissions } from 'expo';

export default class QRreader extends Component {
  state = {
    hasCameraPermission: null
  };

  componentDidMount() {
    this._requestCameraPermission();
  }

  _requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  };

  _handleBarCodeRead = data => {
    Alert.alert(
      'Scan successful!',
      JSON.stringify(data)
    );
  };

  render() {
    return (
      <View style={styles.container}>
        {this.state.hasCameraPermission === null ?
          <Text>Requesting for camera permission</Text> :
          this.state.hasCameraPermission === false ?
            <Text>Camera permission is not granted</Text> :
            <BarCodeScanner
              onBarCodeRead={this._handleBarCodeRead}
              style={{ height: 200, width: 200 }}
            />
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  }
});

I tried different variations of the import using "./" "." "qr.js" "qr"

Im getting an error Unable to resolve module "qr.js" Module does not exist in the main module map.

My file structure is Here


问:
R: how to use "get/assign" function in foreach?

I'm trying to use "get/assign" function inside "foreach".
A simplified case is here:

a1, a2, a3,...an (n can be any predefined number) are the objects saved in the global environment, and b is an array inside the loop used to store the objects.

*More complicated case could be a1, a2, a3,...an are large matrices, and try to use "get" plus index to retrieve cell value, such as   get(a1)[index]. The "sum" process could be a more complicated computation based on the array b.

My code is:

```<code>c <- foreach (j = 1:3) %dopar% {
    for (i in 1:n){
        b[i] <- get(paste("a",i,sep=""))
    }
    sum(b)
}
</code>```

I'm expecting the results like this:

```<code>for (j in 1:3) {
    for (i in 1:3){
        b[i] <- get(paste("a",i,sep=""))
    }
    c[i] = sum(b)
}
</code>```

However, the a1,a2,a3 have not been found

答:
I don't think you necessarily have a problem with get inside the foreach block. You have two loops here, so it's not clear where b is created. This is true for both code blocks. Also, foreach should be foreach(j=1:3)

Try adding b <- c() before the for(i in 1:3) statement.

```<code>library(foreach)
a1 <- 1
a2 <- 2
a3 <- 3
c <- foreach(j=1:3) %dopar% {
    b <- c()
        for (i in 1:3) {
            b[i] <- get(paste("a",i,sep=""))
        }
    sum(b)
}
</code>```

Body:
I'm trying to use "get/assign" function inside "foreach".
A simplified case is here:

a1, a2, a3,...an (n can be any predefined number) are the objects saved in the global environment, and b is an array inside the loop used to store the objects.

*More complicated case could be a1, a2, a3,...an are large matrices, and try to use "get" plus index to retrieve cell value, such as   get(a1)[index]. The "sum" process could be a more complicated computation based on the array b.

My code is:

c <- foreach (j = 1:3) %dopar% {
    for (i in 1:n){
        b[i] <- get(paste("a",i,sep=""))
    }
    sum(b)
}

I'm expecting the results like this:

for (j in 1:3) {
    for (i in 1:3){
        b[i] <- get(paste("a",i,sep=""))
    }
    c[i] = sum(b)
}

However, the a1,a2,a3 have not been found

Body:
I don't think you necessarily have a problem with get inside the foreach block. You have two loops here, so it's not clear where b is created. This is true for both code blocks. Also, foreach should be foreach(j=1:3)

Try adding b <- c() before the for(i in 1:3) statement.

library(foreach)
a1 <- 1
a2 <- 2
a3 <- 3
c <- foreach(j=1:3) %dopar% {
    b <- c()
        for (i in 1:3) {
            b[i] <- get(paste("a",i,sep=""))
        }
    sum(b)
}


问:
Silverlight does not support dynamic resources: what does this mean?
It is said here:
http://msdn.microsoft.com/en-us/library/cc903925(VS.95).aspx

Silverlight does not support dynamic resources. All resource references to keyed resources in XAML are static. For more information, see Resources Overview.

I looked at resources Overview but still don't understand what they mean. Can someone explain: does it mean I cannot xamlreader to change user intreface dynamically ?

答:
You can use XAML-Reader in silverlight to build dynamically changing interfaces. Set for example the ControlTemplate of a control to a ControlTemplate you have loaded or created with XamlReader.

However you can not change resources (for examle a ControlTemplate in a ResourceDictionary) during runtime and expect them to change the content in currently used elements.


问:
What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis in env laravel?
I use laravel 5.3

In my localhost, the env like this :

```<code>CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

In my production, the env like this :

```<code>CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

Almost all the same, just SESSION_DRIVER different

What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis?

答: SESSION_DRIVER define how Laravel will store sessions data, if you don't know/have redis, you should set this to "file".

Body:
I use laravel 5.3

In my localhost, the env like this :

CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

In my production, the env like this :

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Almost all the same, just SESSION_DRIVER different

What is the difference between SESSION_DRIVER=file and SESSION_DRIVER=redis?


问:
Error with hyperlink when viewed in excel

I am trying to generate excel file and my data is in the form of HTML string. The html string has hyperlinks(anchor tags) in them. the column 1 has a hyperlink and some text after that. however, when viewed in Excel, it makes all the text in that cell as hyperlink. Is it possible to restrict that. Open the below file in browser and it works fine. When opened in excel, it hyperlinks everything in that cell.

<!DOCTYPE html>

Visit our HTML tutorial
This is a sample text

column 2

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

<p>
<img src="https://i.stack.imgur.com/RnBDP.png" alt="enter image description here"></p>

```enter code here
```

答:
Are you just opening the .html file directly in Excel? If so, Excel is doing some conversion/interpreting work that we can't exactly see. It will be trial and error if this is the process you're using.

It is likely interpreting that  all as one cell, so it's styling the entire cell with the hyperlink. If you put "This is a sample text" in its own  so it's in a different cell, that is one way to fix it. You'll have three columns instead of two, but visually it would accomplish what you want.

If you want it in the same cell, I'm not certain if that is possible based on how Excel is interpreting it. I tried all sorts of things (putting the sample text in its own span or p tags, etc) but those placed it in a different row, but it seems like if it goes in the same cell as the link, Excel is going to style the entire cell that way.

If you use a method that gives you more control over the conversion (VBA, etc) then you may have more options.

Body:
I am trying to generate excel file and my data is in the form of HTML string. The html string has hyperlinks(anchor tags) in them. the column 1 has a hyperlink and some text after that. however, when viewed in Excel, it makes all the text in that cell as hyperlink. Is it possible to restrict that. Open the below file in browser and it works fine. When opened in excel, it hyperlinks everything in that cell.

<!DOCTYPE html>

Visit our HTML tutorial
This is a sample text

column 2

enter code here

Body:
Are you just opening the .html file directly in Excel? If so, Excel is doing some conversion/interpreting work that we can't exactly see. It will be trial and error if this is the process you're using.

It is likely interpreting that <td> all as one cell, so it's styling the entire cell with the hyperlink. If you put "This is a sample text" in its own <td> so it's in a different cell, that is one way to fix it. You'll have three columns instead of two, but visually it would accomplish what you want.

If you want it in the same cell, I'm not certain if that is possible based on how Excel is interpreting it. I tried all sorts of things (putting the sample text in its own span or p tags, etc) but those placed it in a different row, but it seems like if it goes in the same cell as the link, Excel is going to style the entire cell that way.

If you use a method that gives you more control over the conversion (VBA, etc) then you may have more options.


问:
Why does Sass incorrectly convert css content?
I have the following rule in my .scss file:

```<code>.listing-price:before {
   ...
   content: "♥";
</code>```

For whatever reason, running sass --update foo.scss:foo.css --style expanded converts it to:

```<code>.listing-price:before {
   ...
   content: "ΓÖÑ";
</code>```

Why does this happen and what do I need to do to prevent it?

答:
Sass should be auto-detecting character encoding on your documents. If not for some reason, you can explicitly set it to UTF-8 using @charset "UTF-8";

From the SASS docs:

When running on Ruby 1.9 and later, Sass is aware of the character encoding of documents. Sass follows the CSS spec to determine the encoding of a stylesheet, and falls back to the Ruby string encoding. This means that it first checks the Unicode byte order mark, then the @charset declaration, then the Ruby string encoding. If none of these are set, it will assume the document is in UTF-8.

To explicitly specify the encoding of your stylesheet, use a @charset declaration just like in CSS. Add @charset "encoding-name"; at the beginning of the stylesheet (before any whitespace or comments) and Sass will interpret it as the given encoding. Note that whatever encoding you use, it must be convertible to Unicode.

Sass will always encode its output as UTF-8. It will include a @charset declaration if and only if the output file contains non-ASCII characters. In compressed mode, a UTF-8 byte order mark is used in place of a @charset declaration.

```<code>@charset "UTF-8";
.listing-price:before {
    content: "♥";
}
</code>```

Demo:

https://www.sassmeister.com/gist/6326e75075795d1c265d26467c06518c

Docs:

http://sass-lang.com/documentation/file.SASS_REFERENCE.html

Body:
I have the following rule in my .scss file:

.listing-price:before {
   ...
   content: "♥";

For whatever reason, running sass --update foo.scss:foo.css --style expanded converts it to:

.listing-price:before {
   ...
   content: "ΓÖÑ";

Why does this happen and what do I need to do to prevent it?

Body:
Sass should be auto-detecting character encoding on your documents. If not for some reason, you can explicitly set it to UTF-8 using @charset "UTF-8";

From the SASS docs:

When running on Ruby 1.9 and later, Sass is aware of the character encoding of documents. Sass follows the CSS spec to determine the encoding of a stylesheet, and falls back to the Ruby string encoding. This means that it first checks the Unicode byte order mark, then the @charset declaration, then the Ruby string encoding. If none of these are set, it will assume the document is in UTF-8.

To explicitly specify the encoding of your stylesheet, use a @charset declaration just like in CSS. Add @charset "encoding-name"; at the beginning of the stylesheet (before any whitespace or comments) and Sass will interpret it as the given encoding. Note that whatever encoding you use, it must be convertible to Unicode.

Sass will always encode its output as UTF-8. It will include a @charset declaration if and only if the output file contains non-ASCII characters. In compressed mode, a UTF-8 byte order mark is used in place of a @charset declaration.

@charset "UTF-8";
.listing-price:before {
    content: "♥";
}

Demo:

https://www.sassmeister.com/gist/6326e75075795d1c265d26467c06518c

Docs:

http://sass-lang.com/documentation/file.SASS_REFERENCE.html


问:
Valgrind and global variables
I'm running valgrind to look for memory leaks. I have alloc'd two global variables in the main function; then, at the end of main I free both, but Valgrind keeps writing:

```<code>==18311== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A30C: main (application.c:730)
==18311==
==18311== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A31D: main (application.c:731)
</code>```

Leak summary:

```<code>==18311== LEAK SUMMARY:
==18311==    definitely lost: 32 bytes in 2 blocks
==18311==    indirectly lost: 0 bytes in 0 blocks
==18311==      possibly lost: 0 bytes in 0 blocks
==18311==    still reachable: 0 bytes in 0 blocks
==18311==         suppressed: 0 bytes in 0 blocks
</code>```

Why I can't free these two variables?

Edit

```<code>someList *something; *something_else;
</code>```

The struct used has two fields of type char * and a field someList *next.
Later there's a lot of code. A few threads are going to add/edit/delete objects using this two variables.

```<code>something -> object 1 -> ... -> object n
something_else -> object 1 -> ... -> object m
</code>```

Where -> means that something->next = object 1, and object k are all instances of someList *.

Near the end of the application, I freed every field of each object k element. Then, in the last part:

```<code>free(something);
free(something_else);
</code>```

It's possible that I forgot to free a field of an object. Can this cause the behavior I'm having here?

I hope it's clearer, now.

答:
For each malloc() call you typically need a corresponding free() call, in order to avoid memory leaks. For optimal memory usage, you should free() each allocated memory block as soon as possible after being done with it.

In your case, you have two malloc() calls in application.c:730 and application.c:731, for which there is no free() call made by the time your program terminates. Therefore, the memory blocks allocated there are not freed. This causes a memory leak that Valgrind detects and reports.

Unless you provide us with some code and/or more information on your program there is no way for us to help you more.

EDIT:

There are two interesting lines in your Valgrind output:

```<code>==18311==    definitely lost: 32 bytes in 2 blocks
...
==18311==    still reachable: 0 bytes in 0 blocks
</code>```

You have definitely "lost" two memory blocks and there no pointers to them at the time your program terminates. This means that the pointers to these two blocks were in fact overwritten or otherwise lost their value during the course of your program.

A common cause of this issue is storing the result of two malloc() calls to the same pointer without an intermediate free() call. Another possible cause is a changed pointer value due to pointer arithmetic operations - Valgrind makes an effort to detect some of these cases, but it is not always successful, depending on your code.

Title: Valgrind and global variables

Body:
I'm running valgrind to look for memory leaks. I have alloc'd two global variables in the main function; then, at the end of main I free both, but Valgrind keeps writing:

==18311== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A30C: main (application.c:730)
==18311==
==18311== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A31D: main (application.c:731)

Leak summary:

==18311== LEAK SUMMARY:
==18311==    definitely lost: 32 bytes in 2 blocks
==18311==    indirectly lost: 0 bytes in 0 blocks
==18311==      possibly lost: 0 bytes in 0 blocks
==18311==    still reachable: 0 bytes in 0 blocks
==18311==         suppressed: 0 bytes in 0 blocks

Why I can't free these two variables?

Edit

someList *something; *something_else;

The struct used has two fields of type char * and a field someList *next.
Later there's a lot of code. A few threads are going to add/edit/delete objects using this two variables.

something -> object 1 -> ... -> object n
something_else -> object 1 -> ... -> object m

Where -> means that something->next = object 1, and object k are all instances of someList *.

Near the end of the application, I freed every field of each object k element. Then, in the last part:

free(something);
free(something_else);

It's possible that I forgot to free a field of an object. Can this cause the behavior I'm having here?

I hope it's clearer, now.

Body:
For each malloc() call you typically need a corresponding free() call, in order to avoid memory leaks. For optimal memory usage, you should free() each allocated memory block as soon as possible after being done with it.

In your case, you have two malloc() calls in application.c:730 and application.c:731, for which there is no free() call made by the time your program terminates. Therefore, the memory blocks allocated there are not freed. This causes a memory leak that Valgrind detects and reports.

Unless you provide us with some code and/or more information on your program there is no way for us to help you more.

EDIT:

There are two interesting lines in your Valgrind output:

==18311==    definitely lost: 32 bytes in 2 blocks
...
==18311==    still reachable: 0 bytes in 0 blocks

You have definitely "lost" two memory blocks and there no pointers to them at the time your program terminates. This means that the pointers to these two blocks were in fact overwritten or otherwise lost their value during the course of your program.

A common cause of this issue is storing the result of two malloc() calls to the same pointer without an intermediate free() call. Another possible cause is a changed pointer value due to pointer arithmetic operations - Valgrind makes an effort to detect some of these cases, but it is not always successful, depending on your code.


问:
Using JavaScript to change were a link is pointing to based on screen size
I am creating a mobile-first site using the Bootstrap 4 framework. I am trying to create a JavaScript function which will change where a  tag is pointing to based upon the screen size of the browser. The following is just a very small portion of the HTML code for the page:

```<code><div class="col-md">
    <div id="accordion" class="form-group text-dark mt-3">
        <!-- Cold Card -->
        <div class="card">
            <!-- Cold Temps -->
            <!-- Temps include Make line temps, Refrigerator temps,
                 Freezer temps, and Beffet temps -->
            <div class="card-header">
                <a class="card-link"
                   data-toggle="collapse"
                   data-parent="#accordion"
                   href="#cold"
                   id="coldlink">
                    <h3>Cold Temps Management</h3>
                </a>
            </div>

            <!-- Cold Card -->
            <div class="collapse" id="cold">
</code>```

I have been trying several different JavaScript functions, and the following is the most recent set of functions which I have used:

```<code>const mq = window.matchMedia( "(min-width: 767px)");

if(mq.matches) {
    document.getElementById("coldlink").href = "#cold";
} else {
    document.getElementById("coldlink").href = "cold.php";
}
</code>```

From what I have read across many different sites, this code should change the href attribute of the element "coldlink" to "#cold" when the screen size is 767px or larger, and "cold.php" when it is smaller than 767px. Howerver, when I run this code (in the full page) and inspect the page using the developer tools, I get an error message saying "TypeError: document.getElementById(...) is null"

I have used the .getElementById(...) method in several other functions without getting this same error message so I do not know where I went wrong this time.

if there is a way to change the href attribute using Bootstrap, I would be more than willing to give it a shot as I have not discovered how to do this yet

答:
Instead of an href on your  you can do an on-click event
https://www.w3schools.com/jsref/event_onclick.asp

In your onclick function you can do

```<code>const mq = window.matchMedia( "(min-width: 767px)");

if (mq.matches) {
    window.location.href = "#cold";
} else {
    window.location.href = "cold.php";
}
</code>```

Body:
I am creating a mobile-first site using the Bootstrap 4 framework. I am trying to create a JavaScript function which will change where a  tag is pointing to based upon the screen size of the browser. The following is just a very small portion of the HTML code for the page:

Cold Temps Management

I have been trying several different JavaScript functions, and the following is the most recent set of functions which I have used:

const mq = window.matchMedia( "(min-width: 767px)");

if(mq.matches) {
    document.getElementById("coldlink").href = "#cold";
} else {
    document.getElementById("coldlink").href = "cold.php";
}

From what I have read across many different sites, this code should change the href attribute of the element "coldlink" to "#cold" when the screen size is 767px or larger, and "cold.php" when it is smaller than 767px. Howerver, when I run this code (in the full page) and inspect the page using the developer tools, I get an error message saying "TypeError: document.getElementById(...) is null"

I have used the .getElementById(...) method in several other functions without getting this same error message so I do not know where I went wrong this time.

if there is a way to change the href attribute using Bootstrap, I would be more than willing to give it a shot as I have not discovered how to do this yet

Body:
Instead of an href on your  you can do an on-click event
https://www.w3schools.com/jsref/event_onclick.asp

In your onclick function you can do

const mq = window.matchMedia( "(min-width: 767px)");

if (mq.matches) {
    window.location.href = "#cold";
} else {
    window.location.href = "cold.php";
}


问:
load image from url in tableview cell from alamofire swift
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

```<code>{"name": {"image": "https://...",}}
</code>```

Alamorefire and SwiftyJSON

```<code>var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"
</code>```

If anyone can help? If there is another way feel free to write.

答:
I recommend using a different library for loading the images. We always do this in our projects.

There is an easy and smart library which handles pretty much everything from caching to placeholder image.

It's name is Kingfisher
https://github.com/onevcat/Kingfisher

You can use it directly on the ImageView with the URL from JSON
Example:

```<code>let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
</code>```

This is the most basic Asynchronous image loading method,

Take a look for yourself :)

Body:
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

{"name": {"image": "https://...",}}

Alamorefire and SwiftyJSON

var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"

If anyone can help? If there is another way feel free to write.

Body:
I recommend using a different library for loading the images. We always do this in our projects.

There is an easy and smart library which handles pretty much everything from caching to placeholder image.

It's name is Kingfisher
https://github.com/onevcat/Kingfisher

You can use it directly on the ImageView with the URL from JSON
Example:

let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)

This is the most basic Asynchronous image loading method,

Take a look for yourself :)


问:
VLOOKUP to condense data into one cell
I'm trying to create a macro that takes a user's input and shortens it into an abbreviated code. Say a user has inputted the data into the table:

The macro would run and output the abbreviated code based on this table (in this case, outputting "BLK190_G16_WFUR12"):

```<code>Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.CountIf("B16:B25", "*")

' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount
    abbrev = Application.VLookup(Range("B" & materialnum), info.Range("C2:D20"), 1, False)
    newCode = abbrev & Range("C" & materialnum)

    x = x + 1
    materialnum = materialnum + 1

    Range("E16") = Range("E16") & newCode & "_" 'Output string of text into cell E16
    Loop

End Sub
</code>```

If anyone could please help me out, I'd really appreciate it.

答:
```<code>Sub InputToAbbreviation()
    Dim References As Range, Materials As Range
    Dim reference, material As Range, code As String

    Set References = Range("C2:D20")
    Set Materials = Range("B16:B" & Range("B16").End(xlDown).Row)

    For Each material In Materials
        code = code & Application.VLookup(material, References, 2, False) & material.Offset(0, 1) & "_"
    Next

    Debug.Print Left$(code, Len(code) - 1) //Remove trailing '_'
End Sub
</code>```

Notes:

Re-order your code table to description is in the first column, code the second

Assumes code descriptions in range C2:D20

Assumes user inputs material and thickness in row 16 (as your code suggests)

Title: VLOOKUP to condense data into one cell

Body:
I'm trying to create a macro that takes a user's input and shortens it into an abbreviated code. Say a user has inputted the data into the table:

The macro would run and output the abbreviated code based on this table (in this case, outputting "BLK190_G16_WFUR12"):

Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.CountIf("B16:B25", "*")

' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount
    abbrev = Application.VLookup(Range("B" & materialnum), info.Range("C2:D20"), 1, False)
    newCode = abbrev & Range("C" & materialnum)

    x = x + 1
    materialnum = materialnum + 1

    Range("E16") = Range("E16") & newCode & "_" 'Output string of text into cell E16
    Loop

End Sub

If anyone could please help me out, I'd really appreciate it.

Body:
Sub InputToAbbreviation()
    Dim References As Range, Materials As Range
    Dim reference, material As Range, code As String

    Set References = Range("C2:D20")
    Set Materials = Range("B16:B" & Range("B16").End(xlDown).Row)

    For Each material In Materials
        code = code & Application.VLookup(material, References, 2, False) & material.Offset(0, 1) & "_"
    Next

    Debug.Print Left$(code, Len(code) - 1) //Remove trailing '_'
End Sub

Notes:

Re-order your code table to description is in the first column, code the second

Assumes code descriptions in range C2:D20

Assumes user inputs material and thickness in row 16 (as your code suggests)


答:
Set

```<code>@charset "utf-8";
</code>```

at the top of your scss files where you use characters in the UTF range

https://github.com/sass/sass/issues/1663

Title: Why does Sass incorrectly convert css content?

Body:
Set

@charset "utf-8";

at the top of your scss files where you use characters in the UTF range

https://github.com/sass/sass/issues/1663


问:
Ionic build android, Error: spawn EACCES
If I follow this steps to create a new app:

```<code>Rubens-MacBook-Pro:~ rlopez$ npm install -g cordova ionic
Rubens-MacBook-Pro:~ rlopez$ ionic start myApp tabs
Rubens-MacBook-Pro:~ rlopez$ cd myApp
Rubens-MacBook-Pro:myApp rlopez$  ionic platform add android@6.2.2 //6.1.x has a bug
Rubens-MacBook-Pro:myApp rlopez$  ionic build android
</code>```

I get this output:

```<code>> ionic-hello-world@ ionic:build /Users/rlopez/Proyectos/sfp-concursaPy
> ionic-app-scripts build

[15:13:28]  ionic-app-scripts 1.1.4
[15:13:28]  build dev started ...
[15:13:28]  clean started ...
[15:13:28]  clean finished in 3 ms
[15:13:28]  copy started ...
[15:13:28]  transpile started ...
[15:13:31]  transpile finished in 2.96 s
[15:13:31]  preprocess started ...
[15:13:31]  preprocess finished in less than 1 ms
[15:13:31]  webpack started ...
[15:13:31]  copy finished in 3.17 s
[15:13:41]  webpack finished in 9.26 s
[15:13:41]  sass started ...
[15:13:41]  sass finished in 897 ms
[15:13:41]  postprocess started ...
[15:13:41]  postprocess finished in 1 ms
[15:13:41]  lint started ...
[15:13:41]  build dev finished in 13.15 s
[15:13:43]  lint finished in 2.04 s
ANDROID_HOME=/Users/rlopez/Library/Android/sdk

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home

Error: spawn EACCES
</code>```

Running ionic info gives the following:

```<code>Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.6
ios-deploy version: 1.8.5
ios-sim version: 5.0.13
OS: OS X El Capitan
Node Version: v6.10.1
Xcode version: Xcode 7.3.1 Build version 7D1014
</code>```

What am I doign wrong? Is this a bug in Ionic?

[Edit]

Running ionic build android --verbose gives the following output:

```<code>Running command: "/Applications/Android Studio 2.4
Preview.app/Contents/gradle/gradle-3.4.1/bin/gradle" -p
/Users/rlopez/myApp/platforms/android wrapper -b
/Users/rlopez/myApp/platforms/android/wrapper.gradle

Error: spawn EACCES
    at exports._errnoException (util.js:1018:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at Object.exports.spawn (child_process.js:378:9)
    at exports.spawn(/Users/rlopez/myApp/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:134:31)
    at GradleBuilder.runGradleWrapper(/Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:78:14)
    at /Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:178:21
    at _fulfilled (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:816:13)
    at /Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:570:49
</code>```

答:
```<code>sudo chmod 755 /Applications/Android\ Studio.app/Contents/gradle/gradle-4.1/bin/gradle
</code>```

Body:
If I follow this steps to create a new app:

Rubens-MacBook-Pro:~ rlopez$ npm install -g cordova ionic
Rubens-MacBook-Pro:~ rlopez$ ionic start myApp tabs
Rubens-MacBook-Pro:~ rlopez$ cd myApp
Rubens-MacBook-Pro:myApp rlopez$  ionic platform add android@6.2.2 //6.1.x has a bug
Rubens-MacBook-Pro:myApp rlopez$  ionic build android

I get this output:

> ionic-hello-world@ ionic:build /Users/rlopez/Proyectos/sfp-concursaPy
> ionic-app-scripts build

[15:13:28]  ionic-app-scripts 1.1.4
[15:13:28]  build dev started ...
[15:13:28]  clean started ...
[15:13:28]  clean finished in 3 ms
[15:13:28]  copy started ...
[15:13:28]  transpile started ...
[15:13:31]  transpile finished in 2.96 s
[15:13:31]  preprocess started ...
[15:13:31]  preprocess finished in less than 1 ms
[15:13:31]  webpack started ...
[15:13:31]  copy finished in 3.17 s
[15:13:41]  webpack finished in 9.26 s
[15:13:41]  sass started ...
[15:13:41]  sass finished in 897 ms
[15:13:41]  postprocess started ...
[15:13:41]  postprocess finished in 1 ms
[15:13:41]  lint started ...
[15:13:41]  build dev finished in 13.15 s
[15:13:43]  lint finished in 2.04 s
ANDROID_HOME=/Users/rlopez/Library/Android/sdk

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home

Error: spawn EACCES

Running ionic info gives the following:

Your system information:

Cordova CLI: 6.5.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.6
ios-deploy version: 1.8.5
ios-sim version: 5.0.13
OS: OS X El Capitan
Node Version: v6.10.1
Xcode version: Xcode 7.3.1 Build version 7D1014

What am I doign wrong? Is this a bug in Ionic?

[Edit]

Running ionic build android --verbose gives the following output:

Running command: "/Applications/Android Studio 2.4
Preview.app/Contents/gradle/gradle-3.4.1/bin/gradle" -p
/Users/rlopez/myApp/platforms/android wrapper -b
/Users/rlopez/myApp/platforms/android/wrapper.gradle

Error: spawn EACCES
    at exports._errnoException (util.js:1018:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at Object.exports.spawn (child_process.js:378:9)
    at exports.spawn(/Users/rlopez/myApp/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:134:31)
    at GradleBuilder.runGradleWrapper(/Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:78:14)
    at /Users/rlopez/myApp/platforms/android/cordova/lib/builders/GradleBuilder.js:178:21
    at _fulfilled (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:854:54)
    at self.promiseDispatch.done (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:883:30)
    at Promise.promise.promiseDispatch (/Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:816:13)
    at /Users/rlopez/myApp/platforms/android/cordova/node_modules/q/q.js:570:49