问:
How to optimize this regex
Can someone help me to optimize my regex pattern, so I don't have to go through each regexes below. So it matches all of the string like the example I provided.

```<code>$pattern = "/__\(\"(.*)\"/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\"(.*)\",/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\'(.*)\'/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\'(.*)\',/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\"(.*)\"/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\"(.*)\",/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\'(.*)\'/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\'(.*)\',/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
</code>```

Example:

```<code>_e('string');
_e("string");
_e('string', 'string2');
_e("string", 'string2');
__('string');
__("string");
__('string', 'string2');
__("string", 'string2');
</code>```

Also if it possible, to match also these string below.

```<code>"string"|trans
'string'|trans
"string"|trans({}, "string2")
'string'|trans({}, 'string2')
'string'|trans({}, "string2")
"string"|trans({}, 'string2')
</code>```

If it is possible to get the value string2 too. In the worst case, in the file, there are also mixed single and double quote.

Like you see on my preg_match_all code now, I go with 8 patterns for the first and also 8 patterns for the second one to get the first string.

Note:
I just only run this script on console command, not in PHP application. So I don't pay any attention to the performance and it doesn't matter too.

Thank you for your help!

Edited

Thank you for the response. I tried both your regex, almost there. My question might confusing. I am not english speaker. I copy paste from regex101. It might be easier to understand, what I am trying to achieve.

https://regex101.com/r/uX5nqR/2

and this one too

https://regex101.com/r/Fxs7yY/1

Please check this out. I tried to extract translations from wordpress project and also twig file which using "trans" filter. I know there are mo po Editor, but the editor don't recognize the file extension I used.

答:
I took the liberty of writing this in JavaScript, but the regex will work the same.

My complete code looks like this:

```<code>const r = /^_[e_]\((\"(.*)\"|\'(.*)\')(, (\"(.*)\"|\'(.*)\'))?\);$/;

const xs = [
  "_e('string');",
  "_e(\"string\");",
  "_e('string', 'string2');",
  "_e(\"string\", 'string2');",
  "__('string');",
  "__(\"string\");",
  "__('string', 'string2');",
  "__(\"string\", 'string2');",
];

xs.forEach((x) => {
  const matches = x.match(r);

  if(matches){
    console.log('matches are:\n ', matches.filter(m => m !== undefined).join('\n  '));
  }else{
    console.log('no matches for', x);
  }
});
</code>```

Now let me explain how the regex works and how I arrived at it:
First I noticed that all your strings start with _ and end with );,
so I knew the regex had to look something like ^…\);$.
Here ^ and $ mark the beginning and end of the string, and you should leave them out if they're not required.

After the initial _ you've got either another _ or a e, so we put these into a group followed by the opening parenthesis: [e_]\(.

Now we have a string that is either in " or in ', and we put it down as alternatives: (\"(.*)\"|\'(.*)\').

This string is repeated, but optionally, with a leading , in front.
So we get (, …)? for the optional part, and (\"(.*)\"|\'(.*)\') for the whole second portion.

For the second portion of your problem you can use the same strategy:

```<code>"string"|trans
'string'|trans
"string"|trans({}, "string2")
'string'|trans({}, 'string2')
'string'|trans({}, "string2")
"string"|trans({}, 'string2')
</code>```

Start building up your regex from the similarities. We've got the same string pattern as before used twice, and the optional second part now looks like (\(\{\}, (\"(.*)\"|\'(.*)\')\))?.

This way we can end up with a regex like this:

```<code>^(\"(.*)\"|\'(.*)\')\|trans\(\{\}, (\"(.*)\"|\'(.*)\')\))?$
</code>```

Please note that this regex is not tested, but just a guess from my side.

Upon further discussion it became apparent that we're looking at several matches in a larger bunch of text. To adapt to this we need to exclude the ' and " characters from the innermost groups, which leaves us with these regexes:

```<code>_[e_]\(("([^"]*)"|\'([^']*)\')(, ("([^"]*)"|\'([^']*)\'))?\);
(\"(.*)\"|\'(.*)\')\|trans(\(\{\}, (\"(.*)\"|\'(.*)\')\))?
</code>```

I've also noted that my second regex apparently had an unmatched parenthesis in it.

Title: How to optimize this regex

Body:
Can someone help me to optimize my regex pattern, so I don't have to go through each regexes below. So it matches all of the string like the example I provided.

$pattern = "/__\(\"(.*)\"/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\"(.*)\",/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\'(.*)\'/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/__\(\'(.*)\',/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\"(.*)\"/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\"(.*)\",/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\'(.*)\'/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

$pattern = "/_e\(\'(.*)\',/";
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

Example:

_e('string');
_e("string");
_e('string', 'string2');
_e("string", 'string2');
__('string');
__("string");
__('string', 'string2');
__("string", 'string2');

Also if it possible, to match also these string below.

"string"|trans
'string'|trans
"string"|trans({}, "string2")
'string'|trans({}, 'string2')
'string'|trans({}, "string2")
"string"|trans({}, 'string2')

If it is possible to get the value string2 too. In the worst case, in the file, there are also mixed single and double quote.

Like you see on my preg_match_all code now, I go with 8 patterns for the first and also 8 patterns for the second one to get the first string.

Note:
I just only run this script on console command, not in PHP application. So I don't pay any attention to the performance and it doesn't matter too.

Thank you for your help!

Edited

Thank you for the response. I tried both your regex, almost there. My question might confusing. I am not english speaker. I copy paste from regex101. It might be easier to understand, what I am trying to achieve.

https://regex101.com/r/uX5nqR/2

and this one too

https://regex101.com/r/Fxs7yY/1

Please check this out. I tried to extract translations from wordpress project and also twig file which using "trans" filter. I know there are mo po Editor, but the editor don't recognize the file extension I used.

Body:
I took the liberty of writing this in JavaScript, but the regex will work the same.

My complete code looks like this:

const r = /^_[e_]\((\"(.*)\"|\'(.*)\')(, (\"(.*)\"|\'(.*)\'))?\);$/;

const xs = [
  "_e('string');",
  "_e(\"string\");",
  "_e('string', 'string2');",
  "_e(\"string\", 'string2');",
  "__('string');",
  "__(\"string\");",
  "__('string', 'string2');",
  "__(\"string\", 'string2');",
];

xs.forEach((x) => {
  const matches = x.match(r);

  if(matches){
    console.log('matches are:\n ', matches.filter(m => m !== undefined).join('\n  '));
  }else{
    console.log('no matches for', x);
  }
});

Now let me explain how the regex works and how I arrived at it:
First I noticed that all your strings start with _ and end with );,
so I knew the regex had to look something like ^…\);$.
Here ^ and $ mark the beginning and end of the string, and you should leave them out if they're not required.

After the initial _ you've got either another _ or a e, so we put these into a group followed by the opening parenthesis: [e_]\(.

Now we have a string that is either in " or in ', and we put it down as alternatives: (\"(.*)\"|\'(.*)\').

This string is repeated, but optionally, with a leading , in front.
So we get (, …)? for the optional part, and (\"(.*)\"|\'(.*)\') for the whole second portion.

For the second portion of your problem you can use the same strategy:

"string"|trans
'string'|trans
"string"|trans({}, "string2")
'string'|trans({}, 'string2')
'string'|trans({}, "string2")
"string"|trans({}, 'string2')

Start building up your regex from the similarities. We've got the same string pattern as before used twice, and the optional second part now looks like (\(\{\}, (\"(.*)\"|\'(.*)\')\))?.

This way we can end up with a regex like this:

^(\"(.*)\"|\'(.*)\')\|trans\(\{\}, (\"(.*)\"|\'(.*)\')\))?$

Please note that this regex is not tested, but just a guess from my side.

Upon further discussion it became apparent that we're looking at several matches in a larger bunch of text. To adapt to this we need to exclude the ' and " characters from the innermost groups, which leaves us with these regexes:

_[e_]\(("([^"]*)"|\'([^']*)\')(, ("([^"]*)"|\'([^']*)\'))?\);
(\"(.*)\"|\'(.*)\')\|trans(\(\{\}, (\"(.*)\"|\'(.*)\')\))?

I've also noted that my second regex apparently had an unmatched parenthesis in it.


来源: stackexchange

问:
How to add array of strings into HashMap<String, String> and then send with Retrofit?
I am using Retrofit 2 for sending API calls to server, but with parameters I need to send array of strings which must be excluded from API response.

I need to send parameters like deviceToken, feedType and also send an array of excluded strings, so my URL with exclude strings should look like this:

```<code>http://test.com?test[]=1&test[]=2&test[]=3
</code>```

Of course there are other missing requirements.

Take look at this line of code:

params.put("exclusions",  Arrays.deepToString(arr));

Here is my code:

```<code>@GET("enquiry/user-feed/")
Call<UserFeed> userFeed(@QueryMap Map<String, String>   params);

HashMap<String, String> params = new HashMap<String, String>();

params.put("deviceToken", getDeviceToken());
params.put("feedType", feedType[0]);
params.put("feedOrder", order);
params.put("feedLimit", String.valueOf(limit));

Log.d("TAG", "exclusions: : "+ Arrays.deepToString(arr));
params.put("exclusions",  Arrays.deepToString(arr));
</code>```

答:
use LinkedHashMap </p>

```<code>LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();

params.put("deviceToken", getDeviceToken());
params.put("feedType", feedType[0]);
params.put("feedOrder", order);
params.put("feedLimit", String.valueOf(limit));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Retrofit 2 for sending API calls to server, but with parameters I need to send array of strings which must be excluded from API response.

I need to send parameters like deviceToken, feedType and also send an array of excluded strings, so my URL with exclude strings should look like this:

http://test.com?test[]=1&test[]=2&test[]=3

Of course there are other missing requirements.

Take look at this line of code:

params.put("exclusions",  Arrays.deepToString(arr));

Here is my code:

@GET("enquiry/user-feed/")
Call<UserFeed> userFeed(@QueryMap Map<String, String>   params);

HashMap<String, String> params = new HashMap<String, String>();

params.put("deviceToken", getDeviceToken());
params.put("feedType", feedType[0]);
params.put("feedOrder", order);
params.put("feedLimit", String.valueOf(limit));

Log.d("TAG", "exclusions: : "+ Arrays.deepToString(arr));
params.put("exclusions",  Arrays.deepToString(arr));

Body:
use LinkedHashMap

LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();

params.put("deviceToken", getDeviceToken());
params.put("feedType", feedType[0]);
params.put("feedOrder", order);
params.put("feedLimit", String.valueOf(limit));


问:
Google App Engine - Production Only - Module Import Error
I am getting this error when running the app in production. It works fine in my local environment. But, after I upload to server, it throws this exception.

The test_handler module exists in test package (and it works fine in local). I believe that the entire folder structure will be uploaded to the server, when we upload.

Also, is there a way to see the entire folder structure in the Google Application Account online?

============================================================================

```<code><type 'exceptions.ImportError'>: cannot import name test_handler
Traceback (most recent call last):
  File "/base/data/home/apps/mad-scribe/1.346944987034829366/url_handler.py", line 15, in <module>
    from test import test_handler
</code>```

答:
The issue was with the package name. I named the package as 'test', which might have stepped on the shoes of some other package.

from test import test_handler

Renaming the package name (test -> test_handlers) fixed the issue.

Thanks to all who responded to this question.

ContentLicense: CC BY-SA 2.5

Body:
I am getting this error when running the app in production. It works fine in my local environment. But, after I upload to server, it throws this exception.

The test_handler module exists in test package (and it works fine in local). I believe that the entire folder structure will be uploaded to the server, when we upload.

Also, is there a way to see the entire folder structure in the Google Application Account online?

============================================================================

<type 'exceptions.ImportError'>: cannot import name test_handler
Traceback (most recent call last):
  File "/base/data/home/apps/mad-scribe/1.346944987034829366/url_handler.py", line 15, in <module>
    from test import test_handler


问:
Change UISearchBar Shap
I used UISearchBar in the project, but I can't change the view of it. I want to set border around the search bar.

Can I change UIsearchbar as the same as this image?

答:
You can customise the appearance of UISearchbar as:</p>

```<code>// Get UISearchBar UITextFiled
let txfSearchField = Searchbar.value(forKey: "_searchField") as! UITextField

// set Search Bar texfield corder radius
txfSearchField.layer.cornerRadius = 8.0

// set Search Bar texfield border colour and width
txfSearchField.layer.borderWidth = 2.0
txfSearchField.layer.borderColor = UIColor.lightGray.cgColor

// set Search Bar tintColor.
Searchbar.barTintColor = UIColor.white

// Change the search bar placeholder text color
let placeholderlabels   = txfSearchField.value(forKey: "_placeholderLabel") as! UILabel
placeholderlabels.textColor = UIColor.lightGray
</code>```

Title: Change UISearchBar Shap

Body:
You can customise the appearance of UISearchbar as:

// Get UISearchBar UITextFiled
let txfSearchField = Searchbar.value(forKey: "_searchField") as! UITextField

// set Search Bar texfield corder radius
txfSearchField.layer.cornerRadius = 8.0

// set Search Bar texfield border colour and width
txfSearchField.layer.borderWidth = 2.0
txfSearchField.layer.borderColor = UIColor.lightGray.cgColor

// set Search Bar tintColor.
Searchbar.barTintColor = UIColor.white

// Change the search bar placeholder text color
let placeholderlabels   = txfSearchField.value(forKey: "_placeholderLabel") as! UILabel
placeholderlabels.textColor = UIColor.lightGray


问:
Why .remove() doesn't remove the element?
Here is my code:

```<code>$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});
</code>```

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

答:
$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("
Some explanations about "+tag_name+"
");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
  $('.tag_info').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    body{
      padding: 20px;
    }

    a {
        color: #3e6d8e !important;
        background-color: #E1ECF4;
        padding: 2px 5px;
    }
    .tag_info{
      position: absolute;
      width: 130px;
      height: 100px;
      display:none;
      background-color: black;
      color: white;
      padding: 10px;
    }</code>```

    tag1
    tag2```
</div>
</div>
</p>

```check the code `https://jsfiddle.net/uz6y3L2y/3/` may help you.
```

Body:
Here is my code:

$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("
Some explanations about "+tag_name+"
");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

Body:
$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
  $('.tag_info').remove();
  });
});

    body{
      padding: 20px;
    }

    a {
        color: #3e6d8e !important;
        background-color: #E1ECF4;
        padding: 2px 5px;
    }
    .tag_info{
      position: absolute;
      width: 130px;
      height: 100px;
      display:none;
      background-color: black;
      color: white;
      padding: 10px;
    }

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a>tag1</a>
    <a>tag2</a>

check the code `https://jsfiddle.net/uz6y3L2y/3/` may help you.


答:
You should use the key ($outMonth[$key]) for accessing the array element and change the value </p>

```<code>  foreach ($outMonth as $key => $value) {
      if (strlen($value) === 1 ) {
          $outMonth[$key] = "0".$value;

      }
  }
</code>```

Title: php array update values if string length is equal to 1

Body:
I have an array like this:

array(53) { [0]=> string(2) "11" [1]=> string(1) "1" [2]=> string(2) "11" [3]=> string(1) "7" [4]=> string(2) "11" [5]=> string(1) "7" [6]=> string(2) "10" [7]=> string(2) "10" [8]=> string(1) "9" [9]=> string(1) "8" [10]=> string(1) "8" [11]=> string(2) "12" [12]=> string(1) "6" [13]=> string(2) "10" [14]=> string(2) "10" [15]=> string(2) "12" [16]=> string(1) "2" [17]=> string(1) "3" [18]=> string(1) "8" [19]=> string(1) "5" [20]=> string(1) "4" [21]=> string(1) "3" [22]=> string(1) "2" [23]=> string(1) "2" [24]=> string(1) "3" [25]=> string(1) "7" [26]=> string(1) "3" [27]=> string(1) "6" [28]=> string(1) "9" [29]=> string(1) "3" [30]=> string(1) "3" [31]=> string(2) "12" [32]=> string(2) "12" [33]=> string(1) "1" [34]=> string(2) "12" [35]=> string(1) "5" [36]=> string(1) "2" [37]=> string(1) "8" [38]=> string(1) "6" [39]=> string(1) "9" [40]=> string(1) "9" [41]=> string(2) "10" [42]=> string(1) "1" [43]=> string(1) "2" [44]=> string(1) "3" [45]=> string(2) "10" [46]=> string(1) "7" [47]=> string(1) "4" [48]=> string(2) "11" [49]=> string(2) "12" [50]=> string(1) "1" [51]=> string(1) "9" [52]=> string(1) "9" }

I want to every value in this array to have two character length, if array value is:9 to change to 09.

With this I can`t achieve... somewhere I missed something

foreach ($outMonth as $key => $value) {
    if (strlen($outMonth[$value]) == 1 ) {
        $outMonth[$value] = "0".$value;
        //echo (strlen($outMonth[$value])). "
";
    }
}

If I dump, I got:

array(53) { [0]=> string(2) "11" [1]=> string(2) "01" [2]=> string(2) "11" [3]=> string(2) "03" [4]=> string(2) "11" [5]=> string(2) "05" [6]=> string(2) "10" [7]=> string(2) "10" [8]=> string(2) "08" [9]=> string(2) "09" [10]=> string(3) "010" [11]=> string(2) "12" [12]=> string(3) "012" [13]=> string(2) "10" [14]=> string(2) "10" [15]=> string(2) "12" [16]=> string(1) "2" [17]=> string(1) "3" [18]=> string(1) "8" [19]=> string(1) "5" [20]=> string(1) "4" [21]=> string(1) "3" [22]=> string(1) "2" [23]=> string(1) "2" [24]=> string(1) "3" [25]=> string(1) "7" [26]=> string(1) "3" [27]=> string(1) "6" [28]=> string(1) "9" [29]=> string(1) "3" [30]=> string(1) "3" [31]=> string(2) "12" [32]=> string(2) "12" [33]=> string(1) "1" [34]=> string(2) "12" [35]=> string(1) "5" [36]=> string(1) "2" [37]=> string(1) "8" [38]=> string(1) "6" [39]=> string(1) "9" [40]=> string(1) "9" [41]=> string(2) "10" [42]=> string(1) "1" [43]=> string(1) "2" [44]=> string(1) "3" [45]=> string(2) "10" [46]=> string(1) "7" [47]=> string(1) "4" [48]=> string(2) "11" [49]=> string(2) "12" [50]=> string(1) "1" [51]=> string(1) "9" [52]=> string(1) "9" }

You can see that only few values are changed...

Thanks your time!

Body:
You should use the key ($outMonth[$key]) for accessing the array element and change the value

  foreach ($outMonth as $key => $value) {
      if (strlen($value) === 1 ) {
          $outMonth[$key] = "0".$value;

      }
  }


问:
How can I check a current logged in user security level so i can disable features?
PRE
I'm using SQLExpress to store information.

I have a very basic user set-up in my app. I have a Login table that contains only three fields, these are Username, Password and Security Level. There are only three security levels; High, Medium and Low.

On my login form, I have the following code to save the user that is logging into a Settings.Default[], so I can read it later.

```<code>private void Loginbtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MySupportHub;Integrated Security=True");
    SqlDataAdapter sda = new SqlDataAdapter(@"SELECT * FROM [dbo].[Login] Where Username='" + usernameTextBox.Text + "' and Password='" + passwordTextBox.Text + "'", con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    if (dt.Rows.Count == 1)
    {
        Settings.Default["CurrentUserName"] = usernameTextBox.Text;
        Settings.Default.Save();

        this.Hide();
        Home home = new Home();
        home.Show();
    }
    else
    {
        MessageBox.Show("Invalid Username and/or Password..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Clearbtn_Click(sender, e);
    }
}
</code>```

Then on the Home page, I have the following code to get the value and display the current logged in user in the bottom status bar. On page load.

```<code>//Identify and display current logged in user

CurrentUser.Caption = Settings.Default["CurrentUserName"].ToString();
</code>```

What I would like to be able to do now is check the current logged in users security level (User value would be stored here "CurrentUser.Caption" on the main form) and be able to disable features like creating a new user etc.

So I would need to be able to read the CurrentUser.Caption value, check that against the (SQL Express) [dbo].[Login] table and find the user's security level and limit features based on the result.

Any help would be appreciated.

Thanks

Phil

答:
Are you looking for

```<code>SELECT CURRENT_USER;
</code>```

or

```<code>SELECT SUSER_NAME();
</code>```

and check with your table records?

Body:
PRE
I'm using SQLExpress to store information.

I have a very basic user set-up in my app. I have a Login table that contains only three fields, these are Username, Password and Security Level. There are only three security levels; High, Medium and Low.

On my login form, I have the following code to save the user that is logging into a Settings.Default[], so I can read it later.

private void Loginbtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MySupportHub;Integrated Security=True");
    SqlDataAdapter sda = new SqlDataAdapter(@"SELECT * FROM [dbo].[Login] Where Username='" + usernameTextBox.Text + "' and Password='" + passwordTextBox.Text + "'", con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    if (dt.Rows.Count == 1)
    {
        Settings.Default["CurrentUserName"] = usernameTextBox.Text;
        Settings.Default.Save();

        this.Hide();
        Home home = new Home();
        home.Show();
    }
    else
    {
        MessageBox.Show("Invalid Username and/or Password..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Clearbtn_Click(sender, e);
    }
}

Then on the Home page, I have the following code to get the value and display the current logged in user in the bottom status bar. On page load.

//Identify and display current logged in user

CurrentUser.Caption = Settings.Default["CurrentUserName"].ToString();

What I would like to be able to do now is check the current logged in users security level (User value would be stored here "CurrentUser.Caption" on the main form) and be able to disable features like creating a new user etc.

So I would need to be able to read the CurrentUser.Caption value, check that against the (SQL Express) [dbo].[Login] table and find the user's security level and limit features based on the result.

Any help would be appreciated.

Thanks

Phil

Body:
Are you looking for

SELECT CURRENT_USER;

or

SELECT SUSER_NAME();

and check with your table records?


答:
You are giving wrong index while updating array value:</p>

```<code>foreach ($outMonth as $key => $value) {
    if (strlen($value) == 1 ) {
        $outMonth[$key] = "0".$value; //<-----------Need to add $key as index
        //echo (strlen($outMonth[$value])). "<br>";
    }
}
</code>```

Body:
You are giving wrong index while updating array value:

foreach ($outMonth as $key => $value) {
    if (strlen($value) == 1 ) {
        $outMonth[$key] = "0".$value; //<-----------Need to add $key as index
        //echo (strlen($outMonth[$value])). "<br>";
    }
}


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答: We are using akka with its camel plugin to distribute our analysis and trending processing for twimpact.com. We have to process between 50 and 1000 messages per second. In addition to multi-node processing with camel it is also used to distribute work on a single processor to multiple workers for maximum performance. Works quite well, but requires some understanding of how to handle congestions.</p>

ContentLicense: CC BY-SA 4.0


问:
Json info through url php
I'm trying to get specific data from a Json url but i'm stuck in how to get the data i need. The output of my url looks like:

```<code>{
"dev_settings_device":{"uuid":"eneco-001-018946:hdrv_zwave_63523C6205B", "name":"settings_device", "internalAddress":"settings_device", "type":"settings_device", "supportsCrc":"49", "location":"(null)"},
"dev_10":{"uuid":"eneco-001-018946:hdrv_zwave_69423C65F08", "name":"HAE_METER_v2", "internalAddress":"10", "type":"HAE_METER_v2", "supportsCrc":"1", "supportedCC":"22 3c 3d 3e 56 60 70 72 7a 86 8b 73", "IsConnected":"1", "HealthValue":"10", "location":"(null)"},
"dev_10.1":{"uuid":"eneco-001-018946:hdrv_zwave_69448735F0E", "name":"HAE_METER_v2_1", "internalAddress":"10.1", "type":"gas", "supportsCrc":"0", "CurrentGasFlow":"0.00", "CurrentGasQuantity":"670.00", "location":"(null)"},
"dev_10.2":{"uuid":"eneco-001-018946:hdrv_zwave_6945CFF5F0E", "name":"HAE_METER_v2_2", "internalAddress":"10.2", "type":"elec", "supportsCrc":"0", "CurrentElectricityFlow":"428.00", "CurrentElectricityQuantity":"49464.00", "location":"(null)"},
"dev_10.3":{"uuid":"eneco-001-018946:hdrv_zwave_69458EC5F0E", "name":"HAE_METER_v2_3", "internalAddress":"10.3", "type":"elec_delivered_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.4":{"uuid":"eneco-001-018946:hdrv_zwave_6947CCD5F0E", "name":"HAE_METER_v2_4", "internalAddress":"10.4", "type":"elec_received_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.5":{"uuid":"eneco-001-018946:hdrv_zwave_694D7AB5F0E", "name":"HAE_METER_v2_5", "internalAddress":"10.5", "type":"elec_delivered_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.6":{"uuid":"eneco-001-018946:hdrv_zwave_6941EFB5F0E", "name":"HAE_METER_v2_6", "internalAddress":"10.6", "type":"elec_received_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"}
}
</code>```

My file looks like this

```<code><?php
error_reporting(E_ALL);
/* Written by Ierlandfan */
/* 1-11-2015 */
/* Version 1.1 */

/* Change ip_toon to the IP of your Toon */
/* start of current Energy usage import */
$file_string_gas = file_get_contents('http://192.168.1.66/hdrv_zwave?
action=getDevices.json');
$parsed_json = json_decode($file_string_gas, true);
var_dump($parsed_json['dev_10.1']);

/* Create new virtual sensor and write down the idx value */
/* Define idxvalue here */
$gasUsage=$parsed_json['CurrentGasQuantity'];
$idx = 933;

/* If this script is not run locally on the Domoticz server change 127.0.0.1
according to your Domoticz IP */
/* Send currentUsage to Domoticz */
$gasusage = curl_init("http://192.168.1.27:8080/json.htm?
type=command&param=udevice&idx=$idx&nvalue=0&svalue=$gasUsage");
curl_exec($gasusage);
echo $gasUsage;
?>
</code>```

The output i get from the var dump is:

```<code>array(8) {
  ["uuid"]=>
  string(39) "eneco-001-018946:hdrv_zwave_69448735F0E"
  ["name"]=>
  string(14) "HAE_METER_v2_1"
  ["internalAddress"]=>
  string(4) "10.1"
  ["type"]=>
  string(3) "gas"
  ["supportsCrc"]=>
  string(1) "0"
  ["CurrentGasFlow"]=>
  string(4) "0.00"
  ["CurrentGasQuantity"]=>
  string(6) "670.00"
  ["location"]=>
  string(6) "(null)"
</code>```

The error i receive is: PHP Notice:  Undefined index: CurrentGasQuantity in /home/pi/domoticz/scripts/php/gas_data_json1.php on line 16, but for the life of me i don't understand why. I tried a couple of thing but it seems i'm stuck.

答:
Minor mistake :

correction ,
$gasUsage= $parsed_json['dev_10.1']['CurrentGasQuantity']

Title: Json info through url php

Body:
I'm trying to get specific data from a Json url but i'm stuck in how to get the data i need. The output of my url looks like:

{
"dev_settings_device":{"uuid":"eneco-001-018946:hdrv_zwave_63523C6205B", "name":"settings_device", "internalAddress":"settings_device", "type":"settings_device", "supportsCrc":"49", "location":"(null)"},
"dev_10":{"uuid":"eneco-001-018946:hdrv_zwave_69423C65F08", "name":"HAE_METER_v2", "internalAddress":"10", "type":"HAE_METER_v2", "supportsCrc":"1", "supportedCC":"22 3c 3d 3e 56 60 70 72 7a 86 8b 73", "IsConnected":"1", "HealthValue":"10", "location":"(null)"},
"dev_10.1":{"uuid":"eneco-001-018946:hdrv_zwave_69448735F0E", "name":"HAE_METER_v2_1", "internalAddress":"10.1", "type":"gas", "supportsCrc":"0", "CurrentGasFlow":"0.00", "CurrentGasQuantity":"670.00", "location":"(null)"},
"dev_10.2":{"uuid":"eneco-001-018946:hdrv_zwave_6945CFF5F0E", "name":"HAE_METER_v2_2", "internalAddress":"10.2", "type":"elec", "supportsCrc":"0", "CurrentElectricityFlow":"428.00", "CurrentElectricityQuantity":"49464.00", "location":"(null)"},
"dev_10.3":{"uuid":"eneco-001-018946:hdrv_zwave_69458EC5F0E", "name":"HAE_METER_v2_3", "internalAddress":"10.3", "type":"elec_delivered_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.4":{"uuid":"eneco-001-018946:hdrv_zwave_6947CCD5F0E", "name":"HAE_METER_v2_4", "internalAddress":"10.4", "type":"elec_received_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.5":{"uuid":"eneco-001-018946:hdrv_zwave_694D7AB5F0E", "name":"HAE_METER_v2_5", "internalAddress":"10.5", "type":"elec_delivered_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.6":{"uuid":"eneco-001-018946:hdrv_zwave_6941EFB5F0E", "name":"HAE_METER_v2_6", "internalAddress":"10.6", "type":"elec_received_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"}
}

My file looks like this

<?php
error_reporting(E_ALL);
/* Written by Ierlandfan */
/* 1-11-2015 */
/* Version 1.1 */

/* Change ip_toon to the IP of your Toon */
/* start of current Energy usage import */
$file_string_gas = file_get_contents('http://192.168.1.66/hdrv_zwave?
action=getDevices.json');
$parsed_json = json_decode($file_string_gas, true);
var_dump($parsed_json['dev_10.1']);

/* Create new virtual sensor and write down the idx value */
/* Define idxvalue here */
$gasUsage=$parsed_json['CurrentGasQuantity'];
$idx = 933;

/* If this script is not run locally on the Domoticz server change 127.0.0.1
according to your Domoticz IP */
/* Send currentUsage to Domoticz */
$gasusage = curl_init("http://192.168.1.27:8080/json.htm?
type=command&param=udevice&idx=$idx&nvalue=0&svalue=$gasUsage");
curl_exec($gasusage);
echo $gasUsage;
?>

The output i get from the var dump is:

array(8) {
  ["uuid"]=>
  string(39) "eneco-001-018946:hdrv_zwave_69448735F0E"
  ["name"]=>
  string(14) "HAE_METER_v2_1"
  ["internalAddress"]=>
  string(4) "10.1"
  ["type"]=>
  string(3) "gas"
  ["supportsCrc"]=>
  string(1) "0"
  ["CurrentGasFlow"]=>
  string(4) "0.00"
  ["CurrentGasQuantity"]=>
  string(6) "670.00"
  ["location"]=>
  string(6) "(null)"

The error i receive is: PHP Notice:  Undefined index: CurrentGasQuantity in /home/pi/domoticz/scripts/php/gas_data_json1.php on line 16, but for the life of me i don't understand why. I tried a couple of thing but it seems i'm stuck.


问:
Inherit from value class or composite it?
I've the following classes :

```<code>class A{
  int x;
  int y;
  int z;
  public:
    int getX();
    int getY();
    int getZ();
  //...
}

class B{
  int x;
  int y;
  int z;
  double rotation;
}

class C{
  int x;
  int y;
  int z;
  double dir;
  double index;
}
</code>```

classes B and C have class A parameters in common, Is it good practice to inherit from class A or using composite and storing an A object in B and C classes?

when inheriting from A class it's not necessary to re-implement A functions for B and C but everyone says that composite is better than inheritance! so which one is better?

Edit: suppose both conditions: is-a relation and otherwise, suppose I've class "Point" as "A" class mentioned and I've a gps data which has latitude, longitude and elevation and in some classes I want to add some coordinate information to it. it is not clear that gps data is a point or has a point!

答:
It's up to your class definitions and the relations between base and inheited classes.

Let me tell you an example. Suppose there's a class defines a gun. A police officer or soldier may has a gun, but none of them are a gun. So, you better define police officer and soldier classes to have a gun class as their member. This usage of class inheit is so called 'has-a' relations.

However, if you want to define a new gun with special features, you can inherit the gun class and write some new functions which demonstrate the features. This is so called 'is-a' relations.

Body:
I've the following classes :

class A{
  int x;
  int y;
  int z;
  public:
    int getX();
    int getY();
    int getZ();
  //...
}

class B{
  int x;
  int y;
  int z;
  double rotation;
}

class C{
  int x;
  int y;
  int z;
  double dir;
  double index;
}

classes B and C have class A parameters in common, Is it good practice to inherit from class A or using composite and storing an A object in B and C classes?

when inheriting from A class it's not necessary to re-implement A functions for B and C but everyone says that composite is better than inheritance! so which one is better?

Edit: suppose both conditions: is-a relation and otherwise, suppose I've class "Point" as "A" class mentioned and I've a gps data which has latitude, longitude and elevation and in some classes I want to add some coordinate information to it. it is not clear that gps data is a point or has a point!


答:
You are using jquery funciton remove() in wrong way, that's why it does not removing the element which has class .tag_info. Please use it as per documentation

```<code>remove($('.tag_info')); // Not Correct
</code>```

You need to use it like this

```<code>$('.tag_info').remove();
</code>```

Title: Why .remove() doesn't remove the element?

Body:
You are using jquery funciton remove() in wrong way, that's why it does not removing the element which has class .tag_info. Please use it as per documentation

remove($('.tag_info')); // Not Correct

You need to use it like this

$('.tag_info').remove();


问:
xpath syntax for grabbing text data after a strong tag containing header text
```<code><li><strong>Movie Title:</strong> Training Day</li>
</code>```

How do I grab the textual content in this li tag; "Training Day"?

So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

I have tried stuff using the "following-sibling", but don't seem to be able to get this right.

Another attempt was

```<code>//li/text()[preceding::strong[contains(text(),'Movie Title')]]
</code>```

But this returns ALL text, not just what is inside the li class.

答:
How do I grab the textual content in this li tag; "Training Day"?

  So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

The following XPath expression selects all li-element's text-nodes following a strong-element which value contains the string 'Movie Title'.

```<code>//li[contains(strong,'Movie Title')]/strong/following-sibling::text()
</code>```

In your example XML this results in 'Training Day'.

But if more text-nodes followed, you'd have to restrict the expression to the first text-node like this

```<code>//li[contains(strong,'Movie Title')]/strong/following-sibling::text()[1]
</code>```

Body:
Movie Title: Training Day

How do I grab the textual content in this li tag; "Training Day"?

So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

I have tried stuff using the "following-sibling", but don't seem to be able to get this right.

Another attempt was

//li/text()[preceding::strong[contains(text(),'Movie Title')]]

But this returns ALL text, not just what is inside the li class.

Body:
How do I grab the textual content in this li tag; "Training Day"?

  So I need to say 'if the strong tag has 'Movie Title' in it, return 'Training Day'.

The following XPath expression selects all li-element's text-nodes following a strong-element which value contains the string 'Movie Title'.

//li[contains(strong,'Movie Title')]/strong/following-sibling::text()

In your example XML this results in 'Training Day'.

But if more text-nodes followed, you'd have to restrict the expression to the first text-node like this

//li[contains(strong,'Movie Title')]/strong/following-sibling::text()[1]


问:
Swift: show name in ViewController
I have array with names in TableViewController and I have ViewController. If I click on cell in TableViewController I want to show name from array in ViewController navigation bar title. How to do it?

答:
you can set title of viewcontroller by

suppose you have a view Controller

```<code>class UIViewController{
  // make a variable in your view controller like
 var titleName:String?

 override func viewDidLoad(){
   self.tittle = self.titleName
 }
}
</code>```

from your tableViewController you can pass the name to your ViewController

```<code>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let controller = self.storyboard.instantiateViewController(withIdentifier: "pass you view controller storyboard id here") as! ViewController
controller.titleName = yourArray[indexPath.row]
self.navigationController.pushViewController(controller , animated: true)
    }
</code>```

Title: Swift: show name in ViewController

Body:
you can set title of viewcontroller by

suppose you have a view Controller

class UIViewController{
  // make a variable in your view controller like
 var titleName:String?

 override func viewDidLoad(){
   self.tittle = self.titleName
 }
}

from your tableViewController you can pass the name to your ViewController

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let controller = self.storyboard.instantiateViewController(withIdentifier: "pass you view controller storyboard id here") as! ViewController
controller.titleName = yourArray[indexPath.row]
self.navigationController.pushViewController(controller , animated: true)
    }


问:
Why mapping websocket not working?
I have simple web socket :

```<code>@ServerEndpoint("/chat")
public class ChatEndpoint {

    @OnMessage
    public void onMessage(final Session session, final String msg) {
        try {

            cashing(session, msg);
            newsletter(session, msg);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

But my view chat page index.jsp always mapping to root http://localhost:8080/PsiNavigator. when I try add to path /chat I get 404. Regardless of value in annotation @ServerEndpoint("/chat") or ("bla-bla") always work only root in browser:

My annotation is: @ServerEndpoint("/chat") on both screen.

How to change URL for browser to http://localhost:8080/PsiNavigator/chat?
Thank You.

答:
I thing that you have to access to your websocket endpoint using ws protocol and not http.

I recommed you to follow this helpfull tuto showing how to build a full websocket application example(backend and frontend).
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

Title: Why mapping websocket not working?

Body:
I have simple web socket :

@ServerEndpoint("/chat")
public class ChatEndpoint {

    @OnMessage
    public void onMessage(final Session session, final String msg) {
        try {

            cashing(session, msg);
            newsletter(session, msg);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

But my view chat page index.jsp always mapping to root http://localhost:8080/PsiNavigator. when I try add to path /chat I get 404. Regardless of value in annotation @ServerEndpoint("/chat") or ("bla-bla") always work only root in browser:

My annotation is: @ServerEndpoint("/chat") on both screen.

How to change URL for browser to http://localhost:8080/PsiNavigator/chat?
Thank You.


问:
Regex match for Pivotal Tracker
Pivotal Tracker can parse git commits and change ticket status accordingly. I am writing a PHP script that executes post-commit. It searches the commit message and if it finds the right Pivotal Ticket reference it posts it to the PT api. I'm going a bit nuts trying to figure out the regex.

Currently I have:

```<code>preg_match('/^\[#([0-9]{1,16})\]/', $commit['message'], $matches);
</code>```

So the simplest example of a commit passes:

```<code>[#12345678] Made a commit
</code>```

But what I need to pass are the following:

```<code>1: [finished #12345678] Made a commit //'fixed', 'complete', or 'finished' changes the status
2: I made a commit [#12345678] to a story //Can occur anywhere in the commit
</code>```

答:
The sample inputs are:

```<code>I made a commit [#12345678] to a story
[finished #12345678] Made a commit
[fixed #12345678] Made a commit
[complete #12345678] Made a commit
</code>```

Based on our regex pattern, only the numerical portion is targeted.

To write the best/most efficient pattern to accurately match your input strings, do not use capture groups -- use \K.

```<code>/\[[^#]*#\K\d{1,16}/   #just 24 steps
</code>```

Demo Link

If you need to ensure that the before the #numbers comes either: [nothing], finished, fixed, or complete then this is as refined as I can make it:

```<code>/\[(?:fixed ?|finished ?|complete ?)?#\K\d{1,16}/    #59 steps
</code>```

Demo Link

...this is the same effect as the previous pattern, only condensed slightly:

```<code>/\[(?:fi(?:x|nish)ed ?|complete ?)?#\K\d{1,16}/    #59 steps
</code>```

Demo Link

If these patterns do not satisfy your actual requirements for any reason, please leave a comment and edit your question.  I will adjust my answer to create a most-efficient accurate answer for you.

Title: Regex match for Pivotal Tracker

Body:
Pivotal Tracker can parse git commits and change ticket status accordingly. I am writing a PHP script that executes post-commit. It searches the commit message and if it finds the right Pivotal Ticket reference it posts it to the PT api. I'm going a bit nuts trying to figure out the regex.

Currently I have:

preg_match('/^\[#([0-9]{1,16})\]/', $commit['message'], $matches);

So the simplest example of a commit passes:

[#12345678] Made a commit

But what I need to pass are the following:

1: [finished #12345678] Made a commit //'fixed', 'complete', or 'finished' changes the status
2: I made a commit [#12345678] to a story //Can occur anywhere in the commit

Body:
The sample inputs are:

I made a commit [#12345678] to a story
[finished #12345678] Made a commit
[fixed #12345678] Made a commit
[complete #12345678] Made a commit

Based on our regex pattern, only the numerical portion is targeted.

To write the best/most efficient pattern to accurately match your input strings, do not use capture groups -- use \K.

/\[[^#]*#\K\d{1,16}/   #just 24 steps

Demo Link

If you need to ensure that the before the #numbers comes either: [nothing], finished, fixed, or complete then this is as refined as I can make it:

/\[(?:fixed ?|finished ?|complete ?)?#\K\d{1,16}/    #59 steps

Demo Link

...this is the same effect as the previous pattern, only condensed slightly:

/\[(?:fi(?:x|nish)ed ?|complete ?)?#\K\d{1,16}/    #59 steps

Demo Link

If these patterns do not satisfy your actual requirements for any reason, please leave a comment and edit your question.  I will adjust my answer to create a most-efficient accurate answer for you.


问:
python - Executing transform function on parameter dict when creating new transformdict
I've read about this cool new dictionary type, the transformdict

I want to use it in my project, by initializing a new transform dict with regular dict:

```<code>tran_d = TransformDict(str.lower, {'A':1, 'B':2})
</code>```

which succeeds but when I run this:

```<code>tran_d.keys()
</code>```

I get:

```<code>['A', 'B']
</code>```

How would you suggest to execute the transform function on the parameter (regular) dict when creating the new transform dict?
Just to be clear I want the following:

```<code>tran_d.keys() == ['a', 'b']
</code>```

答:
Per the implementation I have seen, the transformation function can be achieved through a property named transform_func, so

list(map(tran_d.transform_func, tran_d.keys()))
```

should do.

Body:
I've read about this cool new dictionary type, the transformdict

I want to use it in my project, by initializing a new transform dict with regular dict:

tran_d = TransformDict(str.lower, {'A':1, 'B':2})

which succeeds but when I run this:

tran_d.keys()

I get:

['A', 'B']

How would you suggest to execute the transform function on the parameter (regular) dict when creating the new transform dict?
Just to be clear I want the following:

tran_d.keys() == ['a', 'b']

Body:
Per the implementation I have seen, the transformation function can be achieved through a property named transform_func, so

list(map(tran_d.transform_func, tran_d.keys()))

should do.


问:
how to parse json into php
i have a json data retrieved from data base i.e```<code>$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);</code>```
and this give me the result ```[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]```

but from another page when i call this json data i.e```$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;```

it give me the error

```Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0```

答:
Is an array of object, so

```<code>echo $json[0]->fish_id;
</code>```

To loop

```<code>if (!is_array($json)) die('...');
foreach ($json as $key=>$fish)
{
  echo $fish->fish_id;
}
</code>```

Title: how to parse json into php

Body:
i have a json data retrieved from data base i.e
$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);

and this give me the result
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

but from another page when i call this json data i.e
$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;

it give me the error

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0

Body:
Is an array of object, so

echo $json[0]->fish_id;

To loop

if (!is_array($json)) die('...');
foreach ($json as $key=>$fish)
{
  echo $fish->fish_id;
}


问:
Mysql2::Error: Expression #5 of SELECT list is not in GROUP BY clause and contains nonaggregated column
I wrote this query in rails 5 application with 2.4.0 ruby
I have a problem with my query and mysql throws the following error:

```<code>Mysql2::Error: Expression #5 of SELECT list is not in GROUP BY clause and
contains nonaggregated column 'order_it.hidden_companies' which is not
functionally dependent on columns in GROUP BY clause; this is incompatible
with sql_mode=only_full_group_by: SELECT orders.code as Order_code,
customers.name as Company_name.... the reste of my query
</code>```

Query is:

```<code>SELECT
    orders.code AS Order_code,
    customers.name AS Company_name,
    contacts.name AS Name,
    order_it.code AS Medium_Code,
    order_it.hidden_companies,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainphone' then
        contact_resources.value end SEPARATOR '|') AS Main_phone,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainfax' then
        contact_resources.value end SEPARATOR '|') AS Main_fax,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainemail' then
        contact_resources.value end SEPARATOR '|') AS Main_email,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainsite' then
        contact_resources.value end SEPARATOR '|') AS Main_site,
    GROUP_CONCAT(case when contact_resource_types.code = 'procell' then
        contact_resources.value end SEPARATOR '|') AS Pro_cell,
    GROUP_CONCAT(case when contact_resource_types.code = 'cell' then
        contact_resources.value end SEPARATOR '|') AS Cell,
    contact_postal_addresses.street_1 AS Street_1,
    cities.name AS City,
    regions.name AS Region
FROM
    contacts
    INNER JOIN contact_postal_addresses
        ON contact_postal_addresses.contact_id =  contacts.id
    INNER JOIN cities
        ON cities.id = contact_postal_addresses.city_id
    INNER JOIN regions
        ON regions.id = cities.region_id
    INNER JOIN orders
        ON order_id = orders.id
    INNER JOIN contacts AS customers
        ON customers.id = orders.customer_contact_id
    INNER JOIN
    (SELECT DISTINCT
        order_items.order_id,
        order_items.hidden_companies, media.code
    FROM
        order_items
        INNER JOIN media
            ON order_items.medium_id = media.id
    WHERE
        media.id = 76
    ) AS order_it ON order_it.order_id = orders.id
    LEFT OUTER JOIN contact_resources
        ON contact_resources.contact_id = contacts.id
    INNER JOIN contact_resource_types
        ON contact_resources.contact_resource_type_id = contact_resource_types.id
WHERE
    contacts.listing = 1
    and orders.country_id = 5
    and orders.order_status_id = 1
    and contact_resource_types.code in
      ('mainphone','mainfax','mainemail','mainsite','procell','cell')
GROUP BY
    contacts.id
ORDER BY
    contacts.updated_at ;
</code>```

答:
You should GROUP BY using all columns in your SELECT and ORDER BY that are non-aggregated, to be on the safe side. [Having a full definition of all involved tables might help simplify the query].

That is:

```<code>GROUP BY
     contacts.id
    ,Order_code
    ,Company_name
    ,Name
    ,Medium_Code
    ,hidden_companies
    ,Street_1
    ,City
    ,Region
    ,contacts.updated_at
ORDER BY
    contacts.updated_at
</code>```

Body:
I wrote this query in rails 5 application with 2.4.0 ruby
I have a problem with my query and mysql throws the following error:

Mysql2::Error: Expression #5 of SELECT list is not in GROUP BY clause and
contains nonaggregated column 'order_it.hidden_companies' which is not
functionally dependent on columns in GROUP BY clause; this is incompatible
with sql_mode=only_full_group_by: SELECT orders.code as Order_code,
customers.name as Company_name.... the reste of my query

Query is:

SELECT
    orders.code AS Order_code,
    customers.name AS Company_name,
    contacts.name AS Name,
    order_it.code AS Medium_Code,
    order_it.hidden_companies,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainphone' then
        contact_resources.value end SEPARATOR '|') AS Main_phone,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainfax' then
        contact_resources.value end SEPARATOR '|') AS Main_fax,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainemail' then
        contact_resources.value end SEPARATOR '|') AS Main_email,
    GROUP_CONCAT(case when contact_resource_types.code = 'mainsite' then
        contact_resources.value end SEPARATOR '|') AS Main_site,
    GROUP_CONCAT(case when contact_resource_types.code = 'procell' then
        contact_resources.value end SEPARATOR '|') AS Pro_cell,
    GROUP_CONCAT(case when contact_resource_types.code = 'cell' then
        contact_resources.value end SEPARATOR '|') AS Cell,
    contact_postal_addresses.street_1 AS Street_1,
    cities.name AS City,
    regions.name AS Region
FROM
    contacts
    INNER JOIN contact_postal_addresses
        ON contact_postal_addresses.contact_id =  contacts.id
    INNER JOIN cities
        ON cities.id = contact_postal_addresses.city_id
    INNER JOIN regions
        ON regions.id = cities.region_id
    INNER JOIN orders
        ON order_id = orders.id
    INNER JOIN contacts AS customers
        ON customers.id = orders.customer_contact_id
    INNER JOIN
    (SELECT DISTINCT
        order_items.order_id,
        order_items.hidden_companies, media.code
    FROM
        order_items
        INNER JOIN media
            ON order_items.medium_id = media.id
    WHERE
        media.id = 76
    ) AS order_it ON order_it.order_id = orders.id
    LEFT OUTER JOIN contact_resources
        ON contact_resources.contact_id = contacts.id
    INNER JOIN contact_resource_types
        ON contact_resources.contact_resource_type_id = contact_resource_types.id
WHERE
    contacts.listing = 1
    and orders.country_id = 5
    and orders.order_status_id = 1
    and contact_resource_types.code in
      ('mainphone','mainfax','mainemail','mainsite','procell','cell')
GROUP BY
    contacts.id
ORDER BY
    contacts.updated_at ;

Body:
You should GROUP BY using all columns in your SELECT and ORDER BY that are non-aggregated, to be on the safe side. [Having a full definition of all involved tables might help simplify the query].

That is:

GROUP BY
     contacts.id
    ,Order_code
    ,Company_name
    ,Name
    ,Medium_Code
    ,hidden_companies
    ,Street_1
    ,City
    ,Region
    ,contacts.updated_at
ORDER BY
    contacts.updated_at


问:
How to search record if field contain slashes in MySQL
I want to search records based on my erp_no
my erp_no field is varchar in my table.

I am using the following query to search

```<code>SELECT * FROM `invoice` WHERE erp_no LIKE '%SORD\WH03\17\0002917%'
</code>```

But it's returning the empty result set
may I know what is the issue?

答:
You could use escaping sequence for backslash

```<code> SELECT * FROM `invoice` WHERE erp_no LIKE '%SORD\\WH03\\17\\0002917%'
</code>```

looking to your sample you should use

```<code> SELECT * FROM `invoice` WHERE erp_no ='SORD\\WH03\\17\\0002917'
</code>```

Body:
I want to search records based on my erp_no
my erp_no field is varchar in my table.

I am using the following query to search

SELECT * FROM `invoice` WHERE erp_no LIKE '%SORD\WH03\17\0002917%'

But it's returning the empty result set
may I know what is the issue?

Body:
You could use escaping sequence for backslash

 SELECT * FROM `invoice` WHERE erp_no LIKE '%SORD\\WH03\\17\\0002917%'

looking to your sample you should use

 SELECT * FROM `invoice` WHERE erp_no ='SORD\\WH03\\17\\0002917'


问:
What is the purpose of HAVE_* macros?
I am reusing some C/C++ source files part of an autotools project within a CMake project and I see many source files littered with lines like:

```<code>#ifdef HAVE_UNISTD_H
#include <unistd.h>  // for getpid()
#endif
</code>```

I would understand the purpose of this construct if getpid() was optional and its call was surrounded by equivalent HAVE_UNISTD_H directives. However, without HAVE_UNISTD_H the source file does not compile, complaining that getpid() is not defined. This feels a lot more cryptic than the compiler letting me know that unistd.h was not found.

Of course, this is only an example. Other popular macros include HAVE_STDINT_H, HAVE_INTTYPES_H, etc. whose presence is mandatory to compile the source file.

Why are HAVE_* guards included at all? I feel they only bring disadvantages:

Reusing such source files requires making sure the right header files are present and the right HAVE_* macros are defined.

In case of a mistake, the developer gets a more cryptic message, i.e., the compiler does not report the root cause (header not found) but an ancillary error (type/function not found).

The source files are a bit longer and a bit more tedious to read, i.e., #includes mixed with #ifdefs.

答:
Why are HAVE_* guards included at all? I feel they only bring disadvantages: ...

A source could approach an alternative implementation. In that case you certainly don't want to get errors for missing includes.

Silly1 example:

```<code>#ifdef HAVE_UNISTD_H
#include <unistd.h>  // for getpid()
#endif
#ifdef HAVE_WINDoWS_H
#include <windows.h> // for GetProcessId()
#endif
</code>```

1I know that windows supports getpid().

Title: What is the purpose of HAVE_* macros?

Body:
I am reusing some C/C++ source files part of an autotools project within a CMake project and I see many source files littered with lines like:

#ifdef HAVE_UNISTD_H
#include <unistd.h>  // for getpid()
#endif

I would understand the purpose of this construct if getpid() was optional and its call was surrounded by equivalent HAVE_UNISTD_H directives. However, without HAVE_UNISTD_H the source file does not compile, complaining that getpid() is not defined. This feels a lot more cryptic than the compiler letting me know that unistd.h was not found.

Of course, this is only an example. Other popular macros include HAVE_STDINT_H, HAVE_INTTYPES_H, etc. whose presence is mandatory to compile the source file.

Why are HAVE_* guards included at all? I feel they only bring disadvantages:

Reusing such source files requires making sure the right header files are present and the right HAVE_* macros are defined.

In case of a mistake, the developer gets a more cryptic message, i.e., the compiler does not report the root cause (header not found) but an ancillary error (type/function not found).

The source files are a bit longer and a bit more tedious to read, i.e., #includes mixed with #ifdefs.

Body:
Why are HAVE_* guards included at all? I feel they only bring disadvantages: ...

A source could approach an alternative implementation. In that case you certainly don't want to get errors for missing includes.

Silly1 example:

#ifdef HAVE_UNISTD_H
#include <unistd.h>  // for getpid()
#endif
#ifdef HAVE_WINDoWS_H
#include <windows.h> // for GetProcessId()
#endif

1I know that windows supports getpid().


问:
How to call another fetch after the response has come from previous fetch call in Javascript?
There are two fetch statements and I want to execute the second one only after the response has come from the first one ->

```<code>    function CreateRide(userId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/createRide?lat=122.254&lng=14.144&vehicleID=vufn414&time=test';
    fetch(url)
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data.rideID);
            return data.rideID;
        })
    .catch(function (error) {

            responseObj.success = false;
            console.log(error)
        })
}
</code>```

and ->

```<code>function StartRide(rideId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/startRide?rideID=' + rideId;
    fetch(url)
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data);
            return data.success;
        })
        .catch(function (error) {
            responseObj.success = false;
            console.log(error)
        })
}
</code>```

and I want to execute StartRide after the response has come from CreateRide

答:
Use the promise you have in CreateRide, but returning the result of calling fetch().then().catch() so you can use the chain where you call the function. Then use

```<code>CreateRide(/*...*/).then(result => StartRide(/*...*/)).catch(/*...error handler...*/);
</code>```

Here's where you add the return:

```<code>function CreateRide(userId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/createRide?lat=122.254&lng=14.144&vehicleID=vufn414&time=test';
    return fetch(url)                                  // <=======
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data.rideID);
            return data.rideID;
        })
    .catch(function (error) {

            responseObj.success = false;
            console.log(error)
        })
}
</code>```

Side note: This is somewhat a matter of style/debate, but also consider not having CreateRide eat the error; instead, propagate errors (e.g., when returning the promise, don't have a catch) and then handle errors at the outermost level you can.

Side note 2: Also a matter of style, but overwhelmingly, in JavaScript, the convention is that functions that are not constructor functions start with a lower-case letter, e.g. createRide and startRide.

Body:
There are two fetch statements and I want to execute the second one only after the response has come from the first one ->

    function CreateRide(userId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/createRide?lat=122.254&lng=14.144&vehicleID=vufn414&time=test';
    fetch(url)
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data.rideID);
            return data.rideID;
        })
    .catch(function (error) {

            responseObj.success = false;
            console.log(error)
        })
}

and ->

function StartRide(rideId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/startRide?rideID=' + rideId;
    fetch(url)
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data);
            return data.success;
        })
        .catch(function (error) {
            responseObj.success = false;
            console.log(error)
        })
}

and I want to execute StartRide after the response has come from CreateRide

Body:
Use the promise you have in CreateRide, but returning the result of calling fetch().then().catch() so you can use the chain where you call the function. Then use

CreateRide(/*...*/).then(result => StartRide(/*...*/)).catch(/*...error handler...*/);

Here's where you add the return:

function CreateRide(userId){
    const baseUrl = "138.197.99.29:7000/createRide";
    var reqObj = {};
    var responseObj = {"success":false};
    let url = 'http://138.197.99.29:7000/createRide?lat=122.254&lng=14.144&vehicleID=vufn414&time=test';
    return fetch(url)                                  // <=======
        .then((resp) => resp.json())
        .then(function (data) {
            responseObj.success = true;
            console.log(data.rideID);
            return data.rideID;
        })
    .catch(function (error) {

            responseObj.success = false;
            console.log(error)
        })
}

Side note: This is somewhat a matter of style/debate, but also consider not having CreateRide eat the error; instead, propagate errors (e.g., when returning the promise, don't have a catch) and then handle errors at the outermost level you can.

Side note 2: Also a matter of style, but overwhelmingly, in JavaScript, the convention is that functions that are not constructor functions start with a lower-case letter, e.g. createRide and startRide.


问:
No matching client found for package name 'com.google.firebase.udacity.friendlychat'
I'm getting an error about my android project,
enter code herehere the error :

Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package name 'com.google.firebase.udacity.friendlychat'

答: I am pretty much sure that package name in your google-services.json file is different from your actual package name. Go to firebase and check the package name of your app and then download the google-services.json, paste it in your app module. This will solve your problem.


问:
EF4 Code Only - Map Columns to Property Complex type
I have a table like this:

Name

Tree

Iron

Clay

Added

I want to map it to a model like this:

Name

Resources

Tree

Iron

Clay

Added

In makes sense to map it like this, when working with it in my program, but doing it that way in the databse would just make it more complex ... not would not add any useful things.

Is it possible with EF4 Code ONly?

答:
```<code>public class Sample
{
   public int Id { get; set;}  // primary key required
   public string Name {get;set;}
   public DateTime Added{get;set;}

}

 public class Resource
 {
      //  no Id defined here
      public string Tree{get;set;}
      public string Iron { get;set;}
      public string Clay { get;set;}
  }

 public class SampleDB : DbContext
 {
      //public DbSet<Resource> Resources { get; set; } // should not be there
        public DbSet<Sample> Samples { get; set; }
 }
</code>```


答:
Most of the HAVE_xxx_h guards are remnants from an era before POSIX came along and standardized the header files. In early 90s you could easily come across a system that did have getpid(), but without a working unistd.h - the function would simply be declared in another header file, or it wouldn't be declared at all, but it would still work (as long as its return value was int-sized) due to declarations being optional in K&R and C89 C.

There were even stranger issues between the multitude of systems in use at the time. For example there were systems that shipped time.h, those that shipped sys/time.h, and those that shipped both - except that among the last category there was a subset where attempting to actually include both would result in a compilation error! Supporting a vast array of such systems, where possible without listing them all in advance, was one of the explicit design goals of Autoconf, and some of the long-irrelevant hacks are still carefully documented.

In addition to the above concerns, decoupling the header names from support for functions can come in useful when porting the code to non-POSIX systems such as windows. On such systems the posix headers might be missing or broken, and the actual function definition comes from a portability library such as gnulib.

Title: What is the purpose of HAVE_* macros?


问:
Setter and Getter for variable using objc/runtime.h
I have good Setter and Getter code for Object. How do same for BOOL using objc/runtime.h like here?
objc_getAssociatedObject require object</p>

```<code>.h
#import <Foundation/Foundation.h>
@interface UITableView (Additions)
@property (nonatomic, retain) NSNumber *allowReplenishment;
@end

.m
#import "UITableView+Additions.h"
#import <objc/runtime.h>

@implementation UITableView (Additions)

- (NSNumber *)allowReplenishment {
    return objc_getAssociatedObject(self, @selector(allowReplenishment));
}

- (void)setAllowReplenishment:(NSNumber *)value {
    objc_setAssociatedObject(self, @selector(allowReplenishment), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
</code>```

答:
If you want to declare your bool property
@property (nonatomic, assign) BOOL isAllowReplenishment, just create the object in the setter instead, as needed:

```<code>- (void)setIsAllowReplenishment:(BOOL)isAllowReplenishment
    {
        NSNumber *isBool = [NSNumber numberWithBool:isAllowReplenishment];
        objc_setAssociatedObject(self, @selector(isAllowReplenishment), isBool, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }

        - (BOOL)isAllowReplenishment
            {
                NSNumber *isBool = objc_getAssociatedObject(self, @selector(isAllowReplenishment));
                return isBool.boolValue;
    }
</code>```

Body:
I have good Setter and Getter code for Object. How do same for BOOL using objc/runtime.h like here?
objc_getAssociatedObject require object

.h
#import <Foundation/Foundation.h>
@interface UITableView (Additions)
@property (nonatomic, retain) NSNumber *allowReplenishment;
@end

.m
#import "UITableView+Additions.h"
#import <objc/runtime.h>

@implementation UITableView (Additions)

- (NSNumber *)allowReplenishment {
    return objc_getAssociatedObject(self, @selector(allowReplenishment));
}

- (void)setAllowReplenishment:(NSNumber *)value {
    objc_setAssociatedObject(self, @selector(allowReplenishment), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

Body:
If you want to declare your bool property
@property (nonatomic, assign) BOOL isAllowReplenishment, just create the object in the setter instead, as needed:

- (void)setIsAllowReplenishment:(BOOL)isAllowReplenishment
    {
        NSNumber *isBool = [NSNumber numberWithBool:isAllowReplenishment];
        objc_setAssociatedObject(self, @selector(isAllowReplenishment), isBool, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }

        - (BOOL)isAllowReplenishment
            {
                NSNumber *isBool = objc_getAssociatedObject(self, @selector(isAllowReplenishment));
                return isBool.boolValue;
    }


答:
I already said it in the comments but it's important to realize that this is not what TransformDict is meant to do. Therefore you could subclass it with a custom implementation for keys:

```<code>class MyTransformDict(TransformDict):
    def keys(self):
        return map(self.transform_func, super().keys())
</code>```

Depending on your Python version you probably need to use list() around the map (Python 3) or provide arguments for super: super(TransformDict, self) (Python 2). But it should illustrate the principle.

As @Rawing pointed out in the comments there will be more methods that don't work as expected, i.e. __iter__, items and probably also __repr__.

Title: python - Executing transform function on parameter dict when creating new transformdict

Body:
I already said it in the comments but it's important to realize that this is not what TransformDict is meant to do. Therefore you could subclass it with a custom implementation for keys:

class MyTransformDict(TransformDict):
    def keys(self):
        return map(self.transform_func, super().keys())

Depending on your Python version you probably need to use list() around the map (Python 3) or provide arguments for super: super(TransformDict, self) (Python 2). But it should illustrate the principle.

As @Rawing pointed out in the comments there will be more methods that don't work as expected, i.e. __iter__, items and probably also __repr__.


问:
How much memory your program takes? (FastMM vs Borland MM)
I have seen recently a strange behavior in my program. After creating large amounts of objects (500MB of RAM) then releasing them, the program's memory footprint does not return to its original size. It still shows a footprint of 160MB (Private working set).

Normal behavior?

Borland's memory manager does not behave like this, so if possible please confirm (or infirm) this is a normal behavior for FastMM: If you have a handy program in which you create a rather complex MDI child (containing several controls/objects), can you create in a loop 250 instances of that MDI child in memory (at the same time) then release them all and check the memory footprint. Please make sure that you consume at least 200-300MB or RAM with those MDI childs.

Especially those that still using Delphi 7 can see the difference by temporary disabling FastMM.

Thanks

If anybody is interested, especially if you want some proof this is not a memory leak (I hope it is not a mem leak in my code - this is also one of the points of this post: to check if it is my fault), here are the original discussions:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答:
Infirming: Delphi 2007, default memory manager (should be FastMM variation). Several tests on heavy objects:

Initial memory 2Mb, peak memory 30Mb, final memory 4Mb.

Initial memory 2Mb, peak memory 1Gb, final memory 5.5Mb.


问:
Database design for upvote/downvote in discussion forum?
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

```<code>(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)
</code>```

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

```<code>class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID
</code>```

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.

答:
the first approach suggested by Dalen seems best

make a separate table for storing votes, and before performing any up/downvote action, check if the user has done any similar action before.

In case he has done opposite action before, delete/deactivate his previous entry in table and make a new entry.
And in case he has already performed the same action for the question before, do nothing, as his up/downvote has already been accounted.

Making a table for such tasks is highly encouraged, as it will not only make your task easier, it will give you a lot more flexibility, like you can add a timestamp with each action to track history or you can hit a count query on the table to find the total  actions performed on a question

Body:
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.


问:
Getting Embedded with D (the programming language)
I like a lot of what I've read about D.

Unified Documentation (That would
make my job a lot easier.)

Testing capability built in to the
language.

Debug code support in the language.

Forward Declarations.  (I always
thought it was stupid to declare the
same function twice.)

Built in features to replace the
Preprocessor.

Modules

Typedef used for proper type checking
instead of aliasing.

Nested functions. (Cough PASCAL
Cough)

In and Out Parameters. (How obvious is that!)

Supports low level programming -
Embedded systems, oh yeah!

However:

Can D support an embedded system that
not going to be running an OS?

Does the outright declearation that
it doesn't support 16 bit processors
proclude it entirely from embedded
applications running on such machines?  Sometimes you don't need a hammer to solve your problem.

Garbage collection is great on Windows or Linux, but, and unfortunately embedded applications sometime must do explicit memory management.

Array bounds checking, you love it, you hate it.  Great for design assurance, but not alway permissable for performance issues.

What are the implications on an embedded system, not running an OS, for multithreading support?  We have a customer that doesn't even like interrupts.  Much less OS/multithreading.

Is there a D-Lite for embedded systems?

So basically is D suitable for embedded systems with only a few megabytes (sometimes less than a magabyte), not running an OS, where max memory usage must be known at compile time (Per requirements.) and possibly on something smaller than a 32 bit processor?

I'm very interested in some of the features, but I get the impression it's aimed at desktop application developers.

What is specifically that makes it unsuitable for a 16-bit implementation?  (Assuming the 16 bit architecture could address sufficient amounts of memory to hold the runtimes, either in flash memory or RAM.)  32 bit values could still be calculated, albeit slower than 16 bit and requiring more operations, using library code.

答:
The answers to this question are outdated:

Can D support an embedded system that not going to be running an OS?

D can be cross-compiled for ARM Linux and for ARM Cortex-M. Some projects aim at creating libraries for Cortex-M architectures like MiniLibD for the STM32 or this project which uses a generic library for the STM32. (You could implement your own minimalistic OS in D on ARM Cortex-M.)

Does the outright declearation that it doesn't support 16 bit processors proclude it entirely from embedded applications running on such machines? Sometimes you don't need a hammer to solve your problem.

No, see answer above... (But I would not expect that "smaller" architectures than Cortex-M will be supported in the near future.)

Garbage collection is great on Windows or Linux, but, and unfortunately embedded applications sometime must do explicit memory management.

You can write Garbage Collection free code. (The D foundation seems to aim at a "GC free compliant" standard library Phobos but that is work in progress.)

Array bounds checking, you love it, you hate it. Great for design assurance, but not alway permissable for performance issues.

(As you said this depends on your "personal taste" and design decisions. But I would assume an acceptable performance overhead for bound checking due to the background of the D compiler developers and D's design aims.)

What are the implications on an embedded system, not running an OS, for multithreading support? We have a customer that doesn't even like interrupts. Much less OS/multithreading.

(What is the question? One could implement mutlithreading using D's language capabilities e.g. like explained in this question. BTW: If you want to use interrupts consider this "hello world" project for a Cortex-M3.)

Is there a D-Lite for embedded systems?

The SafeD subset of D targets at the embedded domain.


问:
php - displaying error message based on uploading file size not working
I am making basic uploading file code. User is only allowed to upload two types of files, word and excel, and the file size limit to upload is 2MB.

I try to upload the word file and is 1MB, it has successfully uploaded to the database. When I test the code, the error message based on the incorrect file format is displayed, so it works.

Now here is the problem. When i try to test it by uploading the file 5MB, that is above the limit 2MB, it displayed the message "Contract Form Sucessfully Submitted!", but the file is not uploaded to the database. It works but it displayed the message wrong when it supposed to be "Sorry. Your file is too large. Only 2MB is allowed.".

So what is going on here?

PHP:

```<code>if ($_FILES['upload']['size'] != 0 ){

    $filename = mysqli_real_escape_string($con,$_FILES['upload']['name']);
    $filedata= mysqli_real_escape_string($con,file_get_contents($_FILES['upload']['tmp_name']));
    $filetype = mysqli_real_escape_string($con,$_FILES['upload']['type']);
    $filesize = intval($_FILES['upload']['size']);

    $created = date("Y-m-d H:i:s");

    $allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2097152) {

            $query = "INSERT INTO contracts( `filename`,`filedata`,`filetype`,`filesize`,`created`)
                            VALUES (?,?,?,?,?)";
            $stmt = $con->prepare($query);
            $null = NULL;
            $stmt->bind_param("sbsis", $filename, $filedata, $filetype,$filesize,$created);
            $fp = fopen($_FILES['upload']['tmp_name'], "r");

                while (!feof($fp)) {
                $stmt->send_long_data(18, fread($fp,$filesize));
                }
                fclose($fp);
            $stmt->execute();

                if ($stmt->errno){
                    echo "ERROR!!! " . $stmt->error;
                    } else {
                    $successMsg = "Contract Form Sucessfully Submitted!";
                    }
            $stmt->close();

        } else {
            $errorMsg = "Sorry. Your file is too large. Only 2MB is allowed.";
        }
    } else {
        $errorMsg = "Sorry. Only zip, rar, pdf, doc & docx are allowed.";
    }
} else {
        $created = date("Y-m-d H:i:s");
        $query = "INSERT INTO contracts(`created`)
                        VALUES (?)" ;

        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $created);
        $stmt->execute();

        if ($stmt->errno){
        echo "ERROR!!! " . $stmt->error;

        } else {
       $successMsg = "Contract Form Sucessfully Submitted!";
        }
        $stmt->close();
    }
}

$con->close();

?>
</code>```

HTML FORM:

```<code><html>
<body>

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

<label>Upload File</label>
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                    <span class="glyphicon glyphicon-plus"></span> Submit New Contract
                    </button>
</form>
</body>
</html>
</code>```

答:
have you tried to add this piece of code right above your file input:

```<code><html>
<body>

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

<label>Upload File</label>
                    <!-- the added code is here just above the input file type -->
                    <input type="hidden" name="MAX_FILE_SIZE" value="2097152">
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                    <span class="glyphicon glyphicon-plus"></span> Submit New Contract
                    </button>
</form>
</body>
</code>```

Goodluck!

Body:
I am making basic uploading file code. User is only allowed to upload two types of files, word and excel, and the file size limit to upload is 2MB.

I try to upload the word file and is 1MB, it has successfully uploaded to the database. When I test the code, the error message based on the incorrect file format is displayed, so it works.

Now here is the problem. When i try to test it by uploading the file 5MB, that is above the limit 2MB, it displayed the message "Contract Form Sucessfully Submitted!", but the file is not uploaded to the database. It works but it displayed the message wrong when it supposed to be "Sorry. Your file is too large. Only 2MB is allowed.".

So what is going on here?

PHP:

if ($_FILES['upload']['size'] != 0 ){

    $filename = mysqli_real_escape_string($con,$_FILES['upload']['name']);
    $filedata= mysqli_real_escape_string($con,file_get_contents($_FILES['upload']['tmp_name']));
    $filetype = mysqli_real_escape_string($con,$_FILES['upload']['type']);
    $filesize = intval($_FILES['upload']['size']);

    $created = date("Y-m-d H:i:s");

    $allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2097152) {

            $query = "INSERT INTO contracts( `filename`,`filedata`,`filetype`,`filesize`,`created`)
                            VALUES (?,?,?,?,?)";
            $stmt = $con->prepare($query);
            $null = NULL;
            $stmt->bind_param("sbsis", $filename, $filedata, $filetype,$filesize,$created);
            $fp = fopen($_FILES['upload']['tmp_name'], "r");

                while (!feof($fp)) {
                $stmt->send_long_data(18, fread($fp,$filesize));
                }
                fclose($fp);
            $stmt->execute();

                if ($stmt->errno){
                    echo "ERROR!!! " . $stmt->error;
                    } else {
                    $successMsg = "Contract Form Sucessfully Submitted!";
                    }
            $stmt->close();

        } else {
            $errorMsg = "Sorry. Your file is too large. Only 2MB is allowed.";
        }
    } else {
        $errorMsg = "Sorry. Only zip, rar, pdf, doc & docx are allowed.";
    }
} else {
        $created = date("Y-m-d H:i:s");
        $query = "INSERT INTO contracts(`created`)
                        VALUES (?)" ;

        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $created);
        $stmt->execute();

        if ($stmt->errno){
        echo "ERROR!!! " . $stmt->error;

        } else {
       $successMsg = "Contract Form Sucessfully Submitted!";
        }
        $stmt->close();
    }
}

$con->close();

?>

HTML FORM:

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

Upload File
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                     Submit New Contract
                    </button>
</form>

Body:
have you tried to add this piece of code right above your file input:

<html>
<body>

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

<label>Upload File</label>
                    <!-- the added code is here just above the input file type -->
                    <input type="hidden" name="MAX_FILE_SIZE" value="2097152">
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                    <span class="glyphicon glyphicon-plus"></span> Submit New Contract
                    </button>
</form>
</body>

Goodluck!


问:
How to set conditional breakpoint if malloc returns NULL via gdb

Sample source code:

```<code>#include        <stdio.h>
#include        <stdlib.h>
#include        <errno.h>

#define         GIGABYTE        1024*1024*1024

int
main (void)
{
        void    *foo;
        int     result;

        foo = (void *) malloc (GIGABYTE*5);
        result = errno;

        if (foo != NULL) {
                return 2;
        } else {
                fprintf (stderr, "ERROR: %d\n", result);
                return 1;
        }
        return 0;
}
</code>```

Question:

How to instruct gdb (# gdb -silent ./huge_malloc) to stop/halt execution, if malloc() returns 0x0, without checking if foo is 0x0

答: Couldn't you just write a wrapper around malloc that saves the return value and then set a conditional breakpoint on that value?

Body:
Sample source code:

#include        <stdio.h>
#include        <stdlib.h>
#include        <errno.h>

#define         GIGABYTE        1024*1024*1024

int
main (void)
{
        void    *foo;
        int     result;

        foo = (void *) malloc (GIGABYTE*5);
        result = errno;

        if (foo != NULL) {
                return 2;
        } else {
                fprintf (stderr, "ERROR: %d\n", result);
                return 1;
        }
        return 0;
}

Question:

How to instruct gdb (# gdb -silent ./huge_malloc) to stop/halt execution, if malloc() returns 0x0, without checking if foo is 0x0


问:
Is a function definition an object?
Say I have an object and a function definition:

```<code>var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}
</code>```

I can enumerate over the object's key:value pairs thus:

```<code>obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}
</code>```

but this fails for the function definition (same for function expression)

```<code>obj=Car.....
</code>```

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

答:
Lets imagine youre standing in front of a car factory. Can you predict which car will leave it next? Or maybe the factory is closed and will return nothing?

```<code>import Car from "factory";
var car=new Car();//what will car be?
</code>```

So basically you cannot predict what a constructor will construct. But if the car factory just produces diesel engines, we can find that out through the prototype chain, e.g:

```<code>new Car() instanceof Diesel;//true
new Car instanceof Car;//true => all cars have the same prototype ( Car.prototype)
</code>```

So coming back to your example it would make sense to use inheritance like this if the properties are static:

```<code>function Car (desc) {
this.desc = desc;//unpredictable
}
Car.prototype={
  color:"red",//predictable, every car inherits from this
  getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  },
};
</code>```

So to get the static properties, you could iterate over the prototype:

```<code>for(key in Car.prototype);//iterates over color and getInfo
</code>```

Title: Is a function definition an object?

Body:
Say I have an object and a function definition:

var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

I can enumerate over the object's key:value pairs thus:

obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

but this fails for the function definition (same for function expression)

obj=Car.....

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

Body:
Lets imagine youre standing in front of a car factory. Can you predict which car will leave it next? Or maybe the factory is closed and will return nothing?

import Car from "factory";
var car=new Car();//what will car be?

So basically you cannot predict what a constructor will construct. But if the car factory just produces diesel engines, we can find that out through the prototype chain, e.g:

new Car() instanceof Diesel;//true
new Car instanceof Car;//true => all cars have the same prototype ( Car.prototype)

So coming back to your example it would make sense to use inheritance like this if the properties are static:

function Car (desc) {
this.desc = desc;//unpredictable
}
Car.prototype={
  color:"red",//predictable, every car inherits from this
  getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  },
};

So to get the static properties, you could iterate over the prototype:

for(key in Car.prototype);//iterates over color and getInfo