问:
how to give permissions for different users

permission.json

"appUser": {
        "user": {
            "read": true,
            "write": false
        },
        "packages": {
            "read": true,
            "write": false
        },
        "user_package": {
            "read": true,
            "write": false
        },
        "roles": {
            "read": true,
            "write": false
        },
        "user_detail": {
            "read": true,
            "write": false
        },
        "role_mapping": {
            "read": true,
            "write": false
        },
        "guide": {
            "read": true,
            "write": false
        },
        "guide_categories": {
            "read": true,
            "write": false
        },
        "follow_guides": {
            "read": true,
            "write": false
        },
        "pin": {
            "read": true,
            "write": false
        },
        "fav_pins": {
            "read": true,
            "write": false
        },
        "pin_guides": {
            "read": true,
            "write": false
        },
        "pin_media": {
            "read": true,
            "write": false
        },
        "category": {
            "read": true,
            "write": false
        },
        "pin_categories": {
            "read": true,
            "write": false
        },
        "company_details": {
            "read": true,
            "write": false
        },
        "person_details": {
            "read": true,
            "write": false
        },
        "interview": {
            "read": true,
            "write": false
        },
        "guide_media": {
            "read": true,
            "write": false
        },
        "thread": {
            "read": true,
            "write": false
        },
        "tutorial": {
            "read": true,
            "write": false
        },
        "comments": {
            "read": true,
            "write": false
        }
    }```
</div>
</div>
</p>

<h2>auth.js</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function verifyToken(req, res, next) {
    var func = req.query.function;
    var token = req.headers['token'];
    if (!token) {
        return res.status(401).send({
            status: 401,
            data: 'No token provided.'
        });
    }
    db.query('SELECT * FROM users WHERE token = $1', [token], function(err, data) {
        if (err) return next(err);
        db.query('SELECT role_name FROM roles r inner join role_mapping rm on r._id = rm.role_id WHERE rm.user_id = $1', [data.rows[0]._id], function(err, result) {
            if (err) return next(err);
            for(i in permission) {
                if(i == result.rows[0].role_name)
                    if(i.func.read == true)
                        console.log('you have permission');
                    console.log('you dnt have permisstion write');
            }
            if (data.rows.length == 0) {
                return res.status(404).send({
                    status: 404,
                    data: 'Failed to authenticate token.'
                });
            } else {
                next();
            }
        });
    });
}</code>```

I am trying to check the permission of user and I have found the role(appUser) of the user using this for(i in permission) {
   if(i == result.rows[0].role_name).

I am passing user,packages,user_packages etc as query parameters but my question is how can I get that the user has read permission on this table??
I have admin, appUser and businessUser as roles. I want to give different permissions for these three users.

答:
You also need to loop also to the properties of each table. (loop to read write nodes)

```<code>for (i in permission) { //loop tru the users
  for (j in permission[i]) { //loop tru the table permission matrix of each user
    if (j == req.query.your_query_name_of_table) { //condition for specific table
      for (k in permission[i][j]) { //loop tru properties of the table
        if (k == "read") { //because u want to check read permission only
           if (permission[i][j][k]) { //because your value is boolean
             console.log(i + " have permission to " + k + " on " + j);
           } else {
             console.log(i + " dont have permission " + k + " on " + j);
           }
        }
      }
    }
  }
}
</code>```

Output:

appUser have permission to read on user

OR if read is false:

Output:

appUser dont have permission to read on user

Body:
permission.json

"appUser": {
        "user": {
            "read": true,
            "write": false
        },
        "packages": {
            "read": true,
            "write": false
        },
        "user_package": {
            "read": true,
            "write": false
        },
        "roles": {
            "read": true,
            "write": false
        },
        "user_detail": {
            "read": true,
            "write": false
        },
        "role_mapping": {
            "read": true,
            "write": false
        },
        "guide": {
            "read": true,
            "write": false
        },
        "guide_categories": {
            "read": true,
            "write": false
        },
        "follow_guides": {
            "read": true,
            "write": false
        },
        "pin": {
            "read": true,
            "write": false
        },
        "fav_pins": {
            "read": true,
            "write": false
        },
        "pin_guides": {
            "read": true,
            "write": false
        },
        "pin_media": {
            "read": true,
            "write": false
        },
        "category": {
            "read": true,
            "write": false
        },
        "pin_categories": {
            "read": true,
            "write": false
        },
        "company_details": {
            "read": true,
            "write": false
        },
        "person_details": {
            "read": true,
            "write": false
        },
        "interview": {
            "read": true,
            "write": false
        },
        "guide_media": {
            "read": true,
            "write": false
        },
        "thread": {
            "read": true,
            "write": false
        },
        "tutorial": {
            "read": true,
            "write": false
        },
        "comments": {
            "read": true,
            "write": false
        }
    }

auth.js

function verifyToken(req, res, next) {
    var func = req.query.function;
    var token = req.headers['token'];
    if (!token) {
        return res.status(401).send({
            status: 401,
            data: 'No token provided.'
        });
    }
    db.query('SELECT * FROM users WHERE token = $1', [token], function(err, data) {
        if (err) return next(err);
        db.query('SELECT role_name FROM roles r inner join role_mapping rm on r._id = rm.role_id WHERE rm.user_id = $1', [data.rows[0]._id], function(err, result) {
            if (err) return next(err);
            for(i in permission) {
                if(i == result.rows[0].role_name)
                    if(i.func.read == true)
                        console.log('you have permission');
                    console.log('you dnt have permisstion write');
            }
            if (data.rows.length == 0) {
                return res.status(404).send({
                    status: 404,
                    data: 'Failed to authenticate token.'
                });
            } else {
                next();
            }
        });
    });
}

I am trying to check the permission of user and I have found the role(appUser) of the user using this for(i in permission) {
   if(i == result.rows[0].role_name).

I am passing user,packages,user_packages etc as query parameters but my question is how can I get that the user has read permission on this table??
I have admin, appUser and businessUser as roles. I want to give different permissions for these three users.

Body:
You also need to loop also to the properties of each table. (loop to read write nodes)

for (i in permission) { //loop tru the users
  for (j in permission[i]) { //loop tru the table permission matrix of each user
    if (j == req.query.your_query_name_of_table) { //condition for specific table
      for (k in permission[i][j]) { //loop tru properties of the table
        if (k == "read") { //because u want to check read permission only
           if (permission[i][j][k]) { //because your value is boolean
             console.log(i + " have permission to " + k + " on " + j);
           } else {
             console.log(i + " dont have permission " + k + " on " + j);
           }
        }
      }
    }
  }
}

Output:

appUser have permission to read on user

OR if read is false:

Output:

appUser dont have permission to read on user


来源: stackexchange

问:
Regex match the words from a string without the start and end space
I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

```<code>"word , word , two words, word"
</code>```

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

```<code>["word","word","two words","word"]
</code>```

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

```<code>match(/[^(,)]+/g)
</code>```

and using map to remove all the spaces from the resulting array:

```<code>map(value => value.trim());
</code>```

But would like to do it only through regular expression and have no idea how to do it.

答:
You can apply the following regex:

```<code>(\w+\s*\w+)
</code>```

that matches

1 or more word character(s) followed by

0 to N white characters (whitespace character: space, tab, newline, carriage return, vertical tab) followed by

1 or more word character(s).

http://www.rexegg.com/regex-quickstart.html

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

"word , word , two words, word"

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

["word","word","two words","word"]

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

match(/[^(,)]+/g)

and using map to remove all the spaces from the resulting array:

map(value => value.trim());

But would like to do it only through regular expression and have no idea how to do it.

Body:
You can apply the following regex:

(\w+\s*\w+)

that matches

1 or more word character(s) followed by

0 to N white characters (whitespace character: space, tab, newline, carriage return, vertical tab) followed by

1 or more word character(s).

http://www.rexegg.com/regex-quickstart.html


答:
You can just split on comma surrounded by optional spaces on either side:

var str = "word , , word , two words, word";

var arr = str.split(/(?:\s*,\s*)+/);

console.log(arr);

//=> ["word", "word", "two words", "word"]```

Title: Regex match the words from a string without the start and end space


问:
how can my button open a new tab?
I have a basic jquery issue. Just trying to make this link open in a new tab/window. I have added _blank but it does not go to a new page. Any ideas?

   $('#link13').click(function() {

    window.location.href= 'https://www.google.com','_blank';

  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary" id="link13">See the Resources</button></code>```

答:
```<code>$('#link13').click(function() {
    window.open(
      'https://www.google.com',
      '_blank' // <- This is what makes it open in a new window.
    );
});
</code>```

Title: how can my button open a new tab?

Body:
I have a basic jquery issue. Just trying to make this link open in a new tab/window. I have added _blank but it does not go to a new page. Any ideas?

   $('#link13').click(function() {

    window.location.href= 'https://www.google.com','_blank';

  });

<button type="button" class="btn btn-primary" id="link13">See the Resources</button>


问:
BeautifulSoup find a data-reactid
I have a python script using beautifulsoup to scrape a property sales website.
I am trying to get the number of beds from the HTML.

The data-reactid changes for each listing in the search results. The number $11606747 is unique.
I am trying to wild card search for "*$beds.0.0" to return the number of beds =3 in the example.

There is no error message, and the code runs but doesn't return the number.

What am I doing wrong?

The HTML:

```<code><div class="property-features is-regular listing-result__features" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2"><span class="property-feature__feature" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds"><span class="property-feature__feature-text-container" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0"><span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.0">3</span><span data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.1"> </span><span class="property-features__feature-text" data-reactid=".1e881obdfqe.3.1.3.1:$11606747.0.1.0.2.$beds.0.2">Beds</span></span>
</code>```

The Python code

```<code>beds = listing.findAll('span',{"data-reactid":re.compile('*$beds.0.0')})
</code>```

答:
You need to escape symbols $, . and *, because they are special in regex:

```<code>re.compile(r'\*\$beds\.0\.0')
</code>```

Title: BeautifulSoup find a data-reactid

Body:
I have a python script using beautifulsoup to scrape a property sales website.
I am trying to get the number of beds from the HTML.

The data-reactid changes for each listing in the search results. The number $11606747 is unique.
I am trying to wild card search for "*$beds.0.0" to return the number of beds =3 in the example.

There is no error message, and the code runs but doesn't return the number.

What am I doing wrong?

The HTML:

3 Beds

The Python code

beds = listing.findAll('span',{"data-reactid":re.compile('*$beds.0.0')})

Body:
You need to escape symbols $, . and *, because they are special in regex:

re.compile(r'\*\$beds\.0\.0')


答:
This might be what you're looking for with capture groups, so iterate over \1</p>

```<code>\s*([\w\s]+)\s*
</code>```

Body:
This might be what you're looking for with capture groups, so iterate over \1

\s*([\w\s]+)\s*


问:
passing array to Constructor function and keep it public
here is my code :

```<code>var BoxUtility = function() {
    var boxList = Array.prototype.pop.apply(arguments);
};

Object.defineProperties(BoxUtility, {
    totalArea: {
        value: function(){
           var x = 0;
           for(var i = 0, len = boxList.length; i <= len - 1; i++){
              x = x + boxList[i].area;
           };
        return x;
        }
     }
});
</code>```

I'm trying to achieve this syntax for my Code :

```<code>var boxArray = [box01, box02, box03];
</code>```

box are objects, box01.area => boxes have area property

```<code>var newElement = new BoxUtility(boxArray);
alert(newElement.totalArea);
</code>```

I WANT TO SEE THE RESULT AS I EXPECT but I think boxList is in another scope

How can I reach it in defineProperties

答:
This is simple way to pass array as argument in constructer and declare function prototype for public access.</p>

```<code> function BoxUtility(boxArray) {
     this.boxArray = boxArray;
     this.len = boxArray.length;

  }
 Color.prototype.getAverage = function () {
      var sum = 0;
      for(let i = 0;i<this.len;i++){
       sum+=this.boxArray[i];

  }
   return parseInt(sum);
};

var red = new BoxUtility(boxArray);

alert(red.getAverage());
</code>```

Body:
here is my code :

var BoxUtility = function() {
    var boxList = Array.prototype.pop.apply(arguments);
};

Object.defineProperties(BoxUtility, {
    totalArea: {
        value: function(){
           var x = 0;
           for(var i = 0, len = boxList.length; i <= len - 1; i++){
              x = x + boxList[i].area;
           };
        return x;
        }
     }
});

I'm trying to achieve this syntax for my Code :

var boxArray = [box01, box02, box03];

box are objects, box01.area => boxes have area property

var newElement = new BoxUtility(boxArray);
alert(newElement.totalArea);

I WANT TO SEE THE RESULT AS I EXPECT but I think boxList is in another scope

How can I reach it in defineProperties

Body:
This is simple way to pass array as argument in constructer and declare function prototype for public access.

 function BoxUtility(boxArray) {
     this.boxArray = boxArray;
     this.len = boxArray.length;

  }
 Color.prototype.getAverage = function () {
      var sum = 0;
      for(let i = 0;i<this.len;i++){
       sum+=this.boxArray[i];

  }
   return parseInt(sum);
};

var red = new BoxUtility(boxArray);

alert(red.getAverage());


问:
how to remove the ability of a guest VM to utilize the RDRAND instruction?
If a hypervisor  wishes to remove the ability of a guest VM to utilize the
RDRAND instruction, what steps must it take to achieve this</p>

答:
Yes, Intel VMX hardware virtualization has hardware support for making rdrand and rdseed to a VM exit.

For example, see discussion on the Linux kernel mailing list about patching KVM (the hypervisor built-in to Linux):

A guest may not be configured to support RDSEED, even when the host
  does. If the guest does not support RDSEED, intercept the instruction
  and synthesize #UD. Also clear the "allowed-1" bit for RDSEED exiting
  in the IA32_VMX_PROCBASED_CTLS2 MSR.

The relevant VMX ctrls are SECONDARY_EXEC_RDRAND_EXITING and SECONDARY_EXEC_RDSEED_EXITING.  (See this patch that renamed them in the KVM source code to match what Intel calls them in their x86 Software Development Manuals (SDM), where you should find further details of how to program VMX to do what you want.)

I just used links to KVM stuff because it's what came up first on Google when I was checking to see if there was HW support for this at all.


问:
Declaring new variables inside class methods
I just read about class and method variables in Python, and I am wondering if there is a difference between these two examples:

```<code>class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c

class Example2(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        self.c = self.a + self.b
        return self.c
</code>```

Basically if I do:

```<code>print Example(3,4).Add()
print Example2(3,4).Add()
</code>```

I get the same result:

```<code>7
7
</code>```

So my questions are:

What is the difference between self.c = self.a + self.b and c = self.a + self.b?

Should all new variables declared inside classes be declared with the self statement?

Thanks for any help!

答:
```<code>class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c
</code>```

Suppose if we create a instance x=Example().

If we try to accces c using x.c . We would get following error

AttributeError: 'Example' object has no attribute 'c'.

Body:
I just read about class and method variables in Python, and I am wondering if there is a difference between these two examples:

class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c

class Example2(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        self.c = self.a + self.b
        return self.c

Basically if I do:

print Example(3,4).Add()
print Example2(3,4).Add()

I get the same result:

7
7

So my questions are:

What is the difference between self.c = self.a + self.b and c = self.a + self.b?

Should all new variables declared inside classes be declared with the self statement?

Thanks for any help!

Body:
class Example(object):
    def __init__(self, nr1, nr2):
        self.a = nr1
        self.b = nr2

    def Add(self):
        c = self.a + self.b
        return c

Suppose if we create a instance x=Example().

If we try to accces c using x.c . We would get following error

AttributeError: 'Example' object has no attribute 'c'.


问:
read() with Keysets, ranges
I've started playing around with the Spanner Python client (on appengine flex), but I'm hitting a few walls when trying to reuse the doc examples.
One issue I'm facing is trying to read the database:

execute_sql() returns empty sets (even with a simple 'SELECT 1' query)

```<code>with database.snapshot() as snapshot:
QUERY = ('SELECT 1')
result = snapshot.execute_sql(QUERY)
for row in result.rows:
    print(row)
</code>```

read() returns a "AttributeError: 'list' object has no attribute 'to_pb'" error, whether I

try to build the whole keyset as a dictionary

```<code>keyset = {'keys': ['f0_'],
          'ranges': [{'startClosed': [], 'endClosed': [500]}],
          'all': False}
</code>```

passing value lists directly

```<code>keyset = [0, 1, 2]
</code>```

and an attempt at using the Keyset() constructor tells me that spanner does not have a keyset member
AttributeError: 'module' object has no attribute 'keyset'

```<code>keys = ['f0_']
ranges = spanner.keyset.KeyRange(start_closed=[], end_closed=[500])
keyset = {
    'keys': keys,
    'ranges': ranges,
    'all': False}
keyset = spanner.keyset.Keyset(keys=keys, ranges=[range])
</code>```

So I'm a bit stuck, and I'm wondering whether there's something I'm doing wrong or the examples / docs need a bit of spolishing...
Any help appreciated :)

答:
Sorry for the late response, but you can use the KeyRange and Keyset like so.  Also, .consume_all() is likely to be private in the future.  You should instead use list to get the answers that you want.

```<code>...
range = spanner.KeyRange(start_closed=[START], end_closed=[END])
keyset = spanner.KeySet(ranges=(closed_closed,))
rows = list(snapshot.read(self.TABLE, self.COLUMNS, keyset))
...
</code>```

Title: read() with Keysets, ranges

Body:
I've started playing around with the Spanner Python client (on appengine flex), but I'm hitting a few walls when trying to reuse the doc examples.
One issue I'm facing is trying to read the database:

execute_sql() returns empty sets (even with a simple 'SELECT 1' query)

with database.snapshot() as snapshot:
QUERY = ('SELECT 1')
result = snapshot.execute_sql(QUERY)
for row in result.rows:
    print(row)

read() returns a "AttributeError: 'list' object has no attribute 'to_pb'" error, whether I

try to build the whole keyset as a dictionary

keyset = {'keys': ['f0_'],
          'ranges': [{'startClosed': [], 'endClosed': [500]}],
          'all': False}

passing value lists directly

keyset = [0, 1, 2]

and an attempt at using the Keyset() constructor tells me that spanner does not have a keyset member
AttributeError: 'module' object has no attribute 'keyset'

keys = ['f0_']
ranges = spanner.keyset.KeyRange(start_closed=[], end_closed=[500])
keyset = {
    'keys': keys,
    'ranges': ranges,
    'all': False}
keyset = spanner.keyset.Keyset(keys=keys, ranges=[range])

So I'm a bit stuck, and I'm wondering whether there's something I'm doing wrong or the examples / docs need a bit of spolishing...
Any help appreciated :)

Body:
Sorry for the late response, but you can use the KeyRange and Keyset like so.  Also, .consume_all() is likely to be private in the future.  You should instead use list to get the answers that you want.

...
range = spanner.KeyRange(start_closed=[START], end_closed=[END])
keyset = spanner.KeySet(ranges=(closed_closed,))
rows = list(snapshot.read(self.TABLE, self.COLUMNS, keyset))
...


问:
How to access only the related model with eager loading
I have these models in my project:

```<code>class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}
</code>```

-

```<code>class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}
</code>```

-

```<code>class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}
</code>```

When I try to get the user's favorites i will do like this:-

```<code>$user = User::find(1);
return $user->favorites;
</code>```

Or with the products in his favorites:-

```<code>return $user->favorites->load('product');
</code>```

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

```<code>public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}
</code>```

Thank you in advance.

答:
try this:
in your case, i think it is a Nested Eager Loading

```<code>$user = User::with('favorites.product')->get();
//to grab the data
dd($user->favorites[0]->product);
</code>```

hope it is help

Body:
I have these models in my project:

class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}

-

class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

-

class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}

When I try to get the user's favorites i will do like this:-

$user = User::find(1);
return $user->favorites;

Or with the products in his favorites:-

return $user->favorites->load('product');

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}

Thank you in advance.

Body:
try this:
in your case, i think it is a Nested Eager Loading

$user = User::with('favorites.product')->get();
//to grab the data
dd($user->favorites[0]->product);

hope it is help


问:
Parse same JSON String Multiple Times in python
I need to parse the following json output, so I can take parse the Title entries

```<code>[{"Title":"000webhost","Name":"000webhost","Domain":"000webhost.com","BreachDate":"2015-03-01","AddedDate":"2015-10-26T23:35:45Z","ModifiedDate":"2015-10-26T23:35:45Z","PwnCount":13545468,"Description":"In approximately March 2015, the free web hosting provider <a href=\"http://www.troyhunt.com/2015/10/breaches-traders-plain-text-passwords.html\" target=\"_blank\" rel=\"noopener\">000webhost suffered a major data breach</a> that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.","DataClasses":["Email addresses","IP addresses","Names","Passwords"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"png"},{"Title":"Lifeboat","Name":"Lifeboat","Domain":"lbsg.net","BreachDate":"2016-01-01","AddedDate":"2016-04-25T21:51:50Z","ModifiedDate":"2016-04-25T21:51:50Z","PwnCount":7089395,"Description":"In January 2016, the Minecraft community known as Lifeboat <a href=\"https://motherboard.vice.com/read/another-day-another-hack-7-million-emails-and-hashed-passwords-for-minecraft\" target=\"_blank\" rel=\"noopener\">was hacked and more than 7 million accounts leaked</a>. Lifeboat knew of the incident for three months before the breach was made public but elected not to advise customers. The leaked data included usernames, email addresses and passwords stored as straight MD5 hashes.","DataClasses":["Email addresses","Passwords","Usernames"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"svg"}]
</code>```

To parse, this I use the following code :

```<code>cat $myfile | python -c "import sys, json; print json.load(sys.stdin)[0]['Title']"
</code>```

But this results in the output :

000webhost

whereas I need the output to be :

000webhost

Lifeboat

答:
You really should be doing this with a proper script. Also, that's a superfluous use of cat, and you should put Bash parameter expansions inside double-quotes to prevent word-splitting. You can omit the quotes if you're sure the path doesn't contain spaces, but it's really not a good habit to get into.

Anyway, this code works in both Python 2 and Python 3.

```<code>python -c "import sys,json;print('\n'.join([u['Title']for u in json.load(open(sys.argv[1]))]))" "$myfile"
</code>```

output

```<code>000webhost
Lifeboat
</code>```

Here's how to write it as a proper script.

```<code>import sys
import json

with open(sys.argv[1]) as f:
    data = json.load(f)
print('\n'.join([u['Title'] for u in data]))
</code>```

Body:
I need to parse the following json output, so I can take parse the Title entries

[{"Title":"000webhost","Name":"000webhost","Domain":"000webhost.com","BreachDate":"2015-03-01","AddedDate":"2015-10-26T23:35:45Z","ModifiedDate":"2015-10-26T23:35:45Z","PwnCount":13545468,"Description":"In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.","DataClasses":["Email addresses","IP addresses","Names","Passwords"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"png"},{"Title":"Lifeboat","Name":"Lifeboat","Domain":"lbsg.net","BreachDate":"2016-01-01","AddedDate":"2016-04-25T21:51:50Z","ModifiedDate":"2016-04-25T21:51:50Z","PwnCount":7089395,"Description":"In January 2016, the Minecraft community known as Lifeboat was hacked and more than 7 million accounts leaked. Lifeboat knew of the incident for three months before the breach was made public but elected not to advise customers. The leaked data included usernames, email addresses and passwords stored as straight MD5 hashes.","DataClasses":["Email addresses","Passwords","Usernames"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"svg"}]

To parse, this I use the following code :

cat $myfile | python -c "import sys, json; print json.load(sys.stdin)[0]['Title']"

But this results in the output :

000webhost

whereas I need the output to be :

000webhost

Lifeboat

Body:
You really should be doing this with a proper script. Also, that's a superfluous use of cat, and you should put Bash parameter expansions inside double-quotes to prevent word-splitting. You can omit the quotes if you're sure the path doesn't contain spaces, but it's really not a good habit to get into.

Anyway, this code works in both Python 2 and Python 3.

python -c "import sys,json;print('\n'.join([u['Title']for u in json.load(open(sys.argv[1]))]))" "$myfile"

output

000webhost
Lifeboat

Here's how to write it as a proper script.

import sys
import json

with open(sys.argv[1]) as f:
    data = json.load(f)
print('\n'.join([u['Title'] for u in data]))


问:
Groovy: Check if text contains a string more than one time
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

```<code> if (env.logs.contains('test')) {
      xxx
}
</code>```

What do I have to change to let this part of code check for more than one appearances of the word test?

答:
The contains() method simply does this:

```<code>public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}
</code>```

Therefore you can do this to check if the value appears more than once:

```<code>int index = env.logs.indexOf("test");
if ((index > -1) && (env.logs.indexOf("test", index + 1) > -1) ) {
        // do something here
}
</code>```

Body:
I want to check if the word "test" appears more than 1 time in the logs.
The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

 if (env.logs.contains('test')) {
      xxx
}

What do I have to change to let this part of code check for more than one appearances of the word test?

Body:
The contains() method simply does this:

public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}

Therefore you can do this to check if the value appears more than once:

int index = env.logs.indexOf("test");
if ((index > -1) && (env.logs.indexOf("test", index + 1) > -1) ) {
        // do something here
}


问:
Which one to go first, Grails or Groovy?
I wanted to create a web application. I thought of selecting Groovy or Grails. But I don't know from where to start! To start with Groovy or Grails?</p>

答: If you have the opportunity to deploy on google appengine you should take a look at Gaelyk (http://gaelyk.appspot.com/), which is a Groovy framework that gets you up and running realy fast.</p>

ContentLicense: CC BY-SA 2.5


问:
How to redirect http to https for IP and domain on Apache2
I have an Apache2 web server running on Ubuntu 12.04. The domain of the website that I am hosting works fine, and if you go to the http version instead of the https version, it automatically redirects to the https version of the domain.

However, if I go to the http version of the ip address of the domain, it does not automatically redirect to the https version of the ip address.

There is nothing in the .htaccess or httpd.conf file.

I have tried adding a redirect for the ip specifically in the .htaccess file, but it does not work properly and the when I visit the domain, it says there are too many redirects.

I have a default-ssl file and website file in the sites-enabled folder. The default-ssl has virtual host config for port 443 and the ServerName

The website file has virtual host config for port 80, but no ServerName

Both files have the same DocumentRoot

How do enable the https redirect for the ip address as well, not only the domain?

答:
Generally, websites don't allow you to browse them using their IP addresses. They will do a 301 redirect to their domain address instead. This is for search engine optimisation, as having multiple addresses point to the same host may confuse search engines into thinking they are different sites, causing the sites to unnecessarily compete with each other for page ranking.

Since you already have HTTPS redirect on your domain address, why don't you redirect your IP address to your domain address? The domain address will then redirect to the HTTPS site. You can do this through .htaccess, or through a server-side page processor like PHP.


问:
how to use JS or CSS to display 50 images one by one with touch swipe
I'm new here.
There is web app project to show different images (I guess more than 50 images) by touch swiping the screen.
You can imagine that this is like playing cartoon. When I swipe the screen, the images will be displayed one after another.
The size of each image is 1-2MB.

Here is my code. imgs is array of images.

```<code>box1.addEventListener('touchmove', function(e){
    var i = 0;
    var touchobj = e.changedTouches[0];
    var dist = Math.abs(parseInt(touchobj.clientX) - startx );
    var X = Math.floor(dist/5) ;

    for(;i<X;i++) {
      if (i < 40)  {
       box1.innerHTML = "<img src=" + imgs[i] + " style='width:100%' >";
      } else {
       box1.innerHTML = "<img src=" + imgs[50] + " style='width:100%' >";
      }
    }

    e.preventDefault();
}, false)
</code>```

答:
I think when you swipe between images you just want to see an overview of the images not the full resolution 1-2 Mb version, so you can use load image library to scale images and provide a way to select one of the images to see it with full resolution.

tip: you could use Math.min to get rid of the if/else part

```<code>for(;i<X;i++) {
   box1.innerHTML = "<img src=" + imgs[Math.min(i, 50)] + " style='width:100%' >";
}
</code>```

Body:
I'm new here.
There is web app project to show different images (I guess more than 50 images) by touch swiping the screen.
You can imagine that this is like playing cartoon. When I swipe the screen, the images will be displayed one after another.
The size of each image is 1-2MB.

Here is my code. imgs is array of images.

box1.addEventListener('touchmove', function(e){
    var i = 0;
    var touchobj = e.changedTouches[0];
    var dist = Math.abs(parseInt(touchobj.clientX) - startx );
    var X = Math.floor(dist/5) ;

    for(;i<X;i++) {
      if (i < 40)  {
       box1.innerHTML = "";
      } else {
       box1.innerHTML = "";
      }
    }

    e.preventDefault();
}, false)

Body:
I think when you swipe between images you just want to see an overview of the images not the full resolution 1-2 Mb version, so you can use load image library to scale images and provide a way to select one of the images to see it with full resolution.

tip: you could use Math.min to get rid of the if/else part

for(;i<X;i++) {
   box1.innerHTML = "<img src=" + imgs[Math.min(i, 50)] + " style='width:100%' >";
}


问:
Resources for TDD aimed at Python Web Development
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.

Are there any particular ones you would recommend for this language/application?

答:
I'd recommend "xUnit Test Patterns: Refactoring Test Code" by Gerard Meszaros. It is not Python or Web specific, but it's a good book on TDD in general and the xUnit framework in particular. Since python unittest is actually an xUnit implementation ("a Python version of JUnit", as the docs say), I'd say that the book is very useful for Python unit testers.

It has an online version at xunitpatterns.com.

OwnerDisplayName: Null Route

OwnerDisplayName: Rafał Dowgird


问:
Add reference failing C#
I have a wcf service running and I was trying to implement a tcp model on it so I made a windows service and tried adding the WCF service as a reference to it which worked fine. But when i tried to build the windows service it gave me an error  as "The type or namespace name '*' could not be found (are you missing a using directive or an assembly reference?)". In fact I tried to add my dal project as reference and the same error cropped up. I implemented a POC just to check if I am doing things correctly which worked fine.  But it fails on my solution am I missing some configuration thing I am confused please help thanks.</p>

答: Thank's for all the help guys I got the reason why it was failing all my other projects are having target framework as .Net Framework 4. But each time I add a new project to my solution they are been targeted to .Net Framework 4 Client Profile. Which I changed and everything worked fine. Thank's again for the help.</p>

Title: Add reference failing C#


问:
How to use JUnit to test asynchronous processes
How do you test methods that fire asynchronous processes with JUnit?

I don't know how to make my test wait for the process to end (it is not exactly a unit test, it is more like an integration test as it involves several classes and not just one).

答:
Avoid testing with parallel threads whenever you can (which is most of the time). This will only make your tests flaky (sometimes pass, sometimes fail).

Only when you need to call some other library / system, you might have to wait on other threads, in that case always use the Awaitility library instead of Thread.sleep().

Never just call get() or join() in your tests, else your tests might run forever on your CI server in case the future never completes. Always assert isDone() first in your tests before calling get(). For CompletionStage, that is .toCompletableFuture().isDone().

When you test a non-blocking method like this:

```<code>public static CompletionStage<String> createGreeting(CompletableFuture<String> future) {
    return future.thenApply(result -> "Hello " + result);
}
</code>```

then you should not just test the result by passing a completed Future in the test, you should also make sure that your method doSomething() does not block by calling join() or get(). This is important in particular if you use a non-blocking framework.

To do that, test with a non-completed future that you set to completed manually:

```<code>@Test
public void testDoSomething() throws Exception {
    CompletableFuture<String> innerFuture = new CompletableFuture<>();
    CompletableFuture<String> futureResult = createGreeting(innerFuture).toCompletableFuture();
    assertFalse(futureResult.isDone());

    // this triggers the future to complete
    innerFuture.complete("world");
    assertTrue(futureResult.isDone());

    // futher asserts about fooResult here
    assertEquals(futureResult.get(), "Hello world");
}
</code>```

That way, if you add future.join() to doSomething(), the test will fail.

If your Service uses an ExecutorService such as in thenApplyAsync(..., executorService), then in your tests inject a single-threaded ExecutorService, such as the one from guava:

```<code>ExecutorService executorService = Executors.newSingleThreadExecutor();
</code>```

If your code uses the forkJoinPool such as thenApplyAsync(...), rewrite the code to use an ExecutorService (there are many good reasons), or use Awaitility.

To shorten the example, I made BarService a method argument implemented as a Java8 lambda in the test, typically it would be an injected reference that you would mock.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 4.0

Body:
Avoid testing with parallel threads whenever you can (which is most of the time). This will only make your tests flaky (sometimes pass, sometimes fail).

Only when you need to call some other library / system, you might have to wait on other threads, in that case always use the Awaitility library instead of Thread.sleep().

Never just call get() or join() in your tests, else your tests might run forever on your CI server in case the future never completes. Always assert isDone() first in your tests before calling get(). For CompletionStage, that is .toCompletableFuture().isDone().

When you test a non-blocking method like this:

public static CompletionStage<String> createGreeting(CompletableFuture<String> future) {
    return future.thenApply(result -> "Hello " + result);
}

then you should not just test the result by passing a completed Future in the test, you should also make sure that your method doSomething() does not block by calling join() or get(). This is important in particular if you use a non-blocking framework.

To do that, test with a non-completed future that you set to completed manually:

@Test
public void testDoSomething() throws Exception {
    CompletableFuture<String> innerFuture = new CompletableFuture<>();
    CompletableFuture<String> futureResult = createGreeting(innerFuture).toCompletableFuture();
    assertFalse(futureResult.isDone());

    // this triggers the future to complete
    innerFuture.complete("world");
    assertTrue(futureResult.isDone());

    // futher asserts about fooResult here
    assertEquals(futureResult.get(), "Hello world");
}

That way, if you add future.join() to doSomething(), the test will fail.

If your Service uses an ExecutorService such as in thenApplyAsync(..., executorService), then in your tests inject a single-threaded ExecutorService, such as the one from guava:

ExecutorService executorService = Executors.newSingleThreadExecutor();

If your code uses the forkJoinPool such as thenApplyAsync(...), rewrite the code to use an ExecutorService (there are many good reasons), or use Awaitility.

To shorten the example, I made BarService a method argument implemented as a Java8 lambda in the test, typically it would be an injected reference that you would mock.


问:
array.pop() function weird behavior
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

```<code>arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined
</code>```

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.

答:
(function() {
   arr=[1,2,3,4,5];
   console.log(arr.pop());
   console.log(arr.pop());
   console.log(arr.pop());
})()```

It works fine here. Can you please update your code with whatever you have tried?.

Title: array.pop() function weird behavior

Body:
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.

Body:
(function() {
   arr=[1,2,3,4,5];
   console.log(arr.pop());
   console.log(arr.pop());
   console.log(arr.pop());
})()

It works fine here. Can you please update your code with whatever you have tried?.


问:
Java JDBC result set error, but why?
```<code>Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","user","pass");
Statement myStmt1 = myConn.createStatement();
System.out.println("connected");

for(int i=1; i<1375462;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);

    String Name = myRs1.getString("Name");
    System.out.print(i);
    System.out.println("Name:"+Name);
}
</code>```

I'm using JDBC Java to query the name from database but this time it got an error and I don't know why. I have used Java JDBC before. I can connect to database but the query seem like not working? Id column is integer 10 digit.

```<code>"run: connected java.sql.SQLException: Before start of result set
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5206)"
</code>```

答:
Inside for loop, when getting the ResultSet, you need a check myRs1.next() as described below.

```<code>for(int i=0; i<1;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);
    while(myRs1.next()) {
        String Name = myRs1.getString("Name");
        System.out.print(i);
        System.out.println("Name:"+Name);
    }
}
</code>```

Title: Java JDBC result set error, but why?

Body:
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","user","pass");
Statement myStmt1 = myConn.createStatement();
System.out.println("connected");

for(int i=1; i<1375462;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);

    String Name = myRs1.getString("Name");
    System.out.print(i);
    System.out.println("Name:"+Name);
}

I'm using JDBC Java to query the name from database but this time it got an error and I don't know why. I have used Java JDBC before. I can connect to database but the query seem like not working? Id column is integer 10 digit.

"run: connected java.sql.SQLException: Before start of result set
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5206)"

Body:
Inside for loop, when getting the ResultSet, you need a check myRs1.next() as described below.

for(int i=0; i<1;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);
    while(myRs1.next()) {
        String Name = myRs1.getString("Name");
        System.out.print(i);
        System.out.println("Name:"+Name);
    }
}


问:
React Navigation: Call a function of screen from its Navigator - Is it possible?
I've been trying to call a function which is in a screen of a navigator from its screen.

To clarify the point, here is a snippet of my code...

```<code>//ScreenA.js
export default class ScreenA extends React.Component {
    showWarning(){
        this.setState({showWarning: true});
        setTimeout(function() {
            this.setState({showWarning: false});
        }.bind(this), 3000);
    }

    render() {
        return (
          <View  style={{backgroundColor : this.state.showWarning ? "#red" : "#blue"}}>
              {this.state.showWarning && <Warning />}
          </View>
        )
    }
}

//Nagigator.js
default export const Navigator = StackNavigator({
  ScreenA: {screen: ScreenA},
  ScreenB: {screen: ScreenB},
});

//App.js
export default class App extends React.Component {
    handleSubmit(qrCode){
        if(qrCodeIsInvalid){
            this.navigator.ScreenA.showWarning();
            //This is just a sudo code.
            //How do we call ScreenA.showWarning here?
        }
    }

    render() {
        let props = {/*some props here*/};
        return (//This "ref" stops the application without describing any reason
            <Navigator screenProps={props} ref={nav => { this.navigator = nav; }}/>
        );
    }
}
</code>```

There is an example of how to call a function from a navigation header, but not from the class which exports the navigator.

I thought that each screen can be accessed via ref, but this causes an error without explaining what's happening.

Has anyone encountered a similar situation?

Any advice will be appreciated.

P.S.

@ Nimrod Argov

Here are details of what I've been trying to achieve.

ScreenA has a QR code reader and submit function, which submits QR codes to App.js.

App.js has handleSubmit function, where submitted QR codes are sent to a server and labelled as either valid or invalid.

If a submitted QR code turns out to be invalid, ScreenA has to show a warning message and change its background colour for 3 seconds.

It might be achieved by having App.js pass a prop {showWarning:true} to ScreenA and pass {showWarning:false} in 3 seconds.

However, I thought it would be ScreenA's responsibility to change its background colour. Thus, I set setTimeout and setState in the showWarning().

答:
I did it this way:

ScreenA.js

While navigate to ScreenB, including the function you want to call.

export default class ScreenA extends React.Component {
    constructor(props) {
        super(props);
        this.doSomething = this.doSomething.bind(this);
    }
    doSomething() {
        this.setState({blah: true});
    }
    navigateToB() {
        this.props.navigation.navigate('ScreenB', {
            doSomething: this.doSomething,
        });
    }
}
```

<h2>ScreenB.js</h2>

<p>So you can do this in ScreenB.</p>

<pre class="lang-js prettyprint-override"><code>const { state, setParams, navigate } = this.props.navigation;
const params = state.params || {};

params.doSomething();
</code>```

Body:
I've been trying to call a function which is in a screen of a navigator from its screen.

To clarify the point, here is a snippet of my code...

//ScreenA.js
export default class ScreenA extends React.Component {
    showWarning(){
        this.setState({showWarning: true});
        setTimeout(function() {
            this.setState({showWarning: false});
        }.bind(this), 3000);
    }

    render() {
        return (
          <View  style={{backgroundColor : this.state.showWarning ? "#red" : "#blue"}}>
              {this.state.showWarning && <Warning />}
          </View>
        )
    }
}

//Nagigator.js
default export const Navigator = StackNavigator({
  ScreenA: {screen: ScreenA},
  ScreenB: {screen: ScreenB},
});

//App.js
export default class App extends React.Component {
    handleSubmit(qrCode){
        if(qrCodeIsInvalid){
            this.navigator.ScreenA.showWarning();
            //This is just a sudo code.
            //How do we call ScreenA.showWarning here?
        }
    }

    render() {
        let props = {/*some props here*/};
        return (//This "ref" stops the application without describing any reason
            <Navigator screenProps={props} ref={nav => { this.navigator = nav; }}/>
        );
    }
}

There is an example of how to call a function from a navigation header, but not from the class which exports the navigator.

I thought that each screen can be accessed via ref, but this causes an error without explaining what's happening.

Has anyone encountered a similar situation?

Any advice will be appreciated.

P.S.

@ Nimrod Argov

Here are details of what I've been trying to achieve.

ScreenA has a QR code reader and submit function, which submits QR codes to App.js.

App.js has handleSubmit function, where submitted QR codes are sent to a server and labelled as either valid or invalid.

If a submitted QR code turns out to be invalid, ScreenA has to show a warning message and change its background colour for 3 seconds.

It might be achieved by having App.js pass a prop {showWarning:true} to ScreenA and pass {showWarning:false} in 3 seconds.

However, I thought it would be ScreenA's responsibility to change its background colour. Thus, I set setTimeout and setState in the showWarning().

Body:
I did it this way:

ScreenA.js

While navigate to ScreenB, including the function you want to call.

export default class ScreenA extends React.Component {
    constructor(props) {
        super(props);
        this.doSomething = this.doSomething.bind(this);
    }
    doSomething() {
        this.setState({blah: true});
    }
    navigateToB() {
        this.props.navigation.navigate('ScreenB', {
            doSomething: this.doSomething,
        });
    }
}

ScreenB.js

So you can do this in ScreenB.

const { state, setParams, navigate } = this.props.navigation;
const params = state.params || {};

params.doSomething();


问:
How do I protect JavaScript files?
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

```<code><script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
</code>```

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?

答:
Google Closure Compiler, YUI compressor, Minify, /Packer/... etc, are options for compressing/obfuscating your JS codes. But none of them can help you from hiding your code from the users.

Anyone with decent knowledge can easily decode/de-obfuscate your code using tools like JS Beautifier. You name it.

So the answer is, you can always make your code harder to read/decode, but for sure there is no way to hide.

Title: How do I protect JavaScript files?

Body:
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?


问:
get array element by index javascript, ES6
I have an array fruits = ['apple','mango','eggs','guvava','... many others']. I have an index 15, so I am currently getting element as fruits[14].

Is there any way I can do the same using .splice / .slice or any ES6 method.

I tried .slice(14,1) but not getting the desired result.

答:
```<code>fruits.slice(14,15)[0] // => get you the value of fruits[14] and allocate new memory for a new array

fruits.splice(14,1)[0] // => get you fruits[14] but mutates fruits array and also allocate new memory for a new array
</code>```


问:
How can I show a toast for a specific duration?
This is the way I have to show the Toast for 500 milliseconds. Though, it's showing more than a second.

```<code>Toast.makeText(LiveChat.this, "Typing", 500).show();
</code>```

How can I show Toast only for 500 milliseconds?

答:
I tried different method and this method works for me </p>

```<code> final Toast mytoast = Toast.makeText(getApplicationContext(), jsonObject.getString("response_message"), Toast.LENGTH_SHORT);
 mytoast.show();

                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mytoast.cancel();
                            }
                        }, 5000);// 5 sec
</code>```

Body:
This is the way I have to show the Toast for 500 milliseconds. Though, it's showing more than a second.

Toast.makeText(LiveChat.this, "Typing", 500).show();

How can I show Toast only for 500 milliseconds?

Body:
I tried different method and this method works for me

 final Toast mytoast = Toast.makeText(getApplicationContext(), jsonObject.getString("response_message"), Toast.LENGTH_SHORT);
 mytoast.show();

                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mytoast.cancel();
                            }
                        }, 5000);// 5 sec


问:
Adding multiple columns to array
I would like to add several values that I webscrape to a final result array. Each value that I scrape represents a column in the array.

See below what I tried:

```<code><?php
require_once 'vendor/autoload.php';

use Goutte\Client;

$client = new Client();
$cssSelector = 'tr';
$coin = 'td.no-wrap.currency-name > a';
$url = 'td.no-wrap.currency-name > a';
$symbol = 'td.text-left.col-symbol';
$price = 'td:nth-child(5) > a';

$result = array();

$crawler = $client->request('GET', 'https://coinmarketcap.com/all/views/all/');

$crawler->filter($coin)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($url)->each(function ($node) {
    $link = $node->link();
    $uri = $link->getUri();
    print $uri."\n";
    array_push($result, $uri);
});

$crawler->filter($symbol)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($price)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

print_r($result);
</code>```

My problem is that the individual results do not get pushed to the array. Any suggestions why?

Is there a better method to add multiple attributes to an array?

I appreciate your replies!

答:
$result is not known in your closure.

try USE to include the external variable $result within the filter-closure, like so :

```<code>$crawler->filter($coin)->each(function ($node) use (&$result) {
    print $node->text()."\n";
    array_push($result, $node->text());
});
</code>```

http://php.net/manual/en/class.closure.php

Title: Adding multiple columns to array

Body:
I would like to add several values that I webscrape to a final result array. Each value that I scrape represents a column in the array.

See below what I tried:

<?php
require_once 'vendor/autoload.php';

use Goutte\Client;

$client = new Client();
$cssSelector = 'tr';
$coin = 'td.no-wrap.currency-name > a';
$url = 'td.no-wrap.currency-name > a';
$symbol = 'td.text-left.col-symbol';
$price = 'td:nth-child(5) > a';

$result = array();

$crawler = $client->request('GET', 'https://coinmarketcap.com/all/views/all/');

$crawler->filter($coin)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($url)->each(function ($node) {
    $link = $node->link();
    $uri = $link->getUri();
    print $uri."\n";
    array_push($result, $uri);
});

$crawler->filter($symbol)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($price)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

print_r($result);

My problem is that the individual results do not get pushed to the array. Any suggestions why?

Is there a better method to add multiple attributes to an array?

I appreciate your replies!

Body:
$result is not known in your closure.

try USE to include the external variable $result within the filter-closure, like so :

$crawler->filter($coin)->each(function ($node) use (&$result) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

http://php.net/manual/en/class.closure.php


问:
How to store Images in MongoDB through pymongo?
```<code>from PIL import Image
from bson import Binary

img = Image.open('test.jpg')
img = Binary(img)
</code>```

throws an error stating TypeError : data must be an instance of bytes

Why does this happen? And how to resolve this to store the img to MongoDB?

答:
You need to convert the image into a Byte array. You can do this as follows,

```<code>from PIL import Image
from bson import Binary

img = Image.open('test.jpg')

imgByteArr = io.BytesIO()
img.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
</code>```

You can try to save imgByteArr into mongo

OR

You can convert image into string and then store it in mongo:

```<code>import base64

with open("test.jpg", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    //store str in mongo
</code>```

To get back image

```<code>with open("test2.jpg", "wb") as fimage:
    fimage.write(str.decode('base64'))
</code>```

Body:
from PIL import Image
from bson import Binary

img = Image.open('test.jpg')
img = Binary(img)

throws an error stating TypeError : data must be an instance of bytes

Why does this happen? And how to resolve this to store the img to MongoDB?

Body:
You need to convert the image into a Byte array. You can do this as follows,

from PIL import Image
from bson import Binary

img = Image.open('test.jpg')

imgByteArr = io.BytesIO()
img.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()

You can try to save imgByteArr into mongo

OR

You can convert image into string and then store it in mongo:

import base64

with open("test.jpg", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    //store str in mongo

To get back image

with open("test2.jpg", "wb") as fimage:
    fimage.write(str.decode('base64'))


问:
copy file from host to vagrant virtual machine
I am new with virtual machine. I want to copy a file from host (Mac) to vagrant virtual machine. I could not share a folder, so I want to use command line. How can I copy a file from host to vagrant virtual machine with command line?</p>

答:
To copy a file from the host to vagrant:

```<code>scp -P 2222 /path/to/file vagrant@127.0.0.1:.
</code>```

By default The vagrant instance uses port 2222 and ip 127.0.0.1. The password for vagrant is 'vagrant'.
The file will be copied to the home of vagrant.

To copy a file from vagrant to host machine:

```<code>scp -P 2222 vagrant@127.0.0.1:/path/to/file
</code>```

Body:
To copy a file from the host to vagrant:

scp -P 2222 /path/to/file vagrant@127.0.0.1:.

By default The vagrant instance uses port 2222 and ip 127.0.0.1. The password for vagrant is 'vagrant'.
The file will be copied to the home of vagrant.

To copy a file from vagrant to host machine:

scp -P 2222 vagrant@127.0.0.1:/path/to/file


问:
Reverting git merge commit type
In THIS question I asked what is the difference between git merge branchname vs git merge branchname --squash and how it's affecting history of project. Now the follow-up:

Is it possible to change this merge commit type (back and forth --squash) after pushing this branch to remote?

Background story is that of course I merged with wrong flag and now is time to clean up after myself...

答:
The short answer is no, except via force-push.

To understand why, consider the fact that the word merge, in Git, acts as a verb, to merge, and also as an adjective or noun: a merge commit (a commit of type "merge") or a merge (a merge commit).

When we use the verb form, to merge, we mean to combine two different sets of changes made with respect to some common base.  This is the verb form of both git merge (when doing a real, non-fast-forward, merge) and git merge --squash.  So at this step, the two behave in the same way.  (So far, we're pretty good.)

Once git merge or git merge --squash have finished their "to merge" action, though, they take two different paths.  A normal non-squash merge makes a merge commit, which is a commit that has two parent commit IDs.  A --squash merge makes—or rather, leaves it up to you to make, by running git commit—a normal single-parent commit.  Either way you get a commit, but the thing about a Git commit is that it is uniquely identified by its hash ID, and its hash ID is determined by every bit of information in the commit.  Crucially for our case, those bits-of-information include the parent hash or hashes.

What this means is that when you, or Git, make that post-"merge-as-a-verb" commit, you freeze into the commit's ID the two parents (if a merge commit) or single parent (if a normal non-merge).  As with every Git object, once the hash ID is computed from the content, you cannot change the pairing of hash-ID and content.  If you change the content, you make a new object that gets a new (and different) ID.

You could therefore, before git push-ing the commit you have made, make a new commit that uses the same tree but only one parent, or both parents—whichever one you didn't do the first time around—and hence have both "really, truly, a merge commit" and "not-really-a-merge squash commit" objects in your repository.  You could then pick one of them and send it to some remote and ask the remote to set one of its own names, such as master or develop or whatever on the remote, to point to that one commit.

But now, you have already sent one of those two hash IDs to the remote and asked it to set its name to point to that one commit.  Let's say, for concreteness, that you asked the remote to set the name M.  You can send the other hash ID (making the other commit first if you like) and ask that remote to set some other name, such as N, to point to that other hash ID; that would generally be OK.  But if you ask the remote to set M to the other hash ID, the remote will first look at its current setting for M.  It will see that making M point to the new commit instead of the old one will in fact lose the old one, because the new commit's hash ID does not have the old commit's hash ID in its ancestry (the new commit's hash ID is not the current hash ID of M, nor is the new commit's parent or parents M, nor is any of their parents M, and so on).

Thus, the remote <remote> will reject git push <remote> <hash>:M as a non-fast-forward.  To get that other Git to set its M to the new hash, discarding the old one, you must send it a force-push operation.  That does not guarantee that the remote will obey, but it does tell the remote that you do want to discard some commit(s) from their M.

The dangers here are:

You may discard the commit you pushed earlier (which is your intent) in favor of your new hash (which is better), but perhaps someone else using that remote already picked up your old merge, so that now it has gone viral all over the Internet.  This creates problems for everyone.

You might discard more than just the merge you pushed.  Suppose Bob added a commit atop that commit, and Carol added a commit atop Bob's.  Your force-push will discard your old commit in favor of your new one, but it will also discards Bob and Carol's commits that build atop your old commit.

If you are sure that Bob and Carol do not exist and that no one else has your old (wrong-merge-style) commit, it's safe enough to force-push that commit away and replace it with the improved one.  But if not, it's not safe after all.  You can look into the --force-with-lease option as an alternative, but if others picked up your bad commit, that bad commit can keep returning, virus-like, to haunt you.

Title: Reverting git merge commit type


问:
Node.js: What is the proper way of splitting code?
My index.js file has a lot of code which could be split into many pieces.

Basically it looks something like this:

```<code>importing many dependencies;
importing many custom functions;

defining constants;

setting up express;
setting up apollo-server;

post-request #1
get-request #1
requests....

app.listern on port
</code>```

I want my index.js file to contain only imports

To do so I've split my code into many .js files. The majority of files doesn't export anything, but represented as a piece of code like my this:

```<code>// it's a listen.js file
db.sequelize.sync().then(function() {
  app.listen(process.env.PORT || 3000);
});
</code>```

I import it like this using es6 syntax (I import the whole file):

```<code>import './core/api/rest/listen'
</code>```

and get an error:

```<code>db is not defined
</code>```

I understand why it's not defined in listen.js, because I did not imported it into listen.js, but I imported db in my index.js before I importing listen.js. Why doesn't it visible?

BTW, db here is just one of many variables that raises an error.

Correct me if I'm wrong, but I think that if I import all my variables/constants/dependencies in index.js all these variables become accessible to imported files

答:
The import statement is used to import bindings which are exported by another module.

Please see more: developer.mozilla.org/.../Statements/import

You need to export the class/ functions/ variables you want to import

Body:
My index.js file has a lot of code which could be split into many pieces.

Basically it looks something like this:

importing many dependencies;
importing many custom functions;

defining constants;

setting up express;
setting up apollo-server;

post-request #1
get-request #1
requests....

app.listern on port

I want my index.js file to contain only imports

To do so I've split my code into many .js files. The majority of files doesn't export anything, but represented as a piece of code like my this:

// it's a listen.js file
db.sequelize.sync().then(function() {
  app.listen(process.env.PORT || 3000);
});

I import it like this using es6 syntax (I import the whole file):

import './core/api/rest/listen'

and get an error:

db is not defined

I understand why it's not defined in listen.js, because I did not imported it into listen.js, but I imported db in my index.js before I importing listen.js. Why doesn't it visible?

BTW, db here is just one of many variables that raises an error.

Correct me if I'm wrong, but I think that if I import all my variables/constants/dependencies in index.js all these variables become accessible to imported files


问:
Cancel service fabric actor activation on ActivateAsync?
Is it possible to cancel activation on ActivateAsync, based on initialization code and the ActorProxy.Create  to return null?
For example, a web service asks the state of a device actor. Device with this Id does not exist actually. Can I return null on the actor create?</p>

答:
No, for two reasons.

The object returned from ActorProxy.Create is a proxy that can interact with a (remote) Actor, it is not the Actor itself.

An Actor is automatically created just in time, if it's not already there when interacting with it, so you don't need to worry about its life cycle.

To find out which Actors exist, you can interact with the ActorService.
PagedResult<ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken);


问:
Why does typing https:// doesn't work?
I have a website that I'm working on to pass from http to https. A month ago, I've went through all pages on the website and changed the links in the page's content using the Wordpress CMS back-end editor. When I typed https:// in the address, I could see on the console a lot of Mixed Content errors related to links on files that I don't access to, so I passed this all to the back-end guy in my company to deal with.

Today, someone pointed out that the website is still not secure and if you type https:// it will default to http://. I've tried doing this in Chrome, Firefox and Internet Explorer, and them all default back to http://. The person that pointed this problem said that, since we already have the certificate, this should be happening because some part of the website is still not secure.

How can I find where is this issue happening?

答: You will need to enable the secure site feature from your hosting first the "SLL", but since you mentioned it is already enabled. then you will need to use a plugin to enforce the secure website on all pages, you can try https://wordpress.org/plugins/really-simple-ssl/  </p>

Title: Why does typing https:// doesn't work?


问:
ActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent)
i am getting this error when build this is the full source of the file........................ below
this is a plug in for react native

full error as below
local/Android/src/main/java/com/kmlidc/RNShareLocal/RNShareLocalManager.java:51: error: RNShareLocalManager.RNShareLocalActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent) in ActivityEventListener
    private class RNShareLocalActivityEventListener implements ActivityEventListener {

            ^

its a simple social sharing plugin

```<code>public class RNShareLocalManager extends ReactContextBaseJavaModule implements ActivityEventListener{
private ReactApplicationContext reactContext;
private Callback callback;

final int SHARE_REQUEST = 500;

public RNShareLocalManager(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    this.reactContext.addActivityEventListener(new RNShareLocalActivityEventListener());
}

@Override
public String getName() {
    return "RNShareLocal";
}

private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

}

public void onNewIntent(Intent intent) {

}

@ReactMethod
public void message(String winTitle,String subject,String message,ReadableArray component, Callback callback) {
    this.callback = callback;

    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT,message);
    intent.setType("text/plain");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void link(String winTitle,String subject,String url,ReadableArray component, Callback callback) {
    this.callback = callback;
    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, url);
    intent.setType("text/html");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void pictures(String winTitle,String subject,String message,ReadableArray imagesFile,ReadableArray component, Callback callback) {
    this.callback = callback;
    ArrayList<Uri> uris = new ArrayList<Uri>();
    for(int i=0; i<imagesFile.size();i++){
        uris.add(Uri.parse(imagesFile.getString(i)));
    }
    Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);
    intent.putExtra(Intent.EXTRA_STREAM, uris);
    intent.putExtra ("Kdescription", message);
    intent.setType("image/*");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void downloadImage(ReadableArray imagesUrl, Promise promise){
    List<String> paths = new ArrayList<String>();
    for(int i=0; i<imagesUrl.size();i++){
        String imageUrl = imagesUrl.getString(i);
        String fileName = i + ".jpg";
        String path = this.download(imageUrl,fileName);
        paths.add(path);
    }

    JSONArray array = new JSONArray(paths);
    promise.resolve(array.toString());
}

//下载图片并保存
public String download( String imageUrl, String fileName) {
    final String savePath = getReactApplicationContext().getExternalCacheDir() + "/" + fileName;
    try {
        File f = new File(savePath);
        File dir = f.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        FileOutputStream os = new FileOutputStream(f);
        byte[] data = getImage(imageUrl);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.getLocalizedMessage();
    }

    return "file://" + savePath;
}

/*
* 获取网络图片
*/
public byte[] getImage(String imageUrl) throws Exception{
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
        return readStream(inStream);
    }
    return null;
}

/*
获取图片流数据
 */
public static byte[] readStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    return outStream.toByteArray();
}
</code>```

}

it will be great if some can help,

thanks advance

答:
Please implement onNewIntent() </p>

```<code>private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }
}
</code>```

Body:
i am getting this error when build this is the full source of the file........................ below
this is a plug in for react native

full error as below
local/Android/src/main/java/com/kmlidc/RNShareLocal/RNShareLocalManager.java:51: error: RNShareLocalManager.RNShareLocalActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent) in ActivityEventListener
    private class RNShareLocalActivityEventListener implements ActivityEventListener {

            ^

its a simple social sharing plugin

public class RNShareLocalManager extends ReactContextBaseJavaModule implements ActivityEventListener{
private ReactApplicationContext reactContext;
private Callback callback;

final int SHARE_REQUEST = 500;

public RNShareLocalManager(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    this.reactContext.addActivityEventListener(new RNShareLocalActivityEventListener());
}

@Override
public String getName() {
    return "RNShareLocal";
}

private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

}

public void onNewIntent(Intent intent) {

}

@ReactMethod
public void message(String winTitle,String subject,String message,ReadableArray component, Callback callback) {
    this.callback = callback;

    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT,message);
    intent.setType("text/plain");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void link(String winTitle,String subject,String url,ReadableArray component, Callback callback) {
    this.callback = callback;
    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, url);
    intent.setType("text/html");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void pictures(String winTitle,String subject,String message,ReadableArray imagesFile,ReadableArray component, Callback callback) {
    this.callback = callback;
    ArrayList<Uri> uris = new ArrayList<Uri>();
    for(int i=0; i<imagesFile.size();i++){
        uris.add(Uri.parse(imagesFile.getString(i)));
    }
    Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);
    intent.putExtra(Intent.EXTRA_STREAM, uris);
    intent.putExtra ("Kdescription", message);
    intent.setType("image/*");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void downloadImage(ReadableArray imagesUrl, Promise promise){
    List<String> paths = new ArrayList<String>();
    for(int i=0; i<imagesUrl.size();i++){
        String imageUrl = imagesUrl.getString(i);
        String fileName = i + ".jpg";
        String path = this.download(imageUrl,fileName);
        paths.add(path);
    }

    JSONArray array = new JSONArray(paths);
    promise.resolve(array.toString());
}

//下载图片并保存
public String download( String imageUrl, String fileName) {
    final String savePath = getReactApplicationContext().getExternalCacheDir() + "/" + fileName;
    try {
        File f = new File(savePath);
        File dir = f.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        FileOutputStream os = new FileOutputStream(f);
        byte[] data = getImage(imageUrl);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.getLocalizedMessage();
    }

    return "file://" + savePath;
}

/*
* 获取网络图片
*/
public byte[] getImage(String imageUrl) throws Exception{
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
        return readStream(inStream);
    }
    return null;
}

/*
获取图片流数据
 */
public static byte[] readStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    return outStream.toByteArray();
}

}

it will be great if some can help,

thanks advance

Body:
Please implement onNewIntent()

private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }
}


问:
Vertical align checkbox / label pairs
I go through the posts on this issue on Stack Overflow, but nothing really works for me. I have the following CSS code to vertically align checkbox / label pair:

```<code>body {
    font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
    font-size: 11px;
    margin: 0;
    padding: 0;
}

fieldset {
    line-height: 100%;
}

label {
    display: inline-block;
    vertical-align: baseline;
}
</code>```

The full HTML code is here.

Checkbox / label pairs are vertically centered correctly in Safari (5.0.3) and Firefox (3.6.13) under Mac OS X. On Chrome (Mac OS X) checkboxes are rendered slightly to the top. On Windows OS checkboxes and associate labels are aligned to the bottom (consistently across different browsers: Firefox, Safari, Chrome, and Internet Explorer 8).

Could somebody please explain me why this differences between browsers / OS happens (and also how to avoid them)?

Update

The hack to vertically align checkbox with label in Chrome under Mac is as follows:

```<code>input[type=checkbox] {
    position: relative;
    top: 1px;
}
</code>```

Now need to implement OS and browser specific conditionals...

答: No idea why the browsers do different things, they just always do. As far as this, did you try display:table-cell;?

Title: Vertical align checkbox / label pairs

Body:
I go through the posts on this issue on Stack Overflow, but nothing really works for me. I have the following CSS code to vertically align checkbox / label pair:

body {
    font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
    font-size: 11px;
    margin: 0;
    padding: 0;
}

fieldset {
    line-height: 100%;
}

label {
    display: inline-block;
    vertical-align: baseline;
}

The full HTML code is here.

Checkbox / label pairs are vertically centered correctly in Safari (5.0.3) and Firefox (3.6.13) under Mac OS X. On Chrome (Mac OS X) checkboxes are rendered slightly to the top. On Windows OS checkboxes and associate labels are aligned to the bottom (consistently across different browsers: Firefox, Safari, Chrome, and Internet Explorer 8).

Could somebody please explain me why this differences between browsers / OS happens (and also how to avoid them)?

Update

The hack to vertically align checkbox with label in Chrome under Mac is as follows:

input[type=checkbox] {
    position: relative;
    top: 1px;
}

Now need to implement OS and browser specific conditionals...


问:
Inno Setup Hindi language file not working
I am using the Unicode version of the Inno Setup. I am using Hindi as a language. I have download the Hindi.islu from:

https://github.com/jrsoftware/issrc/blob/master/Files/Languages/Unofficial/Hindi.islu

There was no problem in compilation and packaging. When I try to run the setup after selecting the Hindi language, the next screen shows only gibberish.

What do you think? What am I missing here?

答:
The Hindi.islu is missing UTF-8 byte order mark.

Just add it and the translation will work correctly.

An easy way to add the UTF-8 byte order mark is by opening the file in Windows Notepad and saving it without any change.

I have posted a bug report (it was removed meanwhile, without fixing).


问:
How to Apply Regex Validation to a textbox in JQuery to enter only decimal(s),integer(s) numbers(if multiple comma seperated)
My HTML Code is

```<code><input type="text" class="form-control textinput" id="Result" name="Result" value="@p.Result"/>
</code>```

My JQuery Code is :

```<code>$(function () {

    $(".textinput").keydown(function (e) {
        var test = ^(\d?\d?\d(,\d\d\d)*|\d+)(\.\d\d)?$;
        var value = String.fromCharCode(e.keyCode);
        if (value.match(test)) {
            return false;
        }
    });
});
</code>```

I have reffered to This Question but it isn't working,showing an error so please help

My Sample Inputs will be as follows

1,245.30

24,235

135.60,12.6

235.50

34

答:
You can use the regex

```<code>^(?:\d+,)*\d+(?:\.\d+)?$
</code>```

see the regex101 demo

Body:
My HTML Code is

<input type="text" class="form-control textinput" id="Result" name="Result" value="@p.Result"/>

My JQuery Code is :

$(function () {

    $(".textinput").keydown(function (e) {
        var test = ^(\d?\d?\d(,\d\d\d)*|\d+)(\.\d\d)?$;
        var value = String.fromCharCode(e.keyCode);
        if (value.match(test)) {
            return false;
        }
    });
});

I have reffered to This Question but it isn't working,showing an error so please help

My Sample Inputs will be as follows

1,245.30

24,235

135.60,12.6

235.50

34

Body:
You can use the regex

^(?:\d+,)*\d+(?:\.\d+)?$

see the regex101 demo


问:
Erlang Undefined Function Global
This is my first time diving into Erlang, but I've come from from the world of Prolog.

I can't seem to understand why after loading the module, and telling it to execute a function, it seems to run off to another separate function.

The question Erlang - undefined function seems related, but doesn't look as if it applies in my case. I can compile and load the module(s).

Here is my Eshell output:

```<code>Erlang/OTP 20 [erts-9.1] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10]

Eshell V9.1  (abort with ^G)
1> m(chat_client).
Module: chat_client
MD5: 32e278745489222df841e93620154031
Compiled: No compile time info available
Object file: h:/Program Files/erl9.1/bin/chat_client.beam
Compiler options:  []
Exports:
         handle_messages/1
         module_info/0
         module_info/1
         register_nickname/1
         send_message/2
         start_router/0
         unregister_nickname/1
ok
2> chat_client:start_router().
yes
3> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
4> l(chat_client).
{module,chat_client}
5> chat_client:start_router().
ok
6> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
7> l(message_router).
{module,message_router}
8> chat_client:start_router().
ok
9> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
10>
</code>```

In the chat_client.erl file, there is no match to send_message/2:

```<code>-module(chat_client).

-compile(export_all).

register_nickname(Nickname) ->
    Pid = spawn(chat_client, handle_messages, [Nickname]),
    message_router:register_nick(Nickname, Pid).

unregister_nickname(Nickname) ->
    message_router:unregister_nick(Nickname).

send_message(Addressee, MessageBody) ->
    message_router:send_chat_message(Addressee, MessageBody).

handle_messages(Nickname) ->
    receive
        { printmsg, MessageBody } ->
            io:format("~p received: ~p~n", [Nickname, MessageBody]),
            handle_messages(Nickname);
        stop ->
            ok
    end.

start_router() ->
message_router:start().
</code>```

From the related file message_router.erl I can see a global function make a match (or so I think):

```<code>send_chat_message(Addressee, MessageBody) ->
    global:send_message(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send_message(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send_message(?SERVER, { unregister_nick, ClientName }).
</code>```

What am I doing wrong in this case?

答:
In the module global, there is a function send/2, but no send_message/2. change your message_router to:

```<code>send_chat_message(Addressee, MessageBody) ->
    global:send(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send(?SERVER, { unregister_nick, ClientName }).
</code>```

Title: Erlang Undefined Function Global

Body:
This is my first time diving into Erlang, but I've come from from the world of Prolog.

I can't seem to understand why after loading the module, and telling it to execute a function, it seems to run off to another separate function.

The question Erlang - undefined function seems related, but doesn't look as if it applies in my case. I can compile and load the module(s).

Here is my Eshell output:

Erlang/OTP 20 [erts-9.1] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:10]

Eshell V9.1  (abort with ^G)
1> m(chat_client).
Module: chat_client
MD5: 32e278745489222df841e93620154031
Compiled: No compile time info available
Object file: h:/Program Files/erl9.1/bin/chat_client.beam
Compiler options:  []
Exports:
         handle_messages/1
         module_info/0
         module_info/1
         register_nickname/1
         send_message/2
         start_router/0
         unregister_nickname/1
ok
2> chat_client:start_router().
yes
3> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
4> l(chat_client).
{module,chat_client}
5> chat_client:start_router().
ok
6> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
7> l(message_router).
{module,message_router}
8> chat_client:start_router().
ok
9> chat_client:register_nickname(myatom).
** exception error: undefined function global:send_message/2
10>

In the chat_client.erl file, there is no match to send_message/2:

-module(chat_client).

-compile(export_all).

register_nickname(Nickname) ->
    Pid = spawn(chat_client, handle_messages, [Nickname]),
    message_router:register_nick(Nickname, Pid).

unregister_nickname(Nickname) ->
    message_router:unregister_nick(Nickname).

send_message(Addressee, MessageBody) ->
    message_router:send_chat_message(Addressee, MessageBody).

handle_messages(Nickname) ->
    receive
        { printmsg, MessageBody } ->
            io:format("~p received: ~p~n", [Nickname, MessageBody]),
            handle_messages(Nickname);
        stop ->
            ok
    end.

start_router() ->
message_router:start().

From the related file message_router.erl I can see a global function make a match (or so I think):

send_chat_message(Addressee, MessageBody) ->
    global:send_message(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send_message(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send_message(?SERVER, { unregister_nick, ClientName }).

What am I doing wrong in this case?

Body:
In the module global, there is a function send/2, but no send_message/2. change your message_router to:

send_chat_message(Addressee, MessageBody) ->
    global:send(?SERVER, { send_chat_msg, Addressee, MessageBody }).

register_nick(ClientName, ClientPid) ->
    global:send(?SERVER, { register_nick, ClientName, ClientPid }).

unregister_nick(ClientName) ->
    global:send(?SERVER, { unregister_nick, ClientName }).