问:
Send data with curl in Bash script: positional argument not working
Total noob in BASH. Trying to learn.
I have the following bash script to make an API request:

```<code>#!/bin/bash
if [ $1 = "new_event" ]; then
    a='https://www.googleapis.com/calendar/v3/calendars/'
    b=$2
    c='/events?access_token='
    d=$3
    path=$a$b$c$d

    echo $4

  OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d $4 )"
  echo "${OUTPUT}"
fi
</code>```

Positional arguments are 'new_event', calendarId, access token and json string.
If I run the script I get:

first echo is the json string I pass as parameter in the call:

```<code>' {"guestsCanSeeOtherGuests": false, "location": "", "description": "TEST", "reminders": {"useDefault": false}, "start": {"dateTime": "2017-07-06T14:00:00", "timeZone": "America/Sao_Paulo"}, "end": {"dateTime": "2017-07-06T15:00:00", "timeZone": "America/Sao_Paulo"}, "guestsCanInviteOthers": false, "summary": "TEST", "status": "tentative", "attendees": []} '
</code>```

second echo gives me parsing error.

BUT, if I copy the echoed json string and replace $4 for it, everything works.

```<code>OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d ' {"guestsCanSeeOtherGuests": false, "location": "", "description": "TEST", "reminders": {"useDefault": false}, "start": {"dateTime": "2017-07-06T14:00:00", "timeZone": "America/Sao_Paulo"}, "end": {"dateTime": "2017-07-06T15:00:00", "timeZone": "America/Sao_Paulo"}, "guestsCanInviteOthers": false, "summary": "TEST", "status": "tentative", "attendees": []} ' )"
</code>```

Any hint why is it not working with the positional argument while it works if I paste it's content?

Thanks!

答:
When you pass the JSON string as a parameter, it assigns the content contained inside the single quote as a whole string but when you pass it to curl it was subjected to word splitting.

To show what it looks like here's a sample script to demonstrate it.

This script will receive the string and pass it to the second script.

```<code>#!/bin/bash
./params $1
</code>```

This second script simulates what curl sees. It will print the number of parameters it receives.

```<code>#!/bin/bash
echo $#
</code>```

Guess what the output is:

```<code>27
</code>```

To fix your issue and make it simpler, drop the outermost quote and quote everything inside the $().

```<code>OUTPUT=$(curl -s -H "Content-Type: application/json" "$path" -d "$4" )
</code>```

Body:
Total noob in BASH. Trying to learn.
I have the following bash script to make an API request:

#!/bin/bash
if [ $1 = "new_event" ]; then
    a='https://www.googleapis.com/calendar/v3/calendars/'
    b=$2
    c='/events?access_token='
    d=$3
    path=$a$b$c$d

    echo $4

  OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d $4 )"
  echo "${OUTPUT}"
fi

Positional arguments are 'new_event', calendarId, access token and json string.
If I run the script I get:

first echo is the json string I pass as parameter in the call:

' {"guestsCanSeeOtherGuests": false, "location": "", "description": "TEST", "reminders": {"useDefault": false}, "start": {"dateTime": "2017-07-06T14:00:00", "timeZone": "America/Sao_Paulo"}, "end": {"dateTime": "2017-07-06T15:00:00", "timeZone": "America/Sao_Paulo"}, "guestsCanInviteOthers": false, "summary": "TEST", "status": "tentative", "attendees": []} '

second echo gives me parsing error.

BUT, if I copy the echoed json string and replace $4 for it, everything works.

OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d ' {"guestsCanSeeOtherGuests": false, "location": "", "description": "TEST", "reminders": {"useDefault": false}, "start": {"dateTime": "2017-07-06T14:00:00", "timeZone": "America/Sao_Paulo"}, "end": {"dateTime": "2017-07-06T15:00:00", "timeZone": "America/Sao_Paulo"}, "guestsCanInviteOthers": false, "summary": "TEST", "status": "tentative", "attendees": []} ' )"

Any hint why is it not working with the positional argument while it works if I paste it's content?

Thanks!

Body:
When you pass the JSON string as a parameter, it assigns the content contained inside the single quote as a whole string but when you pass it to curl it was subjected to word splitting.

To show what it looks like here's a sample script to demonstrate it.

This script will receive the string and pass it to the second script.

#!/bin/bash
./params $1

This second script simulates what curl sees. It will print the number of parameters it receives.

#!/bin/bash
echo $#

Guess what the output is:

27

To fix your issue and make it simpler, drop the outermost quote and quote everything inside the $().

OUTPUT=$(curl -s -H "Content-Type: application/json" "$path" -d "$4" )


来源: stackexchange

问:
What happen when mobile provision expire?
I have an ad hoc build sent to some persons what will happen when the mobile provision will expire? He ca run the app after that? </p>

答: No he won't.... you'll have to make a new provisioning profile and re-build. That's the point in an adhoc distro, its mean for testing and doesn't last forever. If they want the full app they'll have to download it off the app store. If you want to give it away for free there's a special feature where you can create free download coupons or something similar in itunes connect.</p>

ContentLicense: CC BY-SA 2.5


问:
add google analytics code to all pages by nginx
I want to add my Google Analytics code to all website pages
i try to set

```<code>sub_filter
</code>```

it's not working

```<code> set $tracking_id 'UA-12345678-9';
sub_filter '</head>' '<script type="text/javascript">var _gaq=[["_setAccount","$tracking_id"],["_trackPageview"]];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;g.src="//www.google-analytics.com/ga.js";s.parentNode.insertBefore(g,s)})(document,"script")</script></head>';
</code>```

and i try to use

```<code>add_before_body /file.html
</code>```

it's give me error page not loading

and i try to use

```<code>add_after_body /file.html
</code>```

it's working good , but it's set code out html of page

答:
normal nginx can't help you

you will need to install google nginx

PageSpeed Module
that will help you to minify css , html , js , Analytics and more

https://developers.google.com/speed/pagespeed/module/

to add it to your nginx setup

follow url

https://www.digitalocean.com/community/tutorials/how-to-add-ngx_pagespeed-to-nginx-on-centos-7

ContentLicense: CC BY-SA 3.0

Body:
I want to add my Google Analytics code to all website pages
i try to set

sub_filter

it's not working

 set $tracking_id 'UA-12345678-9';
sub_filter '' '';

and i try to use

add_before_body /file.html

it's give me error page not loading

and i try to use

add_after_body /file.html

it's working good , but it's set code out html of page


问:
Odd behavior with SSRS and table spacing on a new page
In my report in SSRS, I have about .2 inches of space between the headers and tables. However, I have an issue where I have a table that is multiple pages long, and there ends up being no space between the table and the next row on the new page, like so:

And this is what my report likes in the viewer. Note that my .2 inches of white space is inside each subreport.

Is there anything to be done about this?

答: If moving the subreports a few pixels away from the tablix doesn't help, I like to add another row to the bottom of the tablix and set the BorderStyle to None for the extra row in the text box properties. This forces spacing between elements and is not visible in the rendered report.


问:
How can WebApi ChallengeResult be incorporated into an Angular2 SPA?
Context

We are migrating a web application using Asp.Net Core (Web Api) to use an Angular2
 Single Page Application (SPA) front end. The application was initially made with "Individual User Accounts". We have been converting the cshtml views to Angular2 components, the controller methods to produce Json, even incorporating JWT for authentication.

I have been using this Configuring Google authentication microsoft documentation.

Problem

The issue is illustrated by the following two controller methods. The LinkLogin method returns a ChallengeResult action. Obviously this cannot be converted to JSON. I presume this result is supposed to cause the browser to redirect to the external login provider, then automatically redirect to LinkLoginCallback.

```<code>    [HttpPost]
    public async Task<IActionResult> LinkLogin([FromBody] string provider)
    {
        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.Authentication.SignOutAsync(externalCookieScheme);

        // Request a redirect to the external login provider to link a login for the current user
        string redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage");
        var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, userManager.GetUserId(User));
        return Challenge(properties, provider);
    }

    [HttpPost]
    [Produces("application/json")]
    public async Task<ActionResult> LinkLoginCallback()
    {
        User user = await userManager.GetUserAsync(User);
        if (user == null)
            return Json(false);

        ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync(await userManager.GetUserIdAsync(user));
        if (info == null)
            return Json(false);

        IdentityResult result = await userManager.AddLoginAsync(user, info);
        if (result.Succeeded)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.Authentication.SignOutAsync(externalCookieScheme);
            return Json(true);
        }

        return Json(false);
    }
</code>```

If I do attempt to call LinkLogin from Angular I get this response:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53462' is therefore not allowed access. The response had HTTP status code 405.

答:
So I ended up coming up with a solution that avoids "ChallengeResult" by modifying the flow between Angular2 and the WebApi.

Added the angular2-social-login npm package to the angular app (following all their easy instructions for setup).

Merged both controller methods into one. The ExternalLoginViewModel parameter is a simple class with Email, ProviderKey and LoginProvider properties (populated in Angular in step 3):

```<code>[HttpPost]
[Produces("application/json")]
public async Task<ActionResult> LinkLogin([FromBody] ExternalLoginViewModel info)
{
    if (ModelState.IsValid)
    {
        User user = await userManager.GetUserAsync(User);
        if (user != null)
        {
            IdentityResult result = await userManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.LoginProvider));
            if (result.Succeeded)
                return Json(true);
        }
    }
    return Json(false);
}
</code>```

Changed the Angular2 client to use the social media package to get the credentials needed for the web api. Here is my LinkProvider method demonstrating the connection: (this.service.LinkLogin calls the LinkLogin controller method)

```<code>public async LinkProvider(providerName: string): Promise<void>
{
    const result: any = await this.auth.login(providerName).toPromise();
    const success: boolean = await this.service.LinkLogin({
         email: result.email,
         loginProvider: result.provider,
         providerKey: result.uid
    });

    // Handle link response here
}
</code>```

Body:
Context

We are migrating a web application using Asp.Net Core (Web Api) to use an Angular2
 Single Page Application (SPA) front end. The application was initially made with "Individual User Accounts". We have been converting the cshtml views to Angular2 components, the controller methods to produce Json, even incorporating JWT for authentication.

I have been using this Configuring Google authentication microsoft documentation.

Problem

The issue is illustrated by the following two controller methods. The LinkLogin method returns a ChallengeResult action. Obviously this cannot be converted to JSON. I presume this result is supposed to cause the browser to redirect to the external login provider, then automatically redirect to LinkLoginCallback.

    [HttpPost]
    public async Task<IActionResult> LinkLogin([FromBody] string provider)
    {
        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.Authentication.SignOutAsync(externalCookieScheme);

        // Request a redirect to the external login provider to link a login for the current user
        string redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage");
        var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, userManager.GetUserId(User));
        return Challenge(properties, provider);
    }

    [HttpPost]
    [Produces("application/json")]
    public async Task<ActionResult> LinkLoginCallback()
    {
        User user = await userManager.GetUserAsync(User);
        if (user == null)
            return Json(false);

        ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync(await userManager.GetUserIdAsync(user));
        if (info == null)
            return Json(false);

        IdentityResult result = await userManager.AddLoginAsync(user, info);
        if (result.Succeeded)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.Authentication.SignOutAsync(externalCookieScheme);
            return Json(true);
        }

        return Json(false);
    }

If I do attempt to call LinkLogin from Angular I get this response:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53462' is therefore not allowed access. The response had HTTP status code 405.

Body:
So I ended up coming up with a solution that avoids "ChallengeResult" by modifying the flow between Angular2 and the WebApi.

Added the angular2-social-login npm package to the angular app (following all their easy instructions for setup).

Merged both controller methods into one. The ExternalLoginViewModel parameter is a simple class with Email, ProviderKey and LoginProvider properties (populated in Angular in step 3):

[HttpPost]
[Produces("application/json")]
public async Task<ActionResult> LinkLogin([FromBody] ExternalLoginViewModel info)
{
    if (ModelState.IsValid)
    {
        User user = await userManager.GetUserAsync(User);
        if (user != null)
        {
            IdentityResult result = await userManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.LoginProvider));
            if (result.Succeeded)
                return Json(true);
        }
    }
    return Json(false);
}

Changed the Angular2 client to use the social media package to get the credentials needed for the web api. Here is my LinkProvider method demonstrating the connection: (this.service.LinkLogin calls the LinkLogin controller method)

public async LinkProvider(providerName: string): Promise<void>
{
    const result: any = await this.auth.login(providerName).toPromise();
    const success: boolean = await this.service.LinkLogin({
         email: result.email,
         loginProvider: result.provider,
         providerKey: result.uid
    });

    // Handle link response here
}


问:
Javascript - strip out occurrences of u' in JSON string, parse is returning unexpected token
I have a textfield in a database that contains the results of a python json.dumps(list_instance) operation.  As such, the internal fields have a u' prefix, and break the browser's JSON.parse() function.

An example of the JSON string is

```<code>"density": "{u'Penobscot': 40.75222856500098, u'Sagadahoc':
  122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec':
  123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland':
  288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock':
  30.698239582715903, u'Washington': 12.368718341168325, u'Aroostook':
  10.827378163074039, u'York': 183.47612497543722, u'Franklin':
  16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset':
  12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin':
  208.75502815768303}"
</code>```

What I'd like to do is replace those occurrences of u' with a '(single-quote).  I've tried

```<code>function renderValues(data){
   var pop = JSON.parse(data.density.replace(/u'/g, "'"));
}
</code>```

but I'm always getting a unexpected token ' exception.  Since many of the possible key fields may contain a u, it is not feasable to just delete that character.  How can I find all instances of u' and replace with ' without getting the exception?

答:
a little bit old in the answer but if there is no way to change or access the server response try with:

```<code>var strExample = {'att1':u'something with u'};

strExample.replace(/u'[\}|\,]/g, "ç'").replace(/u'/g, "'").replace(/ç'/g, "u'");

//{'att1':'something with u'};
</code>```

The first replace will handle the u' that are in the trailing part of the string in the object changing it to 'ç' character

then removing the u from the phyton unicode and finally change it to u' like the original

Body:
I have a textfield in a database that contains the results of a python json.dumps(list_instance) operation.  As such, the internal fields have a u' prefix, and break the browser's JSON.parse() function.

An example of the JSON string is

"density": "{u'Penobscot': 40.75222856500098, u'Sagadahoc':
  122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec':
  123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland':
  288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock':
  30.698239582715903, u'Washington': 12.368718341168325, u'Aroostook':
  10.827378163074039, u'York': 183.47612497543722, u'Franklin':
  16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset':
  12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin':
  208.75502815768303}"

What I'd like to do is replace those occurrences of u' with a '(single-quote).  I've tried

function renderValues(data){
   var pop = JSON.parse(data.density.replace(/u'/g, "'"));
}

but I'm always getting a unexpected token ' exception.  Since many of the possible key fields may contain a u, it is not feasable to just delete that character.  How can I find all instances of u' and replace with ' without getting the exception?

Body:
a little bit old in the answer but if there is no way to change or access the server response try with:

var strExample = {'att1':u'something with u'};

strExample.replace(/u'[\}|\,]/g, "ç'").replace(/u'/g, "'").replace(/ç'/g, "u'");

//{'att1':'something with u'};

The first replace will handle the u' that are in the trailing part of the string in the object changing it to 'ç' character

then removing the u from the phyton unicode and finally change it to u' like the original


问:
Simple solution for 3 circles (images) sitting horizontally equidistant apart and aligned
So for 3 days all I've been trying to do is have:

3 images shaped into circles

sitting aligned horizontally, equal distance apart

taking up central 70% of the screen

where all heights and widths are based on % (so they adjust with resizing of the browsers)

It seems like such a simple task, but after 3 days and asking multiple questions, I'm getting nowhere. Please, can someone write me a code to achieve this?

If it helps, I have this circle code so far:

Thanks if you can help me

(I am new to coding)

<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">
   <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Welcome to RyanTeaches

Activities

Helllllloooooooooo

```

答:
You can use flex with justify-content to either space-between or space-around (or space-evenly - a new property that isn't well supported, only works in firefox) depending on what you mean by having the elements equidistant apart (read more about that property here). Set a flex-basis on the flex children to establish their width, then nest your elements with the background inside of the flex child so you can use padding-bottom: 100% to make the element as tall as it is wide so that it's a square - or a perfect circle with your border radius.

#container1 {
  height: 50vh;
  display: flex;
  justify-content: space-around;
}

#container1 > div {
  flex: 0 0 23%;
}

.img-circular1,
.img-circular2,
.img-circular3 {
  background-size: cover;
  border-radius: 50%;
  padding-bottom: 100%;
}

.img-circular1 {
  background-image: url('https://i.stack.imgur.com/2C22p.jpg');
}

.img-circular2 {
  background-image: url('https://i.stack.imgur.com/mBNlv.png?s=328&g=1');
}

.img-circular3 {
  background-image: url('http://kenwheeler.github.io/slick/img/lazyfonz2.png');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="navigation"></div>

<div class="parallax"><h5 id="header"><b>Welcome to RyanTeaches</b></h5></div>

<!--<img src="bg.jpg" style="top:60px;height: 510px;min-width: 100%;">-->
<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div>

<div id="container1">
    <div><div class="img-circular1"></div></div>
    <div><div class="img-circular2"></div></div>
    <div><div class="img-circular3"></div></div>
</div>

<div id="content" style="margin-top: 100px;">
<p style="padding-bottom: 300px;">Helllllloooooooooo</p>

</div>

<script src="nav.js"></script>
<script src="template.js"></script>
</body></code>```

Body:
You can use flex with justify-content to either space-between or space-around (or space-evenly - a new property that isn't well supported, only works in firefox) depending on what you mean by having the elements equidistant apart (read more about that property here). Set a flex-basis on the flex children to establish their width, then nest your elements with the background inside of the flex child so you can use padding-bottom: 100% to make the element as tall as it is wide so that it's a square - or a perfect circle with your border radius.

#container1 {
  height: 50vh;
  display: flex;
  justify-content: space-around;
}

#container1 > div {
  flex: 0 0 23%;
}

.img-circular1,
.img-circular2,
.img-circular3 {
  background-size: cover;
  border-radius: 50%;
  padding-bottom: 100%;
}

.img-circular1 {
  background-image: url('https://i.stack.imgur.com/2C22p.jpg');
}

.img-circular2 {
  background-image: url('https://i.stack.imgur.com/mBNlv.png?s=328&g=1');
}

.img-circular3 {
  background-image: url('http://kenwheeler.github.io/slick/img/lazyfonz2.png');
}

<body>
<div id="navigation"></div>

<div class="parallax"><h5 id="header"><b>Welcome to RyanTeaches</b></h5></div>

<!--<img src="bg.jpg" style="top:60px;height: 510px;min-width: 100%;">-->
<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div>

<div id="container1">
    <div><div class="img-circular1"></div></div>
    <div><div class="img-circular2"></div></div>
    <div><div class="img-circular3"></div></div>
</div>

<div id="content" style="margin-top: 100px;">
<p style="padding-bottom: 300px;">Helllllloooooooooo</p>

</div>

<script src="nav.js"></script>
<script src="template.js"></script>
</body>


问:
Checking whole string with a regex
I'm trying to check if a string is a number, so the regex "\d+" seemed good. However that regex also fits "78.46.92.168:8000" for some reason, which I do not want, a little bit of code:

```<code>class Foo():
    _rex = re.compile("\d+")
    def bar(self, string):
         m = _rex.match(string)
         if m != None:
             doStuff()
</code>```

And doStuff() is called when the ip adress is entered. I'm kind of confused, how does "." or ":" match "\d"?

答:
There are a couple of options in Python to match an entire input with a regex.

Python 2 and 3

In Python 2 and 3, you may use

```<code>re.match(r'\d+$') # re.match anchors the match at the start of the string, so $ is what remains to add
</code>```

or - to avoid matching before the final \n in the string:

```<code>re.match(r'\d+\Z') # \Z will only match at the very end of the string
</code>```

Or the same as above with re.search method requiring the use of ^ / \A start-of-string anchor as it does not anchor the match at the start of the string:

```<code>re.search(r'^\d+$')
re.search(r'\A\d+\Z')
</code>```

Note that \A is an unambiguous string start anchor, its behavior cannot be redefined with any modifiers (re.M / re.MULTILINE can only redefine the ^  and $ behavior).

Python 3

All those cases described in the above section and one more useful method, re.fullmatch (also present in the PyPi regex module):

If the whole string matches the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

So, after you compile the regex, just use the appropriate method:

```<code>_rex = re.compile("\d+")
if _rex.fullmatch(s):
    doStuff()
</code>```

Title: Checking whole string with a regex

Body:
I'm trying to check if a string is a number, so the regex "\d+" seemed good. However that regex also fits "78.46.92.168:8000" for some reason, which I do not want, a little bit of code:

class Foo():
    _rex = re.compile("\d+")
    def bar(self, string):
         m = _rex.match(string)
         if m != None:
             doStuff()

And doStuff() is called when the ip adress is entered. I'm kind of confused, how does "." or ":" match "\d"?

Body:
There are a couple of options in Python to match an entire input with a regex.

Python 2 and 3

In Python 2 and 3, you may use

re.match(r'\d+$') # re.match anchors the match at the start of the string, so $ is what remains to add

or - to avoid matching before the final \n in the string:

re.match(r'\d+\Z') # \Z will only match at the very end of the string

Or the same as above with re.search method requiring the use of ^ / \A start-of-string anchor as it does not anchor the match at the start of the string:

re.search(r'^\d+$')
re.search(r'\A\d+\Z')

Note that \A is an unambiguous string start anchor, its behavior cannot be redefined with any modifiers (re.M / re.MULTILINE can only redefine the ^  and $ behavior).

Python 3

All those cases described in the above section and one more useful method, re.fullmatch (also present in the PyPi regex module):

If the whole string matches the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

So, after you compile the regex, just use the appropriate method:

_rex = re.compile("\d+")
if _rex.fullmatch(s):
    doStuff()

ContentLicense: CC BY-SA 4.0


问:
Arrays and Pass-By-Reference
I am new to coding and need to know how to display the Max, Min, Avg, and the new normalized values of my array. I have the max min and avg working correctly as of now, but am very confused on how i would have my function display the proper new values of the array. The point is to use the function;
xi'=(xi-min)/(max-min)
My current code is the following:</p>

```<code>#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    max = 0;
    min = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i = 0; i < size; i++) {
        sum += data[i];
        if ( max < data[i]) {
            max = data[i];
        }
        if (min > data[i]) {
            min = data[i];
        }
    }
    avg = sum/size;

    for (i = 0; i < size; i++){
        data[i] = (data[i]-min)/(max-min);
    }
}

int main()
{
    double data[] = {-10.0,0.0,20.0,30.0,500.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 5, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    cout << data;
    return 0;
}
</code>```

答: data only holds the address of the array, which, in your case, is a pointer to a double, you need iterate the array and print out each value individually.

Title: Arrays and Pass-By-Reference

Body:
I am new to coding and need to know how to display the Max, Min, Avg, and the new normalized values of my array. I have the max min and avg working correctly as of now, but am very confused on how i would have my function display the proper new values of the array. The point is to use the function;
xi'=(xi-min)/(max-min)
My current code is the following:

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    max = 0;
    min = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i = 0; i < size; i++) {
        sum += data[i];
        if ( max < data[i]) {
            max = data[i];
        }
        if (min > data[i]) {
            min = data[i];
        }
    }
    avg = sum/size;

    for (i = 0; i < size; i++){
        data[i] = (data[i]-min)/(max-min);
    }
}

int main()
{
    double data[] = {-10.0,0.0,20.0,30.0,500.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 5, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    cout << data;
    return 0;
}


问:
Detect if user "deselects" marker on google map
I'm looking for a way to detect when a marker on Google map is deselected. I have a Sliding drawer, where the handle is invisible until the user clicks on the marker, and I want to make it invisible again once the marker is "deselected". I've tried with marker.isInfoWindowShown() but I couldn't get it to work.

答:
This is useful only when the marker has an Info Window. When the Info Window appears on marker click and closes when clicking outside the marker. You can detect that event in the map.

```<code>// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });
</code>```

Body:
This is useful only when the marker has an Info Window. When the Info Window appears on marker click and closes when clicking outside the marker. You can detect that event in the map.

// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });


问:
How To handle multi-selection item in a scatterView
I am using Surface Toolkit Beta version for .NET 4.0. I am trying to select multiple items in a ScatterView. But I think I have to do it with code, can any one help me please?

答:
It all depends on how you would want to implement multiple selection with a MT UI. In a traditional mouse & keyboard UI, the user can usually make a multiple selection by one of the following means:

Clicking additional items while holding a modifier key (shift or ctrl) in order to extend the current selection, or

drawing a selection rectangle / lasso around the items to be included in the selection.

Multitouch UIs normally don't provide for keyboard input (unless your scenario specifically requires it), so the question is: What kind of multiple selection would you want in your ScatterView? Something like a modifier key, or dragging a selection rectangle?


问:
GitHub Atom - Remove the center line in the editor
I just downloaded the GitHub Atom Editor and I'm customizing it.

But I couldn't remove the line that is the middle of the editor.

Anyone help me out how to remove that line?

答:
In Atom v1.18.0:

Menu - > Packages -> Settings View -> Manage Packages
Scroll to the bottom and click "Disable" on wrap-guide package

Screenshot - Manage Packages:

Screenshot - wrap-guide:


问:
Java: Difference between two lists
My company's cat-herding application tracks a convoy of cats. Periodically, it needs to compare previousOrder to currentOrder (each is an ArrayList<Cat>) and notify the cat-wranglers of any changes.

Each cat is unique and can only appear once in each list (or not at all). Most of the time, the previousOrder and currentOrder lists have the same contents, in the same order, but any of the following can happen (from more frequent to less frequent):

The order of cats is scrambled completely

Cats individually move up or down in the list

New cats join, at a specific point in the convoy

Cats leave the convoy

This appears like an edit distance problem to me. Ideally, I am looking for an algorithm that determines the steps required to make previousOrder match currentOrder:

MOVE Fluffy to position 12

INSERT Snuggles at position 37

DELETE Mr. Chubbs

etc.

The algorithm should also recognize scenario #1, in which case the new order is communicated in its entirety.

What's the best approach for this?

(This post and that post pose similar questions, but they are both dealing with sorted lists. Mine are ordered, but unsorted.)

EDIT

The Levenshtein algorithm is a great suggestion, but I'm concerned about the time/space requirement of creating a matrix. My main goal is to determine and communicate the changes as quickly as possible. Something that is faster than finding the additions and sending message along the lines of "Here are the new cats, and here is the current order."

答:
I recently had to do this, except items could exist multiple times. This complicated things, but I was able to do it using look-ahead counters and some other craziness. It looks a lot like Rob's solution, so thanks to him for getting me started!

First off, let's assume that we want to return the list of operations that will transform the first list into the second:

```<code>public interface Operation {
    /**
     * Apply the operation to the given list.
     */
    void apply(List<String> keys);
}
</code>```

and we have some helper methods to construct operations. You actually don't need a "move" operation, and you could even have a "swap" as well (or instead), but this is what I went with:

```<code>Operation delete(int index) { ... }
Operation insert(int index, String key) { ... }
Operation move(int from, int to) { ... }
</code>```

Now we'll define a special class to hold our look-ahead counts:

```<code>class Counter {
    private Map<String, Integer> counts;

    Counter(List<String> keys) {
        counts = new HashMap<>();

        for (String key : keys) {
            if (counts.containsKey(key)) {
                counts.put(key, counts.get(key) + 1);
            } else {
                counts.put(key, 1);
            }
        }
    }

    public int get(String key) {
        if (!counts.containsKey(key)) {
            return 0;
        }

        return counts.get(key);
    }

    public void dec(String key) {
        counts.put(key, counts.get(key) - 1);
    }
}
</code>```

And a helper method to get the index of the next key in the list:

```<code>int next(List<String> list, int start, String key) {
    for (int i = start; i < list.size(); i++) {
        if (list.get(i).equals(key)) {
            return i;
        }
    }

    throw new RuntimeException("next index not found for " + key);
}
</code>```

Now we're ready to do the transform:

```<code>List<Operation> transform(List<String> from, List<String> to) {
    List<Operation> operations = new ArrayList<>();

    // make our own copy of the first, that we can mutate
    from = new ArrayList<>(from);

    // maintain lookahead counts
    Counter fromCounts = new Counter(from);
    Counter toCounts = new Counter(to);

    // do all our deletes first
    for (int i = 0; i < from.size(); i++) {
        String current = from.get(i);

        if (fromCounts.get(current) > toCounts.get(current)) {
            Operation op = delete(i);
            operations.add(op);
            op.apply(from);
            fromCounts.dec(current);
            i--;
        }
    }

    // then one more iteration for the inserts and moves
    for (int i = 0; i < to.size(); i++) {
        String current = to.get(i);

        if (from.size() > i && from.get(i).equals(current)) {
            fromCounts.dec(current);
            continue;
        }

        if (fromCounts.get(current) > 0) {
            Operation op = move(next(from, i + 1, current), i);
            operations.add(op);
            op.apply(from);

            fromCounts.dec(current);
        } else {
            Operation op = insert(i, current);
            operations.add(op);
            op.apply(from);
        }
    }

    return operations;
}
</code>```

It's a bit tricky to get your head around, but basically you do the deletes so that you know for every key you are either inserting or moving. Then you run through the list again and if there's enough, you move one from the part of the list your haven't seen yet, otherwise insert. By the time you get to the end, it all lines up.

Title: Java: Difference between two lists

Body:
I recently had to do this, except items could exist multiple times. This complicated things, but I was able to do it using look-ahead counters and some other craziness. It looks a lot like Rob's solution, so thanks to him for getting me started!

First off, let's assume that we want to return the list of operations that will transform the first list into the second:

public interface Operation {
    /**
     * Apply the operation to the given list.
     */
    void apply(List<String> keys);
}

and we have some helper methods to construct operations. You actually don't need a "move" operation, and you could even have a "swap" as well (or instead), but this is what I went with:

Operation delete(int index) { ... }
Operation insert(int index, String key) { ... }
Operation move(int from, int to) { ... }

Now we'll define a special class to hold our look-ahead counts:

class Counter {
    private Map<String, Integer> counts;

    Counter(List<String> keys) {
        counts = new HashMap<>();

        for (String key : keys) {
            if (counts.containsKey(key)) {
                counts.put(key, counts.get(key) + 1);
            } else {
                counts.put(key, 1);
            }
        }
    }

    public int get(String key) {
        if (!counts.containsKey(key)) {
            return 0;
        }

        return counts.get(key);
    }

    public void dec(String key) {
        counts.put(key, counts.get(key) - 1);
    }
}

And a helper method to get the index of the next key in the list:

int next(List<String> list, int start, String key) {
    for (int i = start; i < list.size(); i++) {
        if (list.get(i).equals(key)) {
            return i;
        }
    }

    throw new RuntimeException("next index not found for " + key);
}

Now we're ready to do the transform:

List<Operation> transform(List<String> from, List<String> to) {
    List<Operation> operations = new ArrayList<>();

    // make our own copy of the first, that we can mutate
    from = new ArrayList<>(from);

    // maintain lookahead counts
    Counter fromCounts = new Counter(from);
    Counter toCounts = new Counter(to);

    // do all our deletes first
    for (int i = 0; i < from.size(); i++) {
        String current = from.get(i);

        if (fromCounts.get(current) > toCounts.get(current)) {
            Operation op = delete(i);
            operations.add(op);
            op.apply(from);
            fromCounts.dec(current);
            i--;
        }
    }

    // then one more iteration for the inserts and moves
    for (int i = 0; i < to.size(); i++) {
        String current = to.get(i);

        if (from.size() > i && from.get(i).equals(current)) {
            fromCounts.dec(current);
            continue;
        }

        if (fromCounts.get(current) > 0) {
            Operation op = move(next(from, i + 1, current), i);
            operations.add(op);
            op.apply(from);

            fromCounts.dec(current);
        } else {
            Operation op = insert(i, current);
            operations.add(op);
            op.apply(from);
        }
    }

    return operations;
}

It's a bit tricky to get your head around, but basically you do the deletes so that you know for every key you are either inserting or moving. Then you run through the list again and if there's enough, you move one from the part of the list your haven't seen yet, otherwise insert. By the time you get to the end, it all lines up.


Title: Merge two columns, set value based upon original

Body:
I have a data.frame looking like this:

date1                  date2
2015-09-17 03:07:00    2015-09-17 11:53:00
2015-09-17 08:00:00    2015-09-18 11:48:59
2015-09-18 15:58:00    2015-09-22 12:14:00
2015-09-22 12:14:00    2015-09-24 13:58:21

I'd like to combine these two into one column, something like:

dates
2015-09-17 03:07:00
2015-09-17 11:53:00
2015-09-17 08:00:00
2015-09-18 11:48:59
2015-09-18 15:58:00
2015-09-22 12:14:00
2015-09-22 12:14:00
2015-09-24 13:58:21

Please note that dates (like the last but one and the last but two) can be equal. Now I'd like to add a column 'value'. For every date that has it's origin in date1, the value should be 1, if it's origin is in date2, it should be 2.

Adding a new column is obvious. Merging works fine. I've used:

df <- as.data.frame(df$date1)
df <- data.frame(date1 = c(df$date1, test$date2 ))

That works perfectly fine for the merging of the columns, but how to get the correct value for df$value?

The result should be:

dates                  value
2015-09-17 03:07:00    1
2015-09-17 11:53:00    2
2015-09-17 08:00:00    1
2015-09-18 11:48:59    2
2015-09-18 15:58:00    1
2015-09-22 12:14:00    1
2015-09-22 12:14:00    2
2015-09-24 13:58:21    1

Body:
Can't you just do something like this?

dates1 <- data.frame(dates = c("2015-09-17 03:07:00",
                          "2015-09-17 08:00:00",
                          "2015-09-18 15:58:00",
                          "2015-09-22 12:14:00"), value = 1)

dates2 <- data.frame(dates = c("2015-09-17 11:53:00",
                          "2015-09-18 11:48:59",
                          "2015-09-22 12:14:00",
                          "2015-09-24 13:58:21"), value = 2)

# row-bind the two data.frames
df <- rbind(dates1, dates2)

# if "dates" is in a string format, convert to timestamp
df$dates <- strptime(df$dates, format = "%Y-%m-%d %H:%M:%S")

# order by "dates"
df[order(df$dates),]

# result:
                dates value
1 2015-09-17 03:07:00     1
2 2015-09-17 08:00:00     1
5 2015-09-17 11:53:00     2
6 2015-09-18 11:48:59     2
3 2015-09-18 15:58:00     1
4 2015-09-22 12:14:00     1
7 2015-09-22 12:14:00     2
8 2015-09-24 13:58:21     2


问:
Intellij SVN keeps asking for path to certificate when there is none
A slightly different version of this
Subversion in Intellij keeps asking for authentication

I enter my credentials just fine. Once I enter the correct credentials it takes me to a popup that asks for my path to certificate, and certificate passphrase.

This didn't used to happen until I changed my SVN password. Prior to this, simply enter in my SVN credentials would work fine without issue. Hitting cancel on that gives me an SVN:E175013 error, and hitting OK closes then reopens the same box.

The same issue does not happen in Eclipse. Simply providing the userid and pwd will allow me to access SVN, this is only happening in intellij.

So I cleared the SVN settings for my PC in the %APPDATA% path, as well as my Intellij svn's directory (.IntelliJIdea2017.1\system) I cleaned vcs/vcsCache and vcs-users in that folder.

My Intellij info

IntelliJ IDEA 2017.1.3

Build #IU-171.4424.56

JRE: 1.8.0_112-release-736-b21 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Windows 7 6.1

I'm using svn 1.9.5.1210.

答:
Ultimately resolved the issue by uninstalling Intellij and all cache, settings everything. Then reinstall. Was able to fetch from SVN henceforth.

I wasn't able to test Dimitri's note before I did the reinstallation, but it sounds like it could be it.

The wrong password can be saved by IDE in a storage according to Settings - Appearance & Behavior - System - Passwords. Check the storage, probably set IDE to not remember passwords and restart. – Dmitriy Smirnov


问:
sphinx-build fail - autodoc can't import/find module
I'm trying to get started with Sphinx and seem to have relentless problems.

Command: docs/sphinx-quickstart

I answer all the questions and everything works fine.

Command: docs/ls

Everything looks normal. Result: build  Makefile  source

Command: sphinx-build -d build/doctrees source build/html

It seems to work.  I was able to open the index.html file and see a "shell" of what I'm wanting.

When I try and put my actual source code as the source folder I run into problems.

Command: sphinx-build -d build/doctrees ../ys_utils build/html

Result:

```<code>Making output directory...
Running Sphinx v1.1.3
loading pickled environment... not yet created
No builder selected, using default: html
loading intersphinx inventory from http://docs.python.org/objects.inv...
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils.test_validate_ut
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils.git_utils
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named setup.setup

/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:4: WARNING: autodoc can't import/find module 'ys_utils', it reported error: "No module named ys_utils", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:10: WARNING: autodoc can't import/find module 'ys_utils.test_validate_ut', it reported error: "No module named ys_utils.test_validate_ut", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:12: WARNING: don't know which module to import for autodocumenting u'UnitTests' (try placing a "module" or "currentmodule" directive in the document, or giving an explicit module name)
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:18: WARNING: autodoc can't import/find module 'ys_utils.git_utils', it reported error: "No module named ys_utils.git_utils", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:24: WARNING: autodoc can't import/find module 'setup.setup', it reported error: "No module named setup.setup", please check your spelling and sys.path
WARNING: master file /home/ricomoss/workspace/nextgen/ys_utils/index.rst not found
looking for now-outdated files... none found
pickling environment... done
checking consistency... /home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:: WARNING: document isn't included in any toctree
done
preparing documents... done
writing output... [ 50%] index
Exception occurred:
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/environment.py", line 1213, in get_doctree
    f = open(doctree_filename, 'rb')
IOError: [Errno 2] No such file or directory: '/home/ricomoss/workspace/nextgen/docs/build/doctrees/index.doctree'
The full traceback has been saved in /tmp/sphinx-err-jjJ7gM.log, if you want to report the issue to the developers.
Please also report this if it was a user error, so that a better error message can be provided next time.
Either send bugs to the mailing list at <http://groups.google.com/group/sphinx-dev/>,
or report them in the tracker at <http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!
</code>```

What is wrong, and how can I fix it?

Edit:

I'd like to be able to use a Makefile to handle this.  As of now I have two folders in my project.

nextgen/ls

docs ys_utils

I need nextgen/docs/Makefile to generate the HTML for ys_utils and all other modules I'm going to have.

答:
solution

It sounds like os.path.append() is working OK for folks, but if you follow the conf.py template, you would insert the module path to the front of sys.path using os.path.insert(0, ...), and just add an extra .

```<code>import os
import sys
sys.path.insert(0, os.path.abspath('..'))
</code>```

If you have setup your sphinx project to use separate build and source directories, that call should instead be:

```<code>sys.path.insert(0, os.path.abspath('../..'))
</code>```

about sys.path ...

To run python code, the python interpreter needs to know where it is. With the sphinx config being a python script, it's location needs to be made known, which is done by adding it the the sys.path variable using the insert method (see the docs on module search path).

The path added to sys.path in this case is a "relative" path, which is specified using dots. This is a general way of specifying the path, which allows the code to be moved and still point correctly to the correct path in your codebase.

. - current path of the conf.py

.. - parent path of the conf.py

../.. - parent of the parent path, etc.

I use linux, so directories are specified with a forward slash, but a cross-platform method for specifying parent directories can be acheived with pathlib.

```<code>from pathlib import Path

parent = Path(__file__).parent
parents_parent = Path(__file__).parents[1]
</code>```

Body:
I'm trying to get started with Sphinx and seem to have relentless problems.

Command: docs/sphinx-quickstart

I answer all the questions and everything works fine.

Command: docs/ls

Everything looks normal. Result: build  Makefile  source

Command: sphinx-build -d build/doctrees source build/html

It seems to work.  I was able to open the index.html file and see a "shell" of what I'm wanting.

When I try and put my actual source code as the source folder I run into problems.

Command: sphinx-build -d build/doctrees ../ys_utils build/html

Result:

Making output directory...
Running Sphinx v1.1.3
loading pickled environment... not yet created
No builder selected, using default: html
loading intersphinx inventory from http://docs.python.org/objects.inv...
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils.test_validate_ut
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named ys_utils.git_utils
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/ext/autodoc.py", line 321, in import_object
    __import__(self.modname)
ImportError: No module named setup.setup

/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:4: WARNING: autodoc can't import/find module 'ys_utils', it reported error: "No module named ys_utils", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:10: WARNING: autodoc can't import/find module 'ys_utils.test_validate_ut', it reported error: "No module named ys_utils.test_validate_ut", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:12: WARNING: don't know which module to import for autodocumenting u'UnitTests' (try placing a "module" or "currentmodule" directive in the document, or giving an explicit module name)
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:18: WARNING: autodoc can't import/find module 'ys_utils.git_utils', it reported error: "No module named ys_utils.git_utils", please check your spelling and sys.path
/home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:24: WARNING: autodoc can't import/find module 'setup.setup', it reported error: "No module named setup.setup", please check your spelling and sys.path
WARNING: master file /home/ricomoss/workspace/nextgen/ys_utils/index.rst not found
looking for now-outdated files... none found
pickling environment... done
checking consistency... /home/ricomoss/workspace/nextgen/ys_utils/ys_utils.rst:: WARNING: document isn't included in any toctree
done
preparing documents... done
writing output... [ 50%] index
Exception occurred:
  File "/usr/local/lib/python2.6/dist-packages/Sphinx-1.1.3-py2.6.egg/sphinx/environment.py", line 1213, in get_doctree
    f = open(doctree_filename, 'rb')
IOError: [Errno 2] No such file or directory: '/home/ricomoss/workspace/nextgen/docs/build/doctrees/index.doctree'
The full traceback has been saved in /tmp/sphinx-err-jjJ7gM.log, if you want to report the issue to the developers.
Please also report this if it was a user error, so that a better error message can be provided next time.
Either send bugs to the mailing list at <http://groups.google.com/group/sphinx-dev/>,
or report them in the tracker at <http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!

What is wrong, and how can I fix it?

Edit:

I'd like to be able to use a Makefile to handle this.  As of now I have two folders in my project.

nextgen/ls

docs ys_utils

I need nextgen/docs/Makefile to generate the HTML for ys_utils and all other modules I'm going to have.

Body:
solution

It sounds like os.path.append() is working OK for folks, but if you follow the conf.py template, you would insert the module path to the front of sys.path using os.path.insert(0, ...), and just add an extra .

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

If you have setup your sphinx project to use separate build and source directories, that call should instead be:

sys.path.insert(0, os.path.abspath('../..'))

about sys.path ...

To run python code, the python interpreter needs to know where it is. With the sphinx config being a python script, it's location needs to be made known, which is done by adding it the the sys.path variable using the insert method (see the docs on module search path).

The path added to sys.path in this case is a "relative" path, which is specified using dots. This is a general way of specifying the path, which allows the code to be moved and still point correctly to the correct path in your codebase.

. - current path of the conf.py

.. - parent path of the conf.py

../.. - parent of the parent path, etc.

I use linux, so directories are specified with a forward slash, but a cross-platform method for specifying parent directories can be acheived with pathlib.

from pathlib import Path

parent = Path(__file__).parent
parents_parent = Path(__file__).parents[1]


问:
How to check slow_query_log for the current project I'm working on?
I've read good articles on enabling and logging slow_query_log, tried and it works.

But I would like to understand how to use it in real life scenarios.

I set the slow query log globally like below, which means its applicable to all databases?

```<code>SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = X;
SET GLOBAL slow_query_log_file = '/path/filename';
</code>```

and so forth.....

Now, the real life scenario:

My PC has multiple projects hosted by wamp server. But now I want to
check the queries for project A. How do I check which queries in this
project works slowly, assuming they are using one database only?

How would the slow_query_log know that which database I'm checking? Also how the process flows? I mean, once I enabled the slow_query_log, do I type the queries written in the project one by one to see which one slowing down?

Or once I enabled slow_query_log, I start making all the calls through the system to the database and then later come back and check what has been triggered by slow_query_log during the process?

Incidentally, I prefer using CMD to execute the slow_query_log

答:
Once you have the file, use one of these to summarize it.  Then study the first few queries.</p>

```<code>mysqldumpslow -s t

pt-query-digest
</code>```

Body:
I've read good articles on enabling and logging slow_query_log, tried and it works.

But I would like to understand how to use it in real life scenarios.

I set the slow query log globally like below, which means its applicable to all databases?

SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = X;
SET GLOBAL slow_query_log_file = '/path/filename';

and so forth.....

Now, the real life scenario:

My PC has multiple projects hosted by wamp server. But now I want to
check the queries for project A. How do I check which queries in this
project works slowly, assuming they are using one database only?

How would the slow_query_log know that which database I'm checking? Also how the process flows? I mean, once I enabled the slow_query_log, do I type the queries written in the project one by one to see which one slowing down?

Or once I enabled slow_query_log, I start making all the calls through the system to the database and then later come back and check what has been triggered by slow_query_log during the process?

Incidentally, I prefer using CMD to execute the slow_query_log

Body:
Once you have the file, use one of these to summarize it.  Then study the first few queries.

mysqldumpslow -s t

pt-query-digest


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
If you store a date in the database, then store it as a date not as a string. Then you will only have one format: what the user typed in.

Using DateTime.Parse (or TryParse, or the "Exact" versions) you can convert from the typed-in string to a DateTime value.


问:
.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList
when I share my app to other one then my app crash but when I run my app direct fron studio then app run properly but I have seen all solution but nothing works for me.

java.lang.RuntimeException: Unable to get provider
  com.google.firebase.provider.FirebaseInitProvider:
  java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.amit.workoutdocent-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.amit.workoutdocent-1/lib/arm,
  /vendor/lib, /system/lib]]
                                                                                at
  android.app.ActivityThread.installProvider(ActivityThread.java:6948)
                                                                                at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:6540)
                                                                                at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:6480)
                                                                                at android.app.ActivityThread.access$1800(ActivityThread.java:230)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1888)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.amit.workoutdocent-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.amit.workoutdocent-1/lib/arm,
  /vendor/lib, /system/lib]]
                                                                                at
  dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                                at
  android.app.ActivityThread.installProvider(ActivityThread.java:6933)
                                                                                at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:6540)
                                                                                at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:6480)
                                                                                at android.app.ActivityThread.access$1800(ActivityThread.java:230)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1888)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

答: Lowered my gradle version from 2.3.3 to 2.3.0 in build.gradle file, clean and build the project. Works fine now.</p>


问:
Permanently hide elements after form action
I have no idea how to achieve this effect so I'm farming it out in the hopes that someone knows of a standard method or work around that would allow me to hide certain elements after a form submission. I'm trying to hide (3) elements on the dashboard page of my site once the user has submitted a form.

Elements to hide:

.vc_tta-tab:nth-child(2), .vc_tta-tab:nth-child(3), .vc_tta-tab:nth-child(4)

Once the user has submitted a form the page redirects to a separate success page and then the user clicks a 'Back to Home' button to return to the dashboard. I need to be able to permanently hide these (3) elements on a 'per user' basis after the form has been submitted.

My question is, is this possible and how could I achieve this?

Specs:

Form Submission Method: Post

Classes: .vc_tta-tab:nth-child(2), .vc_tta-tab:nth-child(3), .vc_tta-tab:nth-child(4)

Any assistance would be greatly appreciated!

答:
Assuming you have correctly stored the login status in the session, you can do something like this:

```<code><!doctype html>
<html class="<?= $_SESSION["logged_in"] ? "logged_in" : "logged_out"?>">
<head>
    <style>
        html.logged_in .vc_tta-tab:nth-child(2),
        html.logged_in .vc_tta-tab:nth-child(3),
        html.logged_in .vc_tta-tab:nth-child(4) {
            display: none;
        }
    </style>
</head>
...
</code>```

That is, apply a class to an ancestor element and make a rule based on it. If that class doesn't appear, your elements will behave as they normally do.

Body:
Assuming you have correctly stored the login status in the session, you can do something like this:

<!doctype html>
<html class="<?= $_SESSION["logged_in"] ? "logged_in" : "logged_out"?>">
<head>
    <style>
        html.logged_in .vc_tta-tab:nth-child(2),
        html.logged_in .vc_tta-tab:nth-child(3),
        html.logged_in .vc_tta-tab:nth-child(4) {
            display: none;
        }
    </style>
</head>
...

That is, apply a class to an ancestor element and make a rule based on it. If that class doesn't appear, your elements will behave as they normally do.


问:
Best way to store and retrieve data to and from database in android
I am currently developing a a project with multiple number of tables. So I created separate classes for storage and retrieval of data of each table.

Is there any better way so that I can reduce the number of classes? I am a beginner, so I am really uncertain about this.

答:
Here is description of all basic storage techniques:

Which Android Data Storage Technique to use?

But as @345 mentioned, you should try Realm Db. Its way easier to store and manage your data with it, in comparison to some SQLight wrappers.


答:
You can achieve this by making your code dynamic. Like you create some generalized methods and send the keys (table name, column name, row name) and values on real time when you are accessing those tables. But you have to do a-lot of work to do this, because all your tables will be different in structure. So you have to create methods for each table in that class or you can handle all possible scenarios through conditions (if/else or switch case).

Check this example, I hope it will help you.

http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/

Title: Best way to store and retrieve data to and from database in android

Body:
I am currently developing a a project with multiple number of tables. So I created separate classes for storage and retrieval of data of each table.

Is there any better way so that I can reduce the number of classes? I am a beginner, so I am really uncertain about this.


问:
R - Checking multiple columns for multiple values - loop
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

```<code>DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498
</code>```

Code I tried to perform:

```<code>for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}
</code>```

What I would like my loop to perform:

```<code>DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE
</code>```

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you

答:
We can do this by looping through the columns, check using grepl to create a logical vector, then Reduce it to a single vector with |

```<code>df1$Illness <- Reduce(`|`, lapply(df1, grepl, pattern = "xxx"))
df1$Illness
#[1]  TRUE FALSE  TRUE  TRUE
</code>```

Body:
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498

Code I tried to perform:

for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}

What I would like my loop to perform:

DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you

Body:
We can do this by looping through the columns, check using grepl to create a logical vector, then Reduce it to a single vector with |

df1$Illness <- Reduce(`|`, lapply(df1, grepl, pattern = "xxx"))
df1$Illness
#[1]  TRUE FALSE  TRUE  TRUE


问:
Compare arrays and Return the Difference
I have an array A in memory created at runtime and another array B saved in a mongo database. How can I efficiently get all the elements from A that are not in B?

You can assume that the array stored in mongodb is several orders of magnitude bigger than the array created at runtime, for that reason I think that obtaining the full array from mongo and computing the result would not be efficient, but I have not found any query operation in mongo that allows me to compute the result I want.

Note that the $nin operator does the opposite of what I want, i.e., it retrieves the elements from B that are not in A.

Example:

Array A, created in my appliction at runtime, is [2, 3, 4].

Array B, stored in mongodb, is [1, 3, 5, 6, 7, 10].

The result I expect is [2, 4].

答:
The only things that "modify" the document in response are .aggregate() and .mapReduce(), where the former is the better option.

In that case you are asking for $setDifference which compares the "sets" and returns the "difference" between the two.

So representing a document with your array:

```<code>db.collection.insert({ "b": [1, 3, 5, 6, 7, 10] })
</code>```

Run the aggregation:

```<code>db.collection.aggregate([{ "$project": { "c": { "$setDifference": [ [2,3,4], "$b" ] } } }])
</code>```

Which returns:

```<code>{ "_id" : ObjectId("596005eace45be96e2cb221b"), "c" : [ 2, 4 ] }
</code>```

If you do not want "sets" and instead want to supply an array like [2,3,4,4] then you can compare with $filter and $in instead, if you have MongoDB 3.4 at least:

```<code>db.collection.aggregate([
  { "$project": {
    "c": {
      "$filter": {
        "input": [2,3,4,4],
        "as": "a",
        "cond": {
          "$not": { "$in": [ "$$a", "$b" ]  }
        }
      }
    }
  }}
])
</code>```

Or with $filter and $anyElementTrue in earlier versions:

```<code>db.collection.aggregate([
  { "$project": {
    "c": {
      "$filter": {
        "input": [2,3,4,4],
        "as": "a",
        "cond": {
          "$not": {
            "$anyElementTrue": {
              "$map": {
                "input": "$b",
                "as": "b",
                "in": {
                  "$eq": [ "$$a", "$$b" ]
                }
              }
            }
          }
        }
      }
    }
  }}
])
</code>```

Where both would return:

```<code>{ "_id" : ObjectId("596005eace45be96e2cb221b"), "c" : [ 2, 4, 4 ] }
</code>```

Which is of course "not a set" since the 4 was provided as input "twice" and is therefore returned "twice" as well.

Body:
The only things that "modify" the document in response are .aggregate() and .mapReduce(), where the former is the better option.

In that case you are asking for $setDifference which compares the "sets" and returns the "difference" between the two.

So representing a document with your array:

db.collection.insert({ "b": [1, 3, 5, 6, 7, 10] })

Run the aggregation:

db.collection.aggregate([{ "$project": { "c": { "$setDifference": [ [2,3,4], "$b" ] } } }])

Which returns:

{ "_id" : ObjectId("596005eace45be96e2cb221b"), "c" : [ 2, 4 ] }

If you do not want "sets" and instead want to supply an array like [2,3,4,4] then you can compare with $filter and $in instead, if you have MongoDB 3.4 at least:

db.collection.aggregate([
  { "$project": {
    "c": {
      "$filter": {
        "input": [2,3,4,4],
        "as": "a",
        "cond": {
          "$not": { "$in": [ "$$a", "$b" ]  }
        }
      }
    }
  }}
])

Or with $filter and $anyElementTrue in earlier versions:

db.collection.aggregate([
  { "$project": {
    "c": {
      "$filter": {
        "input": [2,3,4,4],
        "as": "a",
        "cond": {
          "$not": {
            "$anyElementTrue": {
              "$map": {
                "input": "$b",
                "as": "b",
                "in": {
                  "$eq": [ "$$a", "$$b" ]
                }
              }
            }
          }
        }
      }
    }
  }}
])

Where both would return:

{ "_id" : ObjectId("596005eace45be96e2cb221b"), "c" : [ 2, 4, 4 ] }

Which is of course "not a set" since the 4 was provided as input "twice" and is therefore returned "twice" as well.


问:
How often is file loaded from imported module?
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

```<code>import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--
</code>```

main.py

```<code>import lookup

--something something--

for f in files:
    print(lookup.map_file(f))
</code>```

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?

答:
As answered in the comments, but I'll expand a bit on it to really show why.

The question is, how many times do we load the JSON file (line 3 from lookup.py)

When lookup is imported, assuming there is no if __name__ == 'main' guard around it, mapping_dict (an object) is set to the contents of the json file. As well, the functions defined are each set assigned to a function object. You can test this by typing the function name without the parentheses at the end. You should see a memory pointer corresponding to the object

From there on, unless lookup.py is re-imported, mapping_dict is never reassigned or updated. Referencing the functions references the objects they were assigned to.

Body:
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--

main.py

import lookup

--something something--

for f in files:
    print(lookup.map_file(f))

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?


问:
Lua - why is string after function call allowed?
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

```<code>function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'
</code>```

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.

答:
I'm writing answer to my own question just in case anyone else stumbles upon the similar problem in the future and also looks for solution.

Manual

Lua manual (in its section 3.4.10 – Function Calls) basically states, that there are three different ways of providing arguments to Lua function.

Arguments have the following syntax:```<code>  args ::= ‘(’ [explist] ‘)’
  args ::= tableconstructor
  args ::= LiteralString</code>```
  All argument expressions are evaluated before the call. A call of the form f{fields} is syntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string.

Explanation

As lhf pointed out in his answer, both myfunc()"!" and myfunc(){1,2,3} are valid Lua expressions. It means the Lua compiler is doing nothing wrong, considering it doesn't know the function return value at a compile time.

The original example code given in the question:
    ```<code>print("Hello " .. myfunc() "!")</code>```
Could be then rewritten as:
    ```<code>print("Hello " .. (myfunc()) ("!"))</code>```
Which (when executed) translates to:
    ```<code>print("Hello " .. ("everyone") ("!"))</code>```
And thus resulting in the runtime error message attempt to call a string value (which could be rewritten as: the string everyone is not a function, so you can't call it).

Solution

As far as I understand, these two alternative ways of supplying arguments have no real benefit over the standard func(arg) syntax. That's why I ended up modyfing the Lua parser files. The disadventage of keeping this alternative syntax was too big. Here is what I've done (relevant for v5.3.4):

In file lparser.c i searched for function:

```<code>static void suffixedexp (LexState *ls, expdesc *v)</code>```

Inside this function i changed the case statement:
```<code>case '(': case TK_STRING: case '{':</code>```to ```<code>case '(':</code>```

Warning! By doing this I have modified the Lua language, so as lhf stated in his comment, it can no longer be called pure Lua. If you are unsure whether it is exactly what you want, I can't recommend this approach.

With this slight modification compiler detects the two above mentioned alternative syntaxes as errors. Of course, I can no longer use them inside Lua scripts, but for my specific application it's just fine.

All I need to do is to note this change somewhere to find it in case of upgrading Lua to higher version.

Body:
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.

Body:
I'm writing answer to my own question just in case anyone else stumbles upon the similar problem in the future and also looks for solution.

Manual

Lua manual (in its section 3.4.10 – Function Calls) basically states, that there are three different ways of providing arguments to Lua function.

Arguments have the following syntax:
  args ::= ‘(’ [explist] ‘)’
  args ::= tableconstructor
  args ::= LiteralString

  All argument expressions are evaluated before the call. A call of the form f{fields} is syntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string.

Explanation

As lhf pointed out in his answer, both myfunc()"!" and myfunc(){1,2,3} are valid Lua expressions. It means the Lua compiler is doing nothing wrong, considering it doesn't know the function return value at a compile time.

The original example code given in the question:

print("Hello " .. myfunc() "!")

Could be then rewritten as:

print("Hello " .. (myfunc()) ("!"))

Which (when executed) translates to:

print("Hello " .. ("everyone") ("!"))

And thus resulting in the runtime error message attempt to call a string value (which could be rewritten as: the string everyone is not a function, so you can't call it).

Solution

As far as I understand, these two alternative ways of supplying arguments have no real benefit over the standard func(arg) syntax. That's why I ended up modyfing the Lua parser files. The disadventage of keeping this alternative syntax was too big. Here is what I've done (relevant for v5.3.4):

In file lparser.c i searched for function:

static void suffixedexp (LexState *ls, expdesc *v)

Inside this function i changed the case statement:

case '(': case TK_STRING: case '{':
to
case '(':

Warning! By doing this I have modified the Lua language, so as lhf stated in his comment, it can no longer be called pure Lua. If you are unsure whether it is exactly what you want, I can't recommend this approach.

With this slight modification compiler detects the two above mentioned alternative syntaxes as errors. Of course, I can no longer use them inside Lua scripts, but for my specific application it's just fine.

All I need to do is to note this change somewhere to find it in case of upgrading Lua to higher version.


答:
There might be a more clever solution, but I'd just separate each column into its own data frame, add a value column, and then rbind() into a single dates data frame.

```<code>df1 <- df$date1
df1$value <- 1

df2 <- df$date2
df2$value <- 2

dates <- rbind(df1,df2)
</code>```

Body:
There might be a more clever solution, but I'd just separate each column into its own data frame, add a value column, and then rbind() into a single dates data frame.

df1 <- df$date1
df1$value <- 1

df2 <- df$date2
df2$value <- 2

dates <- rbind(df1,df2)


问:
How do I pass an image view and its properties from one view controller to another?
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

```<code>class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}
</code>```

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

答:
You can save the image as a png in the user document folder and reload it as needed. See my recent answer to an unrelated question:

Saving an image to User Documents folder

Body:
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).


问:
Which is the better way to insert HTML tags into PHP code?
I see two methods but I don't know which is better, should I insert a div tag like this :

```<code>echo "<div>";
</code>```

or like this ?

```<code>?> <div> <?php
</code>```

答: The text editor i am using has the color formatting, when you are echoing things, it only all comes out the same color, so if you are outside of PHP you get the benefit of the color co-ordination.</p>

Body:
I see two methods but I don't know which is better, should I insert a div tag like this :

echo "
";

or like this ?

?>
 <?php


问:
Can I safely block Dalvik browser agent requests?
I've noticed that when users on Android-OS devices visit my site, there's constantly two requests happening on each page. The first is the normal browser, and the second is from "Dalvik". Example:

"GET / HTTP/1.1" 200 2126 "-" "Mozilla/5.0 (Linux; Android 5.0.2; SAMSUNG SM-G925F/G925FXXU1AOD8 Build/LRX22G) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/3.0 Chrome/38.0.2125.102 Mobile Safari/537.36" 1229 2802

"GET / HTTP/1.1" 200 2117 "-" "Dalvik/2.1.0 (Linux; U; Android 5.0.2; SM-G925F Build/LRX22G)" 546 8729

From my understanding of this, the first request is from the actual browser, and the other is from the virtual machine (Dalvik) running the browser. The problem is that the Dalvik request doesn't use the same cookies, and/or POST data, and this triggers errors server side. An example would be when a user registers an account. The normal browser sends through POST data, but the Dalvik request just does a GET on the action url. Similarly, if a user is logged in, Dalvik will try a GET on a permission based page, which may redirect it somewhere else because there's no session for it.

The user doesn't experience any real problems (from what I can tell), however, we notice the attempts in our error logging. So my question is: Can I safely block all access attempts if the browser agent indicates "Dalvik/..*"? Will there be any adverse affects for the user? Considering that the Dalvik-related requests aren't actually reposting the real data or carrying a session, it seems unlikely. But hoping someone with more experience with Android can provide some feedback on it, for example, should I issue a specific HTTP header/status code, like "401 Unauthorized" or "400 Bad Request"?

Any help would be appreciated.

答: This is the Linux shell for Samsung phones. My OS is listed as "Linux 3.4.0-7500527 (Dalvik 2.1.0)" and it's a Samsung Galaxy S5. Could you set up a duplicate of your site (even minimal) with the gets receiving a 501, perhaps? With that, it should be easy to find out.</p>


问:
Can I use constructor logic with object initializer syntax?
i.e.

```<code>MyClass myClass = new MyClass() { Value = 5 };
</code>```

I have a bunch of constructor calls like the one above, but now I've realized I need to add logic to the constructor, which was a massive oversight. Currently I have no constructor, so just a blank implicit default constructor.

The below code should explain my problem.

Edit: I'm not actually doing validation, that's just a simple example of constructor logic

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new Test(1) + " should be true");
        Console.WriteLine(new Test(0) + " should be false");
        Test test = new Test(0) { Value = 1 }; // It allows this syntax, oddly, but the value that's used is the one passed as a parameter
        Console.WriteLine("I wish " + test + " was true");
        // This is what I have currently, but I'd like to add logic like that which exists in the parameterized constructor
        //Test test = new Test() { Value = 1 } // Would ideally function just like Test(1), otherwise I have to go and change every call

        // OUTPUT
        // True should be true
        // False should be false
        // I wish False was true

        Console.ReadLine();
    }
}

class Test
{
    public bool? IsGood { get; }
    public int Value { get; set; }

    // This doesn't currently exist in my class, but I'd like to add it
    public Test(int value)
    {
        if (value == 1)
            IsGood = true;
        else
            IsGood = false;
    }

    public override string ToString()
    {
        return IsGood.ToString();
    }
}
</code>```

答:
Can I set members outside of a constructor while still using logic in the constructor?

Meaning, what, exactly?

Using the object initializer syntax, a constructor still runs. You may even choose which one to use, through the normal constructor overload syntax (which you seem to show, but you say it's not in your class?). The code in your constructor looks at the parameter value that is passed to it, not the property Value (which it doesn't even set). But if you meant for the two to work together, then sure…you can set the property in the constructor and set IsGood in the Value property setter.

If you're going to do it that way, then I would not bother with the logic in the constructor at all. Just set the Value property and let its setter do the rest of the work:

```<code>class Test
{
    public bool? IsGood { get; private set; }

    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            IsGood = _value == 1;
        }
    }

    public Test(int value)
    {
        Value = value;
    }
}
</code>```

I should point out that the semantics of the above is slightly different from what you seem to have started with. That is, the Value property is not read-only, and so can be set at any time. So, similarly, the IsGood property can change at any time. You previously had declared it as read-only and it was settable only in the constructor.

It's not clear from your question whether that's a problem or not. If you want IsGood to be strictly read-only (i.e. without even a private setter), then it won't be possible to do literally what you're asking for, because in the object initializer syntax, it relies on setting member properties after the constructor has already returned.

For the moment, I'll assume it's not a problem to add the private setter to the IsGood property.

Note that since IsGood apparently depends solely on the value of Value, you could even implement the above like this:

```<code>class Test
{
    public bool? IsGood => _value != null ? _value == 1 : (bool?)null;

    private int? _value;
    public int Value
    {
        get { return _value ?? 0; }
        set { _value = value; }
    }

    public Test(int value)
    {
        Value = value;
    }
}
</code>```

That is, don't even bother storing a value for IsGood. Just return the appropriate value based on the current state of the Value property (null if it's never been set, true if it's currently set to 1, and false otherwise).

Body:
i.e.

MyClass myClass = new MyClass() { Value = 5 };

I have a bunch of constructor calls like the one above, but now I've realized I need to add logic to the constructor, which was a massive oversight. Currently I have no constructor, so just a blank implicit default constructor.

The below code should explain my problem.

Edit: I'm not actually doing validation, that's just a simple example of constructor logic

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new Test(1) + " should be true");
        Console.WriteLine(new Test(0) + " should be false");
        Test test = new Test(0) { Value = 1 }; // It allows this syntax, oddly, but the value that's used is the one passed as a parameter
        Console.WriteLine("I wish " + test + " was true");
        // This is what I have currently, but I'd like to add logic like that which exists in the parameterized constructor
        //Test test = new Test() { Value = 1 } // Would ideally function just like Test(1), otherwise I have to go and change every call

        // OUTPUT
        // True should be true
        // False should be false
        // I wish False was true

        Console.ReadLine();
    }
}

class Test
{
    public bool? IsGood { get; }
    public int Value { get; set; }

    // This doesn't currently exist in my class, but I'd like to add it
    public Test(int value)
    {
        if (value == 1)
            IsGood = true;
        else
            IsGood = false;
    }

    public override string ToString()
    {
        return IsGood.ToString();
    }
}

Body:
Can I set members outside of a constructor while still using logic in the constructor?

Meaning, what, exactly?

Using the object initializer syntax, a constructor still runs. You may even choose which one to use, through the normal constructor overload syntax (which you seem to show, but you say it's not in your class?). The code in your constructor looks at the parameter value that is passed to it, not the property Value (which it doesn't even set). But if you meant for the two to work together, then sure…you can set the property in the constructor and set IsGood in the Value property setter.

If you're going to do it that way, then I would not bother with the logic in the constructor at all. Just set the Value property and let its setter do the rest of the work:

class Test
{
    public bool? IsGood { get; private set; }

    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            IsGood = _value == 1;
        }
    }

    public Test(int value)
    {
        Value = value;
    }
}

I should point out that the semantics of the above is slightly different from what you seem to have started with. That is, the Value property is not read-only, and so can be set at any time. So, similarly, the IsGood property can change at any time. You previously had declared it as read-only and it was settable only in the constructor.

It's not clear from your question whether that's a problem or not. If you want IsGood to be strictly read-only (i.e. without even a private setter), then it won't be possible to do literally what you're asking for, because in the object initializer syntax, it relies on setting member properties after the constructor has already returned.

For the moment, I'll assume it's not a problem to add the private setter to the IsGood property.

Note that since IsGood apparently depends solely on the value of Value, you could even implement the above like this:

class Test
{
    public bool? IsGood => _value != null ? _value == 1 : (bool?)null;

    private int? _value;
    public int Value
    {
        get { return _value ?? 0; }
        set { _value = value; }
    }

    public Test(int value)
    {
        Value = value;
    }
}

That is, don't even bother storing a value for IsGood. Just return the appropriate value based on the current state of the Value property (null if it's never been set, true if it's currently set to 1, and false otherwise).