问:
Python Script run from C# leaves Python exe running in background eating memory
I am developing a C# ASP.Net Service that constantly reads GPIO on raspberry pis. This reads pins for inputs and also fires pins for outputs. I have the call working but my problem is I call the Python scripts every .5 seconds when needed. e.g the read input will be called every .5 second but the outputs will only fire when required. My problem is that each call starts a new instance of Python.exe and it does not close them when the script is run. I have tried all kinds of exits from the python script as well as some from the C# eg. process.Kill() but nothing is killing the Python exe. Attached is an image of the task manager to show the issue. Below I will add in the code I am using to call the python script and the read input script to show the python script I am calling. I have left some comments in so you can see what I have previously tried. Thanks

Code to call Python Script:

```<code>String exePath = SystemSettingDB.GetSettingValue("Python Executbale Path");
string holdPath = SystemSettingDB.GetSettingValue("Door Open Script Path");

var open = new ProcessStartInfo();

open.FileName = exePath;

var controllerIP = _controllerIP;

open.Arguments = $"\"{holdPath}\" \"{controllerIP}\" \"{_pin}\"";

open.UseShellExecute = false;
open.CreateNoWindow = true;
open.RedirectStandardOutput = true;
open.RedirectStandardError = true;

var process = Process.Start(open);

if (process != null)
{
     process.Kill();
     return true;
}
</code>```

Python Script to read Inputs

```<code>import sys

import os
from time import sleep

os.environ["PIGPIO_PORT"] = "8888"
os.environ["GPIOZERO_PIN_FACTORY"] = "pigpio"
from gpiozero import LED

os.environ["PIGPIO_ADDR"] = sys.argv[1]
gpio_pin = sys.argv[2]

door = LED(gpio_pin)

door._read()
print(door.value)

sys.exit(0)
#os._exit(-1)
</code>```

答:
Try this:
1. Download PSTools from: https://learn.microsoft.com/en-us/sysinternals/downloads/pskill
2. Write the following code:

```<code>>       public static void killPython()
    {
        var killPython = new ProcessStartInfo();
        killPython.FileName = @"\Your_PSTools_Path\pskill.exe";
        //-t Kill the process and its descendants.
        killPython.Arguments = "-t PID"; //process PID from Task Manager
        Process.Start(killPython);
    }
</code>```

Run your code as administrator

Body:
I am developing a C# ASP.Net Service that constantly reads GPIO on raspberry pis. This reads pins for inputs and also fires pins for outputs. I have the call working but my problem is I call the Python scripts every .5 seconds when needed. e.g the read input will be called every .5 second but the outputs will only fire when required. My problem is that each call starts a new instance of Python.exe and it does not close them when the script is run. I have tried all kinds of exits from the python script as well as some from the C# eg. process.Kill() but nothing is killing the Python exe. Attached is an image of the task manager to show the issue. Below I will add in the code I am using to call the python script and the read input script to show the python script I am calling. I have left some comments in so you can see what I have previously tried. Thanks

Code to call Python Script:

String exePath = SystemSettingDB.GetSettingValue("Python Executbale Path");
string holdPath = SystemSettingDB.GetSettingValue("Door Open Script Path");

var open = new ProcessStartInfo();

open.FileName = exePath;

var controllerIP = _controllerIP;

open.Arguments = $"\"{holdPath}\" \"{controllerIP}\" \"{_pin}\"";

open.UseShellExecute = false;
open.CreateNoWindow = true;
open.RedirectStandardOutput = true;
open.RedirectStandardError = true;

var process = Process.Start(open);

if (process != null)
{
     process.Kill();
     return true;
}

Python Script to read Inputs

import sys

import os
from time import sleep

os.environ["PIGPIO_PORT"] = "8888"
os.environ["GPIOZERO_PIN_FACTORY"] = "pigpio"
from gpiozero import LED

os.environ["PIGPIO_ADDR"] = sys.argv[1]
gpio_pin = sys.argv[2]

door = LED(gpio_pin)

door._read()
print(door.value)

sys.exit(0)
#os._exit(-1)

Body:
Try this:
1. Download PSTools from: https://learn.microsoft.com/en-us/sysinternals/downloads/pskill
2. Write the following code:

>       public static void killPython()
    {
        var killPython = new ProcessStartInfo();
        killPython.FileName = @"\Your_PSTools_Path\pskill.exe";
        //-t Kill the process and its descendants.
        killPython.Arguments = "-t PID"; //process PID from Task Manager
        Process.Start(killPython);
    }

Run your code as administrator


来源: stackexchange

问:
Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error
I want to create a docker image. This is my work directory:
Dockerfile.in   test.json   test.py

And this is my Dockerfile:

```<code>COPY ./test.json /home/test.json
COPY ./test.py /home/test.py

RUN python test.py
</code>```

When i launch this command:
docker build -f Dockerfile.in -t 637268723/test:1.0 .

It gives me this error:

```<code>`Step 1/5 : COPY ./test.json /home/test.json
 ---> Using cache
 ---> 6774cd225d60
 Step 2/5 : COPY ./test.py /home/test.py
 COPY failed: stat /var/lib/docker/tmp/docker-builder428014112/test.py:
 no such file or directory`
</code>```

Can anyone help me?

答:
I had the same issue with a .tgz file .

It was just about the location of the  file. Ensure the  file is in the same directory of the Dockerfile.

Also ensure the .dockerignore file directory doesn't exclude the  file regex pattern.

ContentLicense: CC BY-SA 3.0

Body:
I want to create a docker image. This is my work directory:
Dockerfile.in   test.json   test.py

And this is my Dockerfile:

COPY ./test.json /home/test.json
COPY ./test.py /home/test.py

RUN python test.py

When i launch this command:
docker build -f Dockerfile.in -t 637268723/test:1.0 .

It gives me this error:

`Step 1/5 : COPY ./test.json /home/test.json
 ---> Using cache
 ---> 6774cd225d60
 Step 2/5 : COPY ./test.py /home/test.py
 COPY failed: stat /var/lib/docker/tmp/docker-builder428014112/test.py:
 no such file or directory`

Can anyone help me?

ContentLicense: CC BY-SA 4.0


问:
Query on Django list view
I have Django list view but I want to put search based on two columns. how to implement this. User would be able to search records based on two columns in same view.</p>

答:
I think you can do it by | and using Q like below:

```<code>from django.db.models import Q

YourModel.objects.filter(Q(column_1__icontains=searched_keyword) | Q(
                column_2__icontains=searched_keyword))
</code>```

I think this can help.

Title: Query on Django list view

Body:
I think you can do it by | and using Q like below:

from django.db.models import Q

YourModel.objects.filter(Q(column_1__icontains=searched_keyword) | Q(
                column_2__icontains=searched_keyword))

I think this can help.


问:
What is Google expecting from a /token enpoint?
I'm developing a Google Actions Application and a Webhook to make this app comunicate with a server with client credentials. When implementing the OAuth & Google Sign-in flows with my server I can't seem to find what is the response the Google side is waiting from /token endpoint, it is supposed to return the access token that then will be used in every request made from the action (..if I got that part correctly..). I currently returning a ContentResult with the appropriate StatusCode (i think) and a json body with the access token it is supposed to return. Something like this:

```<code>ContentResult result = null;
data.Add(@"token_type", @"Bearer");
data.Add(@"access_token", FAKE_ACCESS_TOKEN);
data.Add(@"refresh_token", FAKE_REFRESH_TOKEN);
data.Add(@"expires_in", FAKE_SECONDS_TO_EXPIRATION);

jsonResponse = data.ToString();

result = new ContentResult
{
     Content = jsonResponse,
     ContentType = "application/json"
     StatusCode = (int?)HttpStatusCode.OK
};

return result;
</code>```

The Documentation on this part seems to be vague. Maybe Someone could help me figure it out ? Thanks in advance

答: [Solved] Thank you for your answers. I got the problem solved by changing the return type of my Post Method to "JsonResult" instead of "ContentResult". </p>

Body:
I'm developing a Google Actions Application and a Webhook to make this app comunicate with a server with client credentials. When implementing the OAuth & Google Sign-in flows with my server I can't seem to find what is the response the Google side is waiting from /token endpoint, it is supposed to return the access token that then will be used in every request made from the action (..if I got that part correctly..). I currently returning a ContentResult with the appropriate StatusCode (i think) and a json body with the access token it is supposed to return. Something like this:

ContentResult result = null;
data.Add(@"token_type", @"Bearer");
data.Add(@"access_token", FAKE_ACCESS_TOKEN);
data.Add(@"refresh_token", FAKE_REFRESH_TOKEN);
data.Add(@"expires_in", FAKE_SECONDS_TO_EXPIRATION);

jsonResponse = data.ToString();

result = new ContentResult
{
     Content = jsonResponse,
     ContentType = "application/json"
     StatusCode = (int?)HttpStatusCode.OK
};

return result;

The Documentation on this part seems to be vague. Maybe Someone could help me figure it out ? Thanks in advance


问:
Read "file.txt" content to List<String> dart
I need to get the text inside a ".txt" file, assign it to a variable and split it on "," in a list of String.

All works fine, the problem in that what is stored in the variable is "Instance of FutureString>".

So I added .then((value) =>value); in _MyRead to wait until the reading action is completed but the result is the same.

All works, I just need to get the text from the file.
Actually a few minutes ago, the result of reading action was null, maybe this can help.

Code :

```<code>Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

Future<File>  _localFile(String name) async {
final path = await _localPath;
print(path);
return File('$path/$name');
}

Future<String> _read(String filename) async {
try {
  final file = await _localFile(filename);

  // Read the file.
  return await file.readAsString();
} catch (e) {
  // If encountering an error, return 0.
  return "Can't read";
 }
}

String _MyRead(String filename){
 var read_ = _read(filename).then((value) =>value);
 String ridd= read_.toString();
 return ridd;
}

List<String> _getLanguages() {
  var _lan= _read("languages.txt");
  if ( _lan==null ) print("languages is empty");
  List<String> list =_lan.toString().split(",");
  return list;
}
</code>```

答:
You can try this :

```<code>Future<String>_MyRead(String filename) async {
 var read_ = await _read(filename);
 String ridd= read_.toString();
 return ridd;
}
</code>```

and you need to await when you call the read function since it returns a Future:

```<code>var _lan= await _read("languages.txt");
</code>```

(Don't forget to make your function asynchronous then)

Body:
I need to get the text inside a ".txt" file, assign it to a variable and split it on "," in a list of String.

All works fine, the problem in that what is stored in the variable is "Instance of FutureString>".

So I added .then((value) =>value); in _MyRead to wait until the reading action is completed but the result is the same.

All works, I just need to get the text from the file.
Actually a few minutes ago, the result of reading action was null, maybe this can help.

Code :

Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

Future<File>  _localFile(String name) async {
final path = await _localPath;
print(path);
return File('$path/$name');
}

Future<String> _read(String filename) async {
try {
  final file = await _localFile(filename);

  // Read the file.
  return await file.readAsString();
} catch (e) {
  // If encountering an error, return 0.
  return "Can't read";
 }
}

String _MyRead(String filename){
 var read_ = _read(filename).then((value) =>value);
 String ridd= read_.toString();
 return ridd;
}

List<String> _getLanguages() {
  var _lan= _read("languages.txt");
  if ( _lan==null ) print("languages is empty");
  List<String> list =_lan.toString().split(",");
  return list;
}

Body:
You can try this :

Future<String>_MyRead(String filename) async {
 var read_ = await _read(filename);
 String ridd= read_.toString();
 return ridd;
}

and you need to await when you call the read function since it returns a Future:

var _lan= await _read("languages.txt");

(Don't forget to make your function asynchronous then)


问:
Search a value in a main-entity's child property of type List<T> in another List<T> and return main entity
I'm running into a LINQ2Sql problem where Visual Studio suggest a potential fix but that doesn't work.
Imagine following:

I need to return an entity of type IEnumerable
QmmProductionOrderInteruptCardCollection contains a List this again contains a List every Note has a property "Reviewed" of type boolean.

I now want to look for this property in each note where Reviewed is false but return the top entity
IEnumerable

Now this is my LINQ-Statement which would return IEnumerable without casting instead:

```<code>return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();
</code>```

Visual studio suggests a casting into type IEnumerable like so:

```<code>return (IEnumerable<QmmProductionOrderInteruptCardCollection>)await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();
</code>```

But when test I get an InvalidCastException

Unable to cast object of type 'System.Collections.Generic.List1[BIP_Models.Domain.Qmm.QmmNote]' to type 'System.Collections.Generic.IEnumerable1[BIP_Models.Domain.Qmm.QmmProductionOrderInteruptCardCollection]'.

Do you have any thoughts how to solve this?

For a better understanding, this would be the sql statement I'd like to transfer:

```<code>SELECT
*
FROM QmmProductionOrderInteruptCardCollections pic
JOIN QmmProductionOrders p ON p.Id = pic.ProductionOrderId
JOIN QmmNotes n ON n.ProductionOrderId = p.Id
WHERE
n.IsReviewed = 0;
</code>```

Thanks and best regards.
Patrick

答:
You shouldn't be using Select here, it performs a projection on an IEnumerable, and here you are returning a new type each time.

Instead just use Where like this:

```<code>return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
        .Where(x => x.ProductionOrder.Notes.Any(y => !y.IsReviewed))
        .ToListAsync();
</code>```

Body:
I'm running into a LINQ2Sql problem where Visual Studio suggest a potential fix but that doesn't work.
Imagine following:

I need to return an entity of type IEnumerable
QmmProductionOrderInteruptCardCollection contains a List this again contains a List every Note has a property "Reviewed" of type boolean.

I now want to look for this property in each note where Reviewed is false but return the top entity
IEnumerable

Now this is my LINQ-Statement which would return IEnumerable without casting instead:

return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();

Visual studio suggests a casting into type IEnumerable like so:

return (IEnumerable<QmmProductionOrderInteruptCardCollection>)await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
            .Select(x => x.ProductionOrder)
            .SelectMany(x => x.Notes)
            .Where(n => !n.IsReviewed)
            .ToListAsync();

But when test I get an InvalidCastException

Unable to cast object of type 'System.Collections.Generic.List1[BIP_Models.Domain.Qmm.QmmNote]' to type 'System.Collections.Generic.IEnumerable1[BIP_Models.Domain.Qmm.QmmProductionOrderInteruptCardCollection]'.

Do you have any thoughts how to solve this?

For a better understanding, this would be the sql statement I'd like to transfer:

SELECT
*
FROM QmmProductionOrderInteruptCardCollections pic
JOIN QmmProductionOrders p ON p.Id = pic.ProductionOrderId
JOIN QmmNotes n ON n.ProductionOrderId = p.Id
WHERE
n.IsReviewed = 0;

Thanks and best regards.
Patrick

Body:
You shouldn't be using Select here, it performs a projection on an IEnumerable, and here you are returning a new type each time.

Instead just use Where like this:

return await ApplicationDbContext.Qmm_ProductionOrderInteruptCardCollections
        .Where(x => x.ProductionOrder.Notes.Any(y => !y.IsReviewed))
        .ToListAsync();


问:
Attempted to load class "Mpdf" from namespace "Mpdf"
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

```<code>use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

</code>```

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

答:
I've already got a similar issue with Mpdf.

PHPSpreadsheet supports multiple Librairies to generate PDF.

I'm nut using Mpdf but Tcpdf.
I'm also not sure but you need to install them manually.

composer require tecnickcom/tcpdf

Then in your code :

```<code>$writer = new Tcpdf($spreadsheet);
</code>```

And don't forget the use statement ;)

Hope this help !

Body:
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

Body:
I've already got a similar issue with Mpdf.

PHPSpreadsheet supports multiple Librairies to generate PDF.

I'm nut using Mpdf but Tcpdf.
I'm also not sure but you need to install them manually.

composer require tecnickcom/tcpdf

Then in your code :

$writer = new Tcpdf($spreadsheet);

And don't forget the use statement ;)

Hope this help !


问:
How to add login credential via python script?
I am sure this is an answered question somewhere, but I could not find a solution for me (if you know a duplicate feel free to mark it).

My goal is to query a RESTful API. To do that I need to authenticate. The only way available for me for this API is via web-browser.

Basically, I am loading URL which redirects to another URL. In the second URL, there is a form where I need to input username and password to authenticate. Currently, I input the credentials manually via a web browser.

My question is: Can I do this programmatically such that I don't have to manually input the credentials via a web browser?

Note: the webpage is not verified.

Attempt 1

I tried the following commands, but none worked:

```<code>curl -k -u username:password https://myurl:port
</code>```

It did not return anything.

Attempt 2

```<code>BASE_URL = 'https://myurl:port'
username = 'username'
password = 'password'
r = requests.get(BASE_URL, auth=(username, password), verify=False)
print(r.status_code, r.reason)
</code>```

it prints <Response [200]> but it does not authenticate. This is because when I try to query an API endpoint - it says I am unauthorized. When I input the credentials manually in the browser - then the endpoint query works.

Attempt 3

Finally, I thought (but did not do) I need some way to read the login page and input credentials by getting the html elements and then clicking log in (with selenium for example), but this seems too rough and error-prone. Maybe there is a more elegant way.

Any ideas of how I can do this?

答:
Basically, I am loading URL which redirects to another URL. In the
  second URL, there is a form where I need to input username and
  password to authenticate

From your description it sounds like you are accessing an API using OAuth2 with the authorization code grant flow ?...which by design requires the user (=resource owner) to authorise (via the form) your app (=client) to access his/her data provided by the API (=resource server). in this case, using basic auth (Attempt 1 and 2) will not help you as the API expects a token, not username/password. you'd probably need a refresh token that does not expire and would allow your client to request a fresh access token each time it wants to access the API...

It all depends on the authentication mechanism used by your API...I'd first figure out if your API is indeed using OAuth2, and if so, learn about authentication flows (e.g. https://www.udemy.com/course/learn-oauth-2/) ...client credentials flow is probably what you'd want if the API allows for it...

update: Attempt 3 might be worth a try, i've never done it though. you might be able to send the credentials by submitting the corresponding form data via python requests...then that should in theory provide you with an authorization code which you can use to get a token...

Body:
I am sure this is an answered question somewhere, but I could not find a solution for me (if you know a duplicate feel free to mark it).

My goal is to query a RESTful API. To do that I need to authenticate. The only way available for me for this API is via web-browser.

Basically, I am loading URL which redirects to another URL. In the second URL, there is a form where I need to input username and password to authenticate. Currently, I input the credentials manually via a web browser.

My question is: Can I do this programmatically such that I don't have to manually input the credentials via a web browser?

Note: the webpage is not verified.

Attempt 1

I tried the following commands, but none worked:

curl -k -u username:password https://myurl:port

It did not return anything.

Attempt 2

BASE_URL = 'https://myurl:port'
username = 'username'
password = 'password'
r = requests.get(BASE_URL, auth=(username, password), verify=False)
print(r.status_code, r.reason)

it prints <Response [200]> but it does not authenticate. This is because when I try to query an API endpoint - it says I am unauthorized. When I input the credentials manually in the browser - then the endpoint query works.

Attempt 3

Finally, I thought (but did not do) I need some way to read the login page and input credentials by getting the html elements and then clicking log in (with selenium for example), but this seems too rough and error-prone. Maybe there is a more elegant way.

Any ideas of how I can do this?


问:
If async-await doesn't create any additional threads, then how does it make applications responsive?
Time and time again, I see it said that using async-await doesn't create any additional threads. That doesn't make sense because the only ways that a computer can appear to be doing more than 1 thing at a time is

Actually doing more than 1 thing at a time (executing in parallel, making use of multiple processors)

Simulating it by scheduling tasks and switching between them (do a little bit of A, a little bit of B, a little bit of A, etc.)

So if async-await does neither of those, then how can it make an application responsive? If there is only 1 thread, then calling any method means waiting for the method to complete before doing anything else, and the methods inside that method have to wait for the result before proceeding, and so forth.

答:
This does not directly answer the question, but I think it provides some interesting additional information:

Async and await does not create new threads by itself. BUT depending on where you use async-await, the synchronous part BEFORE the await may run on a different thread than the synchronous part AFTER the await (for example ASP.NET and ASP.NET core behave differently).

In UI-Thread based applications (WinForms, WPF) you will be on the same thread before and after. But when you use async-await on a Thread pool thread, the thread before and after the await may not be the same.

A great video on this topic


问:
Not able to set a Measure to Text Box in power bi?
My Measure is :

```<code>Last7days =
CALCULATE(
        DISTINCTCOUNT('application_overview'[posting_number]),
        FILTER(ALL('application_overview'), 'application_overview'[app_submitted_date] >= TODAY()-700)
)
</code>```

I am getting the result if I set it to a card, And also able to set some other Measures to the title of a Text box. What is the issue with this Measure, like for what reason I am not able to set it to a Text box?

答:
Concatenate a string to the result, Then you will be able to set it to the Text box.
e.g:</p>

```<code>Last7daysPostings =
var res = CALCULATE(
        DISTINCTCOUNT('application_overview'[posting_id]),
        FILTER(ALL('application_overview'), 'application_overview'[app_submitted_date] >= TODAY()-7)
        )
return res&""
</code>```

Body:
My Measure is :

Last7days =
CALCULATE(
        DISTINCTCOUNT('application_overview'[posting_number]),
        FILTER(ALL('application_overview'), 'application_overview'[app_submitted_date] >= TODAY()-700)
)

I am getting the result if I set it to a card, And also able to set some other Measures to the title of a Text box. What is the issue with this Measure, like for what reason I am not able to set it to a Text box?

Body:
Concatenate a string to the result, Then you will be able to set it to the Text box.
e.g:

Last7daysPostings =
var res = CALCULATE(
        DISTINCTCOUNT('application_overview'[posting_id]),
        FILTER(ALL('application_overview'), 'application_overview'[app_submitted_date] >= TODAY()-7)
        )
return res&""


问:
How to identify touch on a specific imageView from multiple imageViews in a UIScrollView?
I have multiple ImageViews in a UIScrollView and I want to identify the specific imageView on which I touched. So that I could do some actions. (for example, showing Alert with the image name).

I have seen some similar posts, but they did not have proper answer. And some answers were complex to me as I am pretty new to iPhone programming.

It would be great, If anybody helps with a simple example. :-)

my code is like this

```<code>- (void)viewDidLoad {

imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;

    [imgScrollView addSubview:imageView];

    [imageView release];
}

[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}
</code>```

答:
I recommend you look through the documentation and examples for UIGestureRecognizer. There is also a more explanatory Event Handling Guide .

This will walk you through adding Gesture Recognizers to specific views (e.g. your imageView) that can handle swipes, taps and multitouch gestures however you like.

Body:
I have multiple ImageViews in a UIScrollView and I want to identify the specific imageView on which I touched. So that I could do some actions. (for example, showing Alert with the image name).

I have seen some similar posts, but they did not have proper answer. And some answers were complex to me as I am pretty new to iPhone programming.

It would be great, If anybody helps with a simple example. :-)

my code is like this

- (void)viewDidLoad {

imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;

    [imgScrollView addSubview:imageView];

    [imageView release];
}

[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}


问:
How can count words of a line and keep the id of the line with apache pig?
I have a file whith 2 columns, the first one with the id and the second on with a long text and I need to know how to count words for each id.
For example if I have these two rows:

```<code>id | line
(1,  This country is beautiful)
(2, I would love to have a cup of tea)

The answer I need is:
(1, 4)
(2, 9)
</code>```

I have read a lot of comments about this but everyone keeps the total numbers of each word or the total number of words without keeping the id of the line.

I would appreciate if someone could help me.

答:
Something like:

```<code>FOREACH row GENERATE
    id,
    COUNT(STRSPLITTOBAG(line, " "));
</code>```

This should take each row, produce the needed ID field, and then split the text based on a delimeter (here a " " value) to a bag type, where the COUNT function counts the number of items in the bag.

Body:
I have a file whith 2 columns, the first one with the id and the second on with a long text and I need to know how to count words for each id.
For example if I have these two rows:

id | line
(1,  This country is beautiful)
(2, I would love to have a cup of tea)

The answer I need is:
(1, 4)
(2, 9)

I have read a lot of comments about this but everyone keeps the total numbers of each word or the total number of words without keeping the id of the line.

I would appreciate if someone could help me.

Body:
Something like:

FOREACH row GENERATE
    id,
    COUNT(STRSPLITTOBAG(line, " "));

This should take each row, produce the needed ID field, and then split the text based on a delimeter (here a " " value) to a bag type, where the COUNT function counts the number of items in the bag.


问:
Using the ruby gem net-ssh-multi to execute a sudo command on multiple servers at once
In a previous question  I figured out how to start a password-authenticated ssh sessions on multiple servers to run a single command.  Now I need to be able to execute a "sudo" command.  The problem is, that net-ssh-multi does not allocate a pseudo terminal (pty), which sudo needs to run, resulting in the following error:

[127.0.0.1 : stderr] sudo: sorry, you must have a tty to run sudo

According to the documentation, a pseudo-terminal can be allocated with a method call to a channel object, however, the following code does not work:  it generates the "no tty" error above:

```<code>require 'net/ssh'
require 'net/ssh/multi'

Net::SSH::Multi.start do |session|

  # define the servers we want to use
  my_ticket.servers.each do |session_server|
    session.use session_server , :user =>  user_name ,  \
                              :password => user_pass
  end

 # execute commands on all servers
  session.exec 'sudo ls /root' do |channel, stream, data|
   if data =~ /^\[sudo\] password for user:/
     channel.request_pty # <- problem must be here.
     channel.send_data user_pass
   end

  end

 # run the aggregated event loop
 session.loop
end
</code>```

$ ruby --version

ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]

答:
This is what I wound up doing, thanks to @Christian and this wonderful Pastie:</p>

```<code>Net::SSH::Multi.start do |session|

# define the servers we want to use
my_ticket.servers.each do |session_server|
  session.use session_server , :user =>  my_ticket.user_name ,  \
  :password => my_ticket.user_pass
end

session.open_channel do |channel|
channel.request_pty do |c, success|
  raise "could not request pty" unless success
  channel.exec   "sudo YOUR_COMMAND"
  channel.on_data do |c_, data|
  if data = /\[sudo\]/
  channel.send_data(@password + "\n")
  end
   puts data

    end
   end
  end

# run the aggregated event loop
  session.loop
end
</code>```

Body:
In a previous question  I figured out how to start a password-authenticated ssh sessions on multiple servers to run a single command.  Now I need to be able to execute a "sudo" command.  The problem is, that net-ssh-multi does not allocate a pseudo terminal (pty), which sudo needs to run, resulting in the following error:

[127.0.0.1 : stderr] sudo: sorry, you must have a tty to run sudo

According to the documentation, a pseudo-terminal can be allocated with a method call to a channel object, however, the following code does not work:  it generates the "no tty" error above:

require 'net/ssh'
require 'net/ssh/multi'

Net::SSH::Multi.start do |session|

  # define the servers we want to use
  my_ticket.servers.each do |session_server|
    session.use session_server , :user =>  user_name ,  \
                              :password => user_pass
  end

 # execute commands on all servers
  session.exec 'sudo ls /root' do |channel, stream, data|
   if data =~ /^\[sudo\] password for user:/
     channel.request_pty # <- problem must be here.
     channel.send_data user_pass
   end

  end

 # run the aggregated event loop
 session.loop
end

$ ruby --version

ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]

Body:
This is what I wound up doing, thanks to @Christian and this wonderful Pastie:

Net::SSH::Multi.start do |session|

# define the servers we want to use
my_ticket.servers.each do |session_server|
  session.use session_server , :user =>  my_ticket.user_name ,  \
  :password => my_ticket.user_pass
end

session.open_channel do |channel|
channel.request_pty do |c, success|
  raise "could not request pty" unless success
  channel.exec   "sudo YOUR_COMMAND"
  channel.on_data do |c_, data|
  if data = /\[sudo\]/
  channel.send_data(@password + "\n")
  end
   puts data

    end
   end
  end

# run the aggregated event loop
  session.loop
end


问:
Tab bar background color did not get changed

I am new in React-Native development.
I am using TabNavigator from 'react-navigation' for tab bar in React-Native, everything is working fine excepts tab bar activeBackgroundColor and inactiveBackgroundColor did not get changed in android.
Its showing blue color only like the image given below.

Code i am using is:

import React, { Component } from 'react';
import { TabNavigator } from 'react-navigation';
import { PixelRatio } from 'react-native';

import { ColorScheme } from '../Resources/ColorScheme';
import {Fonts} from '../Resources/Fonts';

import TAB1 from '../Screens/TAB1'
import TAB2 from '../Screens/TAB2'
 /** */
 var FONT_SIZE = 8;
 if (PixelRatio.get() === 2) {
  FONT_SIZE=10
 }else if (PixelRatio.get() === 3) {
    FONT_SIZE=12
  }

export default FavoritesScreenTabNavigator=TabNavigator({
    TAB1:{screen:TAB1},
    TAB2:{screen:TAB2}
  },{
      tabBarPosition:'top',
      swipeEnabled:true,
      animationEnabled:true,
      tabBarOptions:{
          activeTintColor:ColorScheme.tabBarSelectedTintColor,
          inactiveTintColor:ColorScheme.tabBarUnSelectedTintColor,
          activeBackgroundColor:'white',
          inactiveBackgroundColor:'white',
          labelStyle:{
            fontSize: FONT_SIZE,
            fontFamily: Fonts.QuicksandBold,
            textAlign:'center'
          },
          indicatorStyle: {
            borderBottomColor:ColorScheme.tabBarSelectedTintColor,
            borderBottomWidth: 3,
          }
      },
  }
)
```

Any help will be appreciated.

Thanks in advance.

答:
I update Val's answer.

```<code> tabBarOptions:{
      //other properties
      pressColor: 'gray',//for click (ripple) effect color
      style: {
        backgroundColor: 'white',//color you want to change
      },
      indicatorStyle: {
        backgroundColor: 'your indicator background color',
        height: '100%',
        borderBottomColor: 'your indicator bottom bar color',
        borderBottomWidth: 1
      },
  }
</code>```

the hack is height value!

Body:
I am new in React-Native development.
I am using TabNavigator from 'react-navigation' for tab bar in React-Native, everything is working fine excepts tab bar activeBackgroundColor and inactiveBackgroundColor did not get changed in android.
Its showing blue color only like the image given below.

Code i am using is:

import React, { Component } from 'react';
import { TabNavigator } from 'react-navigation';
import { PixelRatio } from 'react-native';

import { ColorScheme } from '../Resources/ColorScheme';
import {Fonts} from '../Resources/Fonts';

import TAB1 from '../Screens/TAB1'
import TAB2 from '../Screens/TAB2'
 /** */
 var FONT_SIZE = 8;
 if (PixelRatio.get() === 2) {
  FONT_SIZE=10
 }else if (PixelRatio.get() === 3) {
    FONT_SIZE=12
  }

export default FavoritesScreenTabNavigator=TabNavigator({
    TAB1:{screen:TAB1},
    TAB2:{screen:TAB2}
  },{
      tabBarPosition:'top',
      swipeEnabled:true,
      animationEnabled:true,
      tabBarOptions:{
          activeTintColor:ColorScheme.tabBarSelectedTintColor,
          inactiveTintColor:ColorScheme.tabBarUnSelectedTintColor,
          activeBackgroundColor:'white',
          inactiveBackgroundColor:'white',
          labelStyle:{
            fontSize: FONT_SIZE,
            fontFamily: Fonts.QuicksandBold,
            textAlign:'center'
          },
          indicatorStyle: {
            borderBottomColor:ColorScheme.tabBarSelectedTintColor,
            borderBottomWidth: 3,
          }
      },
  }
)

Any help will be appreciated.

Thanks in advance.

Body:
I update Val's answer.

 tabBarOptions:{
      //other properties
      pressColor: 'gray',//for click (ripple) effect color
      style: {
        backgroundColor: 'white',//color you want to change
      },
      indicatorStyle: {
        backgroundColor: 'your indicator background color',
        height: '100%',
        borderBottomColor: 'your indicator bottom bar color',
        borderBottomWidth: 1
      },
  }

the hack is height value!


问:
Separating Firebase notification for UAT, SIT and Prod
In my application I am using Firebase Notification for push notification.

In my Android app I have three build configurations with three different bundle identifiers.

com.mycompany.myappQA

com.mycompany.myappDev

com.mycompany.myapp

Here my doubt is,

When I create Application in Firebase console do I need to create three different apps for all the three environments? Or Is it possible for me to create one app and handle all the three different app configurations / Apps.

答:
One namespace = one app. To add more namespaces, more apps needs to be added to the project.

If notifications are the main reason for your different namespaces (per environment) and if you're using topics, maybe it would be better to just suffix or prefix the topic name and have the same namespace for all environments and just adjust the subscribe/unsubscribe topic name accordingly.


问:
more complicated label in checkbox - Vuetify
Here's my simple code:

```<code><v-checkbox
  v-model="rodo"
  label="I agree to Privacy Policy (show more)"
  :rules="policyRules"
  required
></v-checkbox>
</code>```

I want to have simple code inside the label, just something to show more on click. What's the best way to approach that? I want to have something like that in label:

```<code>I agree to Privacy Policy
<span @click="showMore=!showMore">(show more)</span>
<span v-show="showMore">Lorem ipsum...</span>
</code>```

答:
You can use the label slot.

```<code><v-checkbox
  v-model="rodo"
  :rules="policyRules"
  required>
  <template v-slot:label>
   I agree to Privacy Policy
   <span @click="showMore=!showMore">(show more)</span>
   <span v-show="showMore">Lorem ipsum...</span>
  </template>
</v-checkbox>
</code>```

See also documentation for more information:
https://vuetifyjs.com/en/components/selection-controls/

Body:
Here's my simple code:

<v-checkbox
  v-model="rodo"
  label="I agree to Privacy Policy (show more)"
  :rules="policyRules"
  required
></v-checkbox>

I want to have simple code inside the label, just something to show more on click. What's the best way to approach that? I want to have something like that in label:

I agree to Privacy Policy
(show more)
Lorem ipsum...

Body:
You can use the label slot.

<v-checkbox
  v-model="rodo"
  :rules="policyRules"
  required>
  <template v-slot:label>
   I agree to Privacy Policy
   <span @click="showMore=!showMore">(show more)</span>
   <span v-show="showMore">Lorem ipsum...</span>
  </template>
</v-checkbox>

See also documentation for more information:
https://vuetifyjs.com/en/components/selection-controls/


问:
How do I set R console's language to English using a configuration file?
I am trying to set my R console's language to English using a configuration file. I am using Debian and Ubuntu as my OS. To set the R console's language to English, I created ~/.Renviron containing:

```<code>LANGUAGE = 'en_US.UTF-8'
LC_ALL = 'en_US.UTF-8'
</code>```

This works, but I only found it through trial and error, so I am concerned that this will break if I change my system's default languages and locales in the future. These are my current system's environment variables:

$ env | grep "LANG\|LC_"
LANG=fr_FR.UTF-8
LANGUAGE=fr_FR.UTF-8:zh_CN.UTF-8:en_US.UTF-8
LC_ADDRESS=en_SG.UTF-8
LC_IDENTIFICATION=en_SG.UTF-8
LC_MONETARY=en_SG.UTF-8
LC_MEASUREMENT=en_SG.UTF-8
LC_NAME=en_SG.UTF-8
LC_NUMERIC=en_SG.UTF-8
LC_PAPER=en_SG.UTF-8
LC_TELEPHONE=en_SG.UTF-8
LC_TIME=en_SG.UTF-8
```

I want to make sure that no matter what my future system's LANG, LANGUAGE, LC_* are going to be, the values in ~/.Renviron will ensure that the R console's language is English. How can I do that? Does my current ~/.Renviron achieve this goal?

In other words, is setting LANGUAGE and LC_ALL to en_US.UTF-8 in ~/.Renviron sufficient to guarantee that the R console's language is always English no matter what my system's default languages and locales become in the future?

I've read this: How to change language settings in R, but the answers there do not use a configuration file.

答:
Does my current ~/.Renviron achieve this goal?

Probably yes, but potentially not quite.

The relevant information can be found in the locales documentation:

The following categories should always be supported: "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MONETARY", "LC_NUMERIC" and "LC_TIME". Some systems (not Windows) will also support "LC_MESSAGES", "LC_PAPER" and "LC_MEASUREMENT". […]

Note that setting category "LC_ALL" sets only categories "LC_COLLATE", "LC_CTYPE", "LC_MONETARY" and "LC_TIME". […]

Note that the LANGUAGE environment variable has precedence over "LC_MESSAGES" in selecting the language for message translation on most R platforms.

So you might want to also set those categories not set by LC_ALL or LANGUAGE:

LC_NUMERIC

LC_PAPER

LC_MEASUREMENT

Lastly, the R “Startup” documentation tells us that using ~/.Renviron is a good place to set these:

Unless --no-environ was given on the command line, R searches for site and user files to process for setting environment variables. […] The name of the user file can be specified by the R_ENVIRON_USER environment variable; if this is unset, the files searched for are ‘.Renviron’ in the current or in the user's home directory (in that order).

Personally I prefer de-cluttering my home directory and putting all such configuration under ~/.config, e.g. ~/.config/R/REnviron. Doing so requires slightly more work, however, since R by default doesn’t respect the XDG conventions: to fix this I’m setting the environment variables R_ENVIRON_USER, R_LIBS_USER and R_PROFILE_USER in my .bashrc:

export R_ENVIRON_USER=$HOME/.config/R/Renviron

# Need to be set here rather than in REnviron so that they can be overridden
# temporarily:

export R_PROFILE_USER=${XDG_CONFIG_HOME-$HOME/.config}/R/init.r
export R_LIBS_USER=${XDG_DATA_HOME-$HOME/.local/share}/R/x86_64-pc-linux-gnu-library/%v
```

Body:
I am trying to set my R console's language to English using a configuration file. I am using Debian and Ubuntu as my OS. To set the R console's language to English, I created ~/.Renviron containing:

LANGUAGE = 'en_US.UTF-8'
LC_ALL = 'en_US.UTF-8'

This works, but I only found it through trial and error, so I am concerned that this will break if I change my system's default languages and locales in the future. These are my current system's environment variables:

$ env | grep "LANG\|LC_"
LANG=fr_FR.UTF-8
LANGUAGE=fr_FR.UTF-8:zh_CN.UTF-8:en_US.UTF-8
LC_ADDRESS=en_SG.UTF-8
LC_IDENTIFICATION=en_SG.UTF-8
LC_MONETARY=en_SG.UTF-8
LC_MEASUREMENT=en_SG.UTF-8
LC_NAME=en_SG.UTF-8
LC_NUMERIC=en_SG.UTF-8
LC_PAPER=en_SG.UTF-8
LC_TELEPHONE=en_SG.UTF-8
LC_TIME=en_SG.UTF-8

I want to make sure that no matter what my future system's LANG, LANGUAGE, LC_* are going to be, the values in ~/.Renviron will ensure that the R console's language is English. How can I do that? Does my current ~/.Renviron achieve this goal?

In other words, is setting LANGUAGE and LC_ALL to en_US.UTF-8 in ~/.Renviron sufficient to guarantee that the R console's language is always English no matter what my system's default languages and locales become in the future?

I've read this: How to change language settings in R, but the answers there do not use a configuration file.


问:
Random number within range with a seed
I've been trying to wrap my head around solving this issue but I can't seem to find a simple solution to it.

I have a dynamic grid layout, articles are placed on the grid but have different width & height. This width & height of these different articles can change upon visiting the site but only when there is a new article added.

The issue is I have logic that uses mt_rand to generate random numbers within a range (to fit in the layout grid), is there a way I can pass in a seed (planning to use the newest article id) so that the random numbers are consistent until a new article is introduced? I wanted to use mt_srand but there doesn't seem to be an easy way to limit the random number within a range.

Thanks.

答:
mt_srand() is used to set your seed and mt_rand() takes in a min and max if you want to set the range.  Basically something like:

```<code>mt_srand($seed);
mt_rand($min, $max);
</code>```

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

Title: Random number within range with a seed

Body:
mt_srand() is used to set your seed and mt_rand() takes in a min and max if you want to set the range.  Basically something like:

mt_srand($seed);
mt_rand($min, $max);

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.


问:
How to delete CRLFs on a specific line with a loop in Python
I have a file like this:

```<code>"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (CR LF)
Line3Column2 (CR LF)"|"Line3 Column3 (CR LF)
Line3 Column3"|"Line2"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)
</code>```

I want to delete the CRLF on line 3, 4 to have the line 5 on the line 4 and the line 4 on the line 3.

BUT i don't want to delete the CRLF on line 5 otherwise my line 3 and my line 4 will be on the same line...

Finally i want :

```<code>"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (̶C̶R̶L̶F̶) Line3Column2 (̶C̶R̶L̶F̶) "|"Line3 Column3 (̶C̶R̶L̶F̶) Line3 Column3"|"Line3"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)
</code>```

I tried to make a loop (when i have a line with a pipe number < header then i delete his CRLF and then i restart from the beginning) but it doesn't work...

答:
You could use csv module to read rows and do anything you want then write it back.</p>

```<code>import csv

with open('old_file.csv') as f:
    reader = csv.DictReader(f, delimiter='|')
    with open('new_file.csv', 'w') as wf:
        writer = csv.DictWriter(wf, reader.fieldnames, delimiter='|')
        for row in reader:
            writer.writerow({h: v.replace('\r\n', '') for h, v in row.items()})
</code>```

Body:
I have a file like this:

"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (CR LF)
Line3Column2 (CR LF)"|"Line3 Column3 (CR LF)
Line3 Column3"|"Line2"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)

I want to delete the CRLF on line 3, 4 to have the line 5 on the line 4 and the line 4 on the line 3.

BUT i don't want to delete the CRLF on line 5 otherwise my line 3 and my line 4 will be on the same line...

Finally i want :

"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (̶C̶R̶L̶F̶) Line3Column2 (̶C̶R̶L̶F̶) "|"Line3 Column3 (̶C̶R̶L̶F̶) Line3 Column3"|"Line3"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)

I tried to make a loop (when i have a line with a pipe number < header then i delete his CRLF and then i restart from the beginning) but it doesn't work...

Body:
You could use csv module to read rows and do anything you want then write it back.

import csv

with open('old_file.csv') as f:
    reader = csv.DictReader(f, delimiter='|')
    with open('new_file.csv', 'w') as wf:
        writer = csv.DictWriter(wf, reader.fieldnames, delimiter='|')
        for row in reader:
            writer.writerow({h: v.replace('\r\n', '') for h, v in row.items()})


问:
Cannot POST to server even with CORS
I am trying to send a POST to a given server. I am using an XMLHttpRequest and I keep getting
XMLHttpRequest cannot load http://example.org. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. I understand the concept of CORS and I have added

```<code>http_connection.withCredentials = true;
http_connection.setRequestHeader('Access-Control-Allow-Headers', '*');
http_connection.setRequestHeader('Access-Control-Allow-Origin', '*');
</code>```

though they might not all be necessary. I am still getting the error. Is there something else with XMLHttpRequests I can try? More over how can I see if the given server just simply cannot be POSTed to?

答: --disable-web-security works but makes your browser's security vulnerable, you might get any viruses or malwares from the internet.

Title: Cannot POST to server even with CORS

Body:
I am trying to send a POST to a given server. I am using an XMLHttpRequest and I keep getting
XMLHttpRequest cannot load http://example.org. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. I understand the concept of CORS and I have added

http_connection.withCredentials = true;
http_connection.setRequestHeader('Access-Control-Allow-Headers', '*');
http_connection.setRequestHeader('Access-Control-Allow-Origin', '*');

though they might not all be necessary. I am still getting the error. Is there something else with XMLHttpRequests I can try? More over how can I see if the given server just simply cannot be POSTed to?


问:
Renaming symbols fails with errors
i have installed new glib library version 2.6 , And after creation i am trying to rename some of the symbols in glib library using objcopy command. Renaming symbols is necessary for our project support.

It fails with error below

```<code>objcopy --redefine-syms=glibrename libglib-2.0.a
BFD: libglib-2.0.a(deprecated_gcompletion.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
</code>```

glibrename is a file where it has all glib original symbols defined and renamed symbols that i want to do.

Example file contents will be :

```<code> glib_melloc test_glib_melloc
 glib_sym    test_glib_sym
</code>```

Here is my objcopy version:

```<code>[kltest@il-kltest ~]$ objcopy --version
GNU objcopy version 2.20.51.0.2-5.36.el6 20100205
Copyright 2009 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) any later version.
 This program has absolutely no warranty.
</code>```

Anyone please help why i am hitting this issue, Any idea?

答: Binutils 2.20 is just too old I'm afraid. (It's 9 years old.) Support for relocation type 42 was introduced about v2.25 /.26.</p>

Title: Renaming symbols fails with errors

Body:
i have installed new glib library version 2.6 , And after creation i am trying to rename some of the symbols in glib library using objcopy command. Renaming symbols is necessary for our project support.

It fails with error below

objcopy --redefine-syms=glibrename libglib-2.0.a
BFD: libglib-2.0.a(deprecated_gcompletion.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42
BFD: BFD version 2.20.51.0.2-5.36.el6 20100205 assertion fail elf64-x86-64.c:290
BFD: libglib-2.0.a(deprecated_gthread-deprecated.c.o): invalid relocation type 42

glibrename is a file where it has all glib original symbols defined and renamed symbols that i want to do.

Example file contents will be :

 glib_melloc test_glib_melloc
 glib_sym    test_glib_sym

Here is my objcopy version:

[kltest@il-kltest ~]$ objcopy --version
GNU objcopy version 2.20.51.0.2-5.36.el6 20100205
Copyright 2009 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) any later version.
 This program has absolutely no warranty.

Anyone please help why i am hitting this issue, Any idea?


问:
Generate an OAuth access token with openssl and c++
I need to get an access token (for a service account) for the google's OAuth authentication service. I tried several things an studied a lot of on the web but don't succeed.

Basically i followed https://developers.google.com/accounts/docs/OAuth2ServiceAccount

What i have done (VS2013):

```<code>int _tmain(int argc, _TCHAR* argv[])
{
    Json::Value jwt_header;
    Json::Value jwt_claim_set;
    std::string jwt_b64;
    std::time_t t = std::time(NULL);
    Json::FastWriter jfw;
    Json::StyledWriter jsw;

    /* Create jwt header */
    jwt_header["alg"] = "RS256";
    jwt_header["typ"] = "JWT";
    std::cout << jsw.write(jwt_header);

    /* Create jwt claim set */
    jwt_claim_set["iss"] = "myid@developer.gserviceaccount.com"; /* service account email address */
    jwt_claim_set["scope"] = "https://www.googleapis.com/auth/plus.me" /* scope of requested access token */;
    jwt_claim_set["aud"] = "https://accounts.google.com/o/oauth2/token"; /* intended target of the assertion for an access token */
    jwt_claim_set["iad"] = std::to_string(t); /* issued time */
    jwt_claim_set["exp"] = std::to_string(t+3600); /* expire time*/
    std::cout << jsw.write(jwt_claim_set);

    /* create http POST request body */
    /* for header */
    std::string json_buffer;
    std::string json_buffer1;
    json_buffer = jfw.write(jwt_header);
    json_buffer = json_buffer.substr(0, json_buffer.size() - 1);
    json_buffer = base64_encode(reinterpret_cast<const unsigned char*>(json_buffer.c_str()), json_buffer.length(), true); /* urlsafeBasic64 encode*/
    json_buffer1.clear();
    std::remove_copy(json_buffer.begin(), json_buffer.end(), std::back_inserter(json_buffer1), '=');
    jwt_b64 = json_buffer1;
    jwt_b64 += ".";

    /* for claim set */
    json_buffer = jfw.write(jwt_claim_set);
    json_buffer = json_buffer.substr(0, json_buffer.size() - 1);
    json_buffer = base64_encode(reinterpret_cast<const unsigned char*>(json_buffer.c_str()), json_buffer.length(), true); /* urlsafeBasic64 encode*/
    json_buffer1.clear();
    std::remove_copy(json_buffer.begin(), json_buffer.end(), std::back_inserter(json_buffer1), '=');
    jwt_b64 += json_buffer1;

    /* for signature */
    std::string jwt_signature = jws_sign(jwt_b64, "key.p12");
    if (!jwt_signature.empty())
    {
        jwt_b64 += ".";
        json_buffer1.clear();
        std::remove_copy(jwt_signature.begin(), jwt_signature.end(), std::back_inserter(json_buffer1), '=');
        jwt_b64 += json_buffer1;
        write2file("jwt.bat", jwt_b64); /* for test purpose calling with curl */
    }
    else
        std::cout << "Error creating signature";

    return 0;
}

int write2file(std::string filename, std::string data)
{
    std::ofstream f(filename);
    f << "%curl% -d \"grant_type=urn%%3Aietf%%3Aparams%%3Aoauth%%3Agrant-type%%3Ajwt-bearer&assertion=";
    f << data;
    f << "\" https://accounts.google.com/o/oauth2/token";
    f.close();
    return 0;
}

std::string jws_sign(std::string data, std::string pkcs12_path) {

    SHA256_CTX mctx;
    unsigned char hash[SHA256_DIGEST_LENGTH];
    size_t hlen = SHA256_DIGEST_LENGTH;
    const char *buf = data.c_str();
    int n = strlen((const char*) buf);

    SHA256_Init(&mctx);
    SHA256_Update(&mctx, buf, n);
    SHA256_Final(hash, &mctx);

    std::string signature_b64;
    unsigned char *sig = NULL;
    size_t slen = 0;
    EVP_PKEY_CTX *kctx;
    EVP_PKEY *key = getPkey(pkcs12_path);
    kctx = EVP_PKEY_CTX_new(key, NULL);
    if (!kctx) goto err;

    if (EVP_PKEY_sign_init(kctx) <= 0) goto err;

    if (EVP_PKEY_CTX_set_rsa_padding(kctx, RSA_PKCS1_PADDING) <= 0) goto err;

    if (EVP_PKEY_CTX_set_signature_md(kctx, EVP_sha256()) <= 0) goto err;

    /* Determine buffer length */
    if (EVP_PKEY_sign(kctx, NULL, &slen, hash, hlen) <= 0) goto err;

    sig = (unsigned char *) OPENSSL_malloc(slen);

    if (!sig) goto err;

    if (EVP_PKEY_sign(kctx, sig, &slen, hash, hlen) <= 0) goto err;

    signature_b64 = base64_encode(sig, (unsigned int)slen, true);

    return signature_b64;

err:

    /* Clean up */
    EVP_cleanup();

    signature_b64.clear();
    return signature_b64;
}
</code>```

All i receive back is

```<code>{
  "error" : "invalid_grant"
}
</code>```

So if someone can point me into the right direction would be great.
It would also help, if someone can point me to get the thing working by manually generating the jwt request out of openssl commands.

I'm working with VS2013

答:
I've made a class for authentication on C++, will leave it here, may be someone may need it.</p>

```<code>// YOU SHOULD GO TO Credentials SECTION FOR YOUR PROJECT AT https://console.developers.google.com/
// MAKE Service Account AND GET AUTHENTICATION JSON FROM IT,
// PLACE IT TO BUILD FOLDER AND CALL IT google_service_account.json

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>

// SSL INCLUDES
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/bio.h>

// https://github.com/nlohmann/json
#include <nlohmann/json.hpp>
using json = nlohmann::json;

class TGoogleAuthCpp {
    json serviceAccountJSON;
    bool serviceAccountExists;

    void readServiceAccountJson();
    RSA* createPrivateRSA(std::string key);

    bool RSASign( RSA* rsa,
                  const unsigned char* Msg,
                  size_t MsgLen,
                  unsigned char** EncMsg,
                  size_t* MsgLenEnc);

    std::string signMessage(std::string privateKey, std::string plainText);
    std::string url_encode(const std::string &value);
    std::string base64_encode(const std::string &in);

public:
    TGoogleAuthCpp();
    int createRequest();
};

TGoogleAuthCpp::TGoogleAuthCpp() {
    serviceAccountExists = false;
    readServiceAccountJson();
}

RSA* TGoogleAuthCpp::createPrivateRSA(std::string key) {
    RSA *rsa = NULL;
    const char* c_string = key.c_str();
    BIO * keybio = BIO_new_mem_buf((void*)c_string, -1);
    if (keybio==NULL) {
        return 0;
    }
    rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
    return rsa;
}

bool TGoogleAuthCpp::RSASign( RSA* rsa,
                                const unsigned char* Msg,
                                size_t MsgLen,
                                unsigned char** EncMsg,
                                size_t* MsgLenEnc) {
    EVP_MD_CTX* m_RSASignCtx = EVP_MD_CTX_create();
    EVP_PKEY* priKey  = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(priKey, rsa);
    if (EVP_DigestSignInit(m_RSASignCtx,NULL, EVP_sha256(), NULL,priKey)<=0) {
        return false;
    }
    if (EVP_DigestSignUpdate(m_RSASignCtx, Msg, MsgLen) <= 0) {
        return false;
    }
    if (EVP_DigestSignFinal(m_RSASignCtx, NULL, MsgLenEnc) <=0) {
        return false;
    }
    *EncMsg = (unsigned char*)malloc(*MsgLenEnc);
    if (EVP_DigestSignFinal(m_RSASignCtx, *EncMsg, MsgLenEnc) <= 0) {
        return false;
    }
    EVP_MD_CTX_cleanup(m_RSASignCtx);
    return true;
}

std::string TGoogleAuthCpp::signMessage(std::string privateKey, std::string plainText) {
    RSA* privateRSA = createPrivateRSA(privateKey);
    unsigned char* encMessage;
    size_t encMessageLength;
    RSASign(privateRSA, (unsigned char*) plainText.c_str(), plainText.length(), &encMessage, &encMessageLength);
    std::string str1((char *)(encMessage), encMessageLength);
    free(encMessage);
    return base64_encode(str1);
}

void TGoogleAuthCpp::readServiceAccountJson() {

    std::string fname = "google_service_account.json";

    std::string line;
    std::ifstream myfile (fname);
    if (myfile.good()) {

        std::stringstream ss;

        if (myfile.is_open()) {
            while (getline(myfile, line)) {
                ss << line << '\n';
            }
            myfile.close();
            serviceAccountJSON = json::parse(ss.str());
            serviceAccountExists = true;
        }
    }
}

std::string TGoogleAuthCpp::base64_encode(const std::string &in) {
    std::string out;

    std::string base64_encode_b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//=

    int val=0, valb=-6;
    for (unsigned char c : in) {
        val = (val<<8) + c;
        valb += 8;
        while (valb>=0) {
            out.push_back(base64_encode_b[(val>>valb)&0x3F]);
            valb-=6;
        }
    }
    if (valb>-6) out.push_back(base64_encode_b[((val<<8)>>(valb+8))&0x3F]);
    while (out.size()%4) out.push_back('=');
    return out;
}

std::string TGoogleAuthCpp::url_encode(const std::string &value) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
        std::string::value_type c = (*i);

        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Any other characters are percent-encoded
        escaped << std::uppercase;
        escaped << '%' << std::setw(2) << int((unsigned char) c);
        escaped << std::nouppercase;
    }

    return escaped.str();
}

int TGoogleAuthCpp::createRequest() {
    if (!serviceAccountExists) return 0;
    json jwt_header;
    json jwt_claim_set;
    std::time_t t = std::time(NULL);

    // Create jwt header
    jwt_header["alg"] = "RS256";
    jwt_header["typ"] = "JWT";

    // Create jwt claim set
    jwt_claim_set["iss"] = serviceAccountJSON["client_email"]; /* service account email address */
    jwt_claim_set["scope"] = "https://www.googleapis.com/auth/androidpublisher" /* scope of requested access token */;
    jwt_claim_set["aud"] = serviceAccountJSON["token_uri"]; /* intended target of the assertion for an access token */
    jwt_claim_set["iat"] = t; /* issued time */
    jwt_claim_set["exp"] = t+3600; /* expire time*/

    // web token
    std::stringstream jwt_ss;

    // header
    jwt_ss << base64_encode(jwt_header.dump());
    jwt_ss << ".";

    // claim set
    jwt_ss << base64_encode(jwt_claim_set.dump());

    // signature
    std::string signed_msg = signMessage(serviceAccountJSON["private_key"], jwt_ss.str());

    jwt_ss << "." << signed_msg;

    std::stringstream post_body_ss;
    post_body_ss << "curl -d '";
    post_body_ss << "grant_type=" << url_encode("urn:ietf:params:oauth:grant-type:jwt-bearer");
    post_body_ss << "&assertion=" << url_encode(jwt_ss.str());
    post_body_ss << "' https://oauth2.googleapis.com/token";
    std::string post_body = post_body_ss.str();
    std::cout << post_body << std::endl;

    return 1;
}

int main() {
    TGoogleAuthCpp auth;
    int res = auth.createRequest();
}
</code>```

Body:
I need to get an access token (for a service account) for the google's OAuth authentication service. I tried several things an studied a lot of on the web but don't succeed.

Basically i followed https://developers.google.com/accounts/docs/OAuth2ServiceAccount

What i have done (VS2013):

int _tmain(int argc, _TCHAR* argv[])
{
    Json::Value jwt_header;
    Json::Value jwt_claim_set;
    std::string jwt_b64;
    std::time_t t = std::time(NULL);
    Json::FastWriter jfw;
    Json::StyledWriter jsw;

    /* Create jwt header */
    jwt_header["alg"] = "RS256";
    jwt_header["typ"] = "JWT";
    std::cout << jsw.write(jwt_header);

    /* Create jwt claim set */
    jwt_claim_set["iss"] = "myid@developer.gserviceaccount.com"; /* service account email address */
    jwt_claim_set["scope"] = "https://www.googleapis.com/auth/plus.me" /* scope of requested access token */;
    jwt_claim_set["aud"] = "https://accounts.google.com/o/oauth2/token"; /* intended target of the assertion for an access token */
    jwt_claim_set["iad"] = std::to_string(t); /* issued time */
    jwt_claim_set["exp"] = std::to_string(t+3600); /* expire time*/
    std::cout << jsw.write(jwt_claim_set);

    /* create http POST request body */
    /* for header */
    std::string json_buffer;
    std::string json_buffer1;
    json_buffer = jfw.write(jwt_header);
    json_buffer = json_buffer.substr(0, json_buffer.size() - 1);
    json_buffer = base64_encode(reinterpret_cast<const unsigned char*>(json_buffer.c_str()), json_buffer.length(), true); /* urlsafeBasic64 encode*/
    json_buffer1.clear();
    std::remove_copy(json_buffer.begin(), json_buffer.end(), std::back_inserter(json_buffer1), '=');
    jwt_b64 = json_buffer1;
    jwt_b64 += ".";

    /* for claim set */
    json_buffer = jfw.write(jwt_claim_set);
    json_buffer = json_buffer.substr(0, json_buffer.size() - 1);
    json_buffer = base64_encode(reinterpret_cast<const unsigned char*>(json_buffer.c_str()), json_buffer.length(), true); /* urlsafeBasic64 encode*/
    json_buffer1.clear();
    std::remove_copy(json_buffer.begin(), json_buffer.end(), std::back_inserter(json_buffer1), '=');
    jwt_b64 += json_buffer1;

    /* for signature */
    std::string jwt_signature = jws_sign(jwt_b64, "key.p12");
    if (!jwt_signature.empty())
    {
        jwt_b64 += ".";
        json_buffer1.clear();
        std::remove_copy(jwt_signature.begin(), jwt_signature.end(), std::back_inserter(json_buffer1), '=');
        jwt_b64 += json_buffer1;
        write2file("jwt.bat", jwt_b64); /* for test purpose calling with curl */
    }
    else
        std::cout << "Error creating signature";

    return 0;
}

int write2file(std::string filename, std::string data)
{
    std::ofstream f(filename);
    f << "%curl% -d \"grant_type=urn%%3Aietf%%3Aparams%%3Aoauth%%3Agrant-type%%3Ajwt-bearer&assertion=";
    f << data;
    f << "\" https://accounts.google.com/o/oauth2/token";
    f.close();
    return 0;
}

std::string jws_sign(std::string data, std::string pkcs12_path) {

    SHA256_CTX mctx;
    unsigned char hash[SHA256_DIGEST_LENGTH];
    size_t hlen = SHA256_DIGEST_LENGTH;
    const char *buf = data.c_str();
    int n = strlen((const char*) buf);

    SHA256_Init(&mctx);
    SHA256_Update(&mctx, buf, n);
    SHA256_Final(hash, &mctx);

    std::string signature_b64;
    unsigned char *sig = NULL;
    size_t slen = 0;
    EVP_PKEY_CTX *kctx;
    EVP_PKEY *key = getPkey(pkcs12_path);
    kctx = EVP_PKEY_CTX_new(key, NULL);
    if (!kctx) goto err;

    if (EVP_PKEY_sign_init(kctx) <= 0) goto err;

    if (EVP_PKEY_CTX_set_rsa_padding(kctx, RSA_PKCS1_PADDING) <= 0) goto err;

    if (EVP_PKEY_CTX_set_signature_md(kctx, EVP_sha256()) <= 0) goto err;

    /* Determine buffer length */
    if (EVP_PKEY_sign(kctx, NULL, &slen, hash, hlen) <= 0) goto err;

    sig = (unsigned char *) OPENSSL_malloc(slen);

    if (!sig) goto err;

    if (EVP_PKEY_sign(kctx, sig, &slen, hash, hlen) <= 0) goto err;

    signature_b64 = base64_encode(sig, (unsigned int)slen, true);

    return signature_b64;

err:

    /* Clean up */
    EVP_cleanup();

    signature_b64.clear();
    return signature_b64;
}

All i receive back is

{
  "error" : "invalid_grant"
}

So if someone can point me into the right direction would be great.
It would also help, if someone can point me to get the thing working by manually generating the jwt request out of openssl commands.

I'm working with VS2013

Body:
I've made a class for authentication on C++, will leave it here, may be someone may need it.

// YOU SHOULD GO TO Credentials SECTION FOR YOUR PROJECT AT https://console.developers.google.com/
// MAKE Service Account AND GET AUTHENTICATION JSON FROM IT,
// PLACE IT TO BUILD FOLDER AND CALL IT google_service_account.json

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>

// SSL INCLUDES
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/bio.h>

// https://github.com/nlohmann/json
#include <nlohmann/json.hpp>
using json = nlohmann::json;

class TGoogleAuthCpp {
    json serviceAccountJSON;
    bool serviceAccountExists;

    void readServiceAccountJson();
    RSA* createPrivateRSA(std::string key);

    bool RSASign( RSA* rsa,
                  const unsigned char* Msg,
                  size_t MsgLen,
                  unsigned char** EncMsg,
                  size_t* MsgLenEnc);

    std::string signMessage(std::string privateKey, std::string plainText);
    std::string url_encode(const std::string &value);
    std::string base64_encode(const std::string &in);

public:
    TGoogleAuthCpp();
    int createRequest();
};

TGoogleAuthCpp::TGoogleAuthCpp() {
    serviceAccountExists = false;
    readServiceAccountJson();
}

RSA* TGoogleAuthCpp::createPrivateRSA(std::string key) {
    RSA *rsa = NULL;
    const char* c_string = key.c_str();
    BIO * keybio = BIO_new_mem_buf((void*)c_string, -1);
    if (keybio==NULL) {
        return 0;
    }
    rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
    return rsa;
}

bool TGoogleAuthCpp::RSASign( RSA* rsa,
                                const unsigned char* Msg,
                                size_t MsgLen,
                                unsigned char** EncMsg,
                                size_t* MsgLenEnc) {
    EVP_MD_CTX* m_RSASignCtx = EVP_MD_CTX_create();
    EVP_PKEY* priKey  = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(priKey, rsa);
    if (EVP_DigestSignInit(m_RSASignCtx,NULL, EVP_sha256(), NULL,priKey)<=0) {
        return false;
    }
    if (EVP_DigestSignUpdate(m_RSASignCtx, Msg, MsgLen) <= 0) {
        return false;
    }
    if (EVP_DigestSignFinal(m_RSASignCtx, NULL, MsgLenEnc) <=0) {
        return false;
    }
    *EncMsg = (unsigned char*)malloc(*MsgLenEnc);
    if (EVP_DigestSignFinal(m_RSASignCtx, *EncMsg, MsgLenEnc) <= 0) {
        return false;
    }
    EVP_MD_CTX_cleanup(m_RSASignCtx);
    return true;
}

std::string TGoogleAuthCpp::signMessage(std::string privateKey, std::string plainText) {
    RSA* privateRSA = createPrivateRSA(privateKey);
    unsigned char* encMessage;
    size_t encMessageLength;
    RSASign(privateRSA, (unsigned char*) plainText.c_str(), plainText.length(), &encMessage, &encMessageLength);
    std::string str1((char *)(encMessage), encMessageLength);
    free(encMessage);
    return base64_encode(str1);
}

void TGoogleAuthCpp::readServiceAccountJson() {

    std::string fname = "google_service_account.json";

    std::string line;
    std::ifstream myfile (fname);
    if (myfile.good()) {

        std::stringstream ss;

        if (myfile.is_open()) {
            while (getline(myfile, line)) {
                ss << line << '\n';
            }
            myfile.close();
            serviceAccountJSON = json::parse(ss.str());
            serviceAccountExists = true;
        }
    }
}

std::string TGoogleAuthCpp::base64_encode(const std::string &in) {
    std::string out;

    std::string base64_encode_b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//=

    int val=0, valb=-6;
    for (unsigned char c : in) {
        val = (val<<8) + c;
        valb += 8;
        while (valb>=0) {
            out.push_back(base64_encode_b[(val>>valb)&0x3F]);
            valb-=6;
        }
    }
    if (valb>-6) out.push_back(base64_encode_b[((val<<8)>>(valb+8))&0x3F]);
    while (out.size()%4) out.push_back('=');
    return out;
}

std::string TGoogleAuthCpp::url_encode(const std::string &value) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
        std::string::value_type c = (*i);

        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Any other characters are percent-encoded
        escaped << std::uppercase;
        escaped << '%' << std::setw(2) << int((unsigned char) c);
        escaped << std::nouppercase;
    }

    return escaped.str();
}

int TGoogleAuthCpp::createRequest() {
    if (!serviceAccountExists) return 0;
    json jwt_header;
    json jwt_claim_set;
    std::time_t t = std::time(NULL);

    // Create jwt header
    jwt_header["alg"] = "RS256";
    jwt_header["typ"] = "JWT";

    // Create jwt claim set
    jwt_claim_set["iss"] = serviceAccountJSON["client_email"]; /* service account email address */
    jwt_claim_set["scope"] = "https://www.googleapis.com/auth/androidpublisher" /* scope of requested access token */;
    jwt_claim_set["aud"] = serviceAccountJSON["token_uri"]; /* intended target of the assertion for an access token */
    jwt_claim_set["iat"] = t; /* issued time */
    jwt_claim_set["exp"] = t+3600; /* expire time*/

    // web token
    std::stringstream jwt_ss;

    // header
    jwt_ss << base64_encode(jwt_header.dump());
    jwt_ss << ".";

    // claim set
    jwt_ss << base64_encode(jwt_claim_set.dump());

    // signature
    std::string signed_msg = signMessage(serviceAccountJSON["private_key"], jwt_ss.str());

    jwt_ss << "." << signed_msg;

    std::stringstream post_body_ss;
    post_body_ss << "curl -d '";
    post_body_ss << "grant_type=" << url_encode("urn:ietf:params:oauth:grant-type:jwt-bearer");
    post_body_ss << "&assertion=" << url_encode(jwt_ss.str());
    post_body_ss << "' https://oauth2.googleapis.com/token";
    std::string post_body = post_body_ss.str();
    std::cout << post_body << std::endl;

    return 1;
}

int main() {
    TGoogleAuthCpp auth;
    int res = auth.createRequest();
}


问:
Django urls handle slug with slash inside e.g. /main/subpage
I have this in my urls.py

```<code>path('<str:slug>', views.page, name='page'),
</code>```

which I want to handle any links that didn't get caught above, think of the slug like a url link that can be deep like main\subpage\sub-sub-link which I can match to a page.

Thing is it seems the slug will only handle one layer like \main is there a way to pipe all of that sublink info e.g. domain.com/this/that/that-that so my slug will be this/that/that-that

答:
you can use it likepath('<slug:post>/', views.page, name='page')

But remember your page function should take post as slug parameter.

Like

```<code>def page(request, post):
  post = get_object_or_404(model_name, post)
</code>```

And when using a tag for links you can use it like href="{% url 'page' post.slug %}"

Body:
I have this in my urls.py

path('<str:slug>', views.page, name='page'),

which I want to handle any links that didn't get caught above, think of the slug like a url link that can be deep like main\subpage\sub-sub-link which I can match to a page.

Thing is it seems the slug will only handle one layer like \main is there a way to pipe all of that sublink info e.g. domain.com/this/that/that-that so my slug will be this/that/that-that

Body:
you can use it likepath('<slug:post>/', views.page, name='page')

But remember your page function should take post as slug parameter.

Like

def page(request, post):
  post = get_object_or_404(model_name, post)

And when using a tag for links you can use it like href="{% url 'page' post.slug %}"


问:
Angular reactive form and ngx-admin problem with error FormGroup isn't a known property of form
I need to use angular ReactiveFormsModule on my custom component with ngx-admin theme but I have the problem when compiling for error: "Can't bind to 'formGroup' since it isn't a known property of 'form'", on VisualStudioCode no error reported.

I have add "import { FormsModule, ReactiveFormsModule } from '@angular/forms';" on my module also on pages.module.ts and app.module.ts without success, I have always that error when compiling.

If I try to add reactive form on Register page of ngx-admin no error when compiling.

Can someone help me to find where I'm wrong?

答:
this is my app.module.ts</p>

```<code>import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http';
import { CoreModule } from './@core/core.module';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ThemeModule } from './@theme/theme.module';
import { AuthModule } from './@auth/auth.module';

import {
  NbChatModule,
  NbDatepickerModule,
  NbDialogModule,
  NbMenuModule,
  NbSidebarModule,
  NbToastrModule,
  NbWindowModule,
} from '@nebular/theme';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,
    AuthModule.forRoot(),
    FormsModule,
    ReactiveFormsModule,
    NbSidebarModule.forRoot(),
    NbMenuModule.forRoot(),
    NbDatepickerModule.forRoot(),
    NbDialogModule.forRoot(),
    NbWindowModule.forRoot(),
    NbToastrModule.forRoot(),
    NbChatModule.forRoot({
      messageGoogleMapKey: 'AIzaSyA_wNuCzia92MAmdLRzmqitRGvCF7wCZPY',
    }),
    CoreModule.forRoot(),
    ThemeModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [],
})
export class AppModule {
}
</code>```

Body:
this is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http';
import { CoreModule } from './@core/core.module';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ThemeModule } from './@theme/theme.module';
import { AuthModule } from './@auth/auth.module';

import {
  NbChatModule,
  NbDatepickerModule,
  NbDialogModule,
  NbMenuModule,
  NbSidebarModule,
  NbToastrModule,
  NbWindowModule,
} from '@nebular/theme';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,
    AuthModule.forRoot(),
    FormsModule,
    ReactiveFormsModule,
    NbSidebarModule.forRoot(),
    NbMenuModule.forRoot(),
    NbDatepickerModule.forRoot(),
    NbDialogModule.forRoot(),
    NbWindowModule.forRoot(),
    NbToastrModule.forRoot(),
    NbChatModule.forRoot({
      messageGoogleMapKey: 'AIzaSyA_wNuCzia92MAmdLRzmqitRGvCF7wCZPY',
    }),
    CoreModule.forRoot(),
    ThemeModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [],
})
export class AppModule {
}


问:
Xcode Async Unit Tests waiting on Main Thread
I'm trying to test some asynchronous code using Unit Tests in Xcode, but I'm getting a blocked main thread.

The problem is that some of the code being tested expects to receive a callback from an iOS class (AVFoundation). However, it seems the AVFoundation class will only callback on the Main thread.

The problem is that if I'm doing an async unit test, then the test actually blocks the main thread while it's waiting, so the callback can never be sent.

I'm pretty sure this is the problem. Is there any way to run the tests from another thread or have an XCTWaiter that doesn't block the main thread?

Edit:
After looking a bit at the docs, it seems like the best way to do this would be to run the entire test case on a background thread. However, in my current project the testing is all set up automatically. I wonder if anyone knows how to setup a test case / run manually. That way I could run it on another thread.

答:
Considering @BetterLateThanNever's answer. Here is the code snippet how I test my code using callback in main-thread.</p>
```<code>func test() {
    let expectation = XCTestExpectation(description: "Test")

    DispatchQueue.global(qos: .default).async {
        ...
        ...
        let myObj = MyObj()
        myObj.runSomethingMayWaitForMainThread()
        ...
        ...

        XCTAssert(myObj.result)
        expectation.fulfill()
    }

    wait(for: [expectation], timeout: 50.0)
}
</code>```

Body:
Considering @BetterLateThanNever's answer. Here is the code snippet how I test my code using callback in main-thread.

func test() {
    let expectation = XCTestExpectation(description: "Test")

    DispatchQueue.global(qos: .default).async {
        ...
        ...
        let myObj = MyObj()
        myObj.runSomethingMayWaitForMainThread()
        ...
        ...

        XCTAssert(myObj.result)
        expectation.fulfill()
    }

    wait(for: [expectation], timeout: 50.0)
}


问:
Use SVG from node_modules
I created a node_module with all svg files to modularize our architecture.

It works fine when I call it using:

```<code><q-icon>
  <svg>
    <use xlink:href="~svgmodule/svgs/icons.svg#addicon"></use>
  </svg>
</q-icon>
</code>```

However when doing like this:

```<code><q-icon>
  <svg>
    <use :xlink:href="'~svgmodule/svgs/icons.svg#' + iconParameter"></use>
  </svg>
</q-icon>
</code>```

And iconParameter is defined below as:

```<code>iconParameter: 'addicon'
</code>```

This is the error I am getting:

```<code>vue.runtime.esm.js?0594:6757 GET http://localhost:8080/~svgmodule/svgs/icons.svg net::ERR_ABORTED 404 (Not Found)
</code>```

I also tried this and it works:

```<code><use xlink:href="../../../../../../../../node_modules/svgmodule/svgs/icons.svg#addicon"></use>
</code>```

But this one doesnt:

```<code><use :xlink:href="'../../../../../../../../node_modules/svgmodule/svgs/icons.svg#' + iconParameter"></use>
</code>```

Nor

```<code><use :xlink:href="'../../../../../../../../node_modules/svgmodule/svgs/icons.svg#addicon'"></use>
</code>```

Help!!

答:
vue-loader does not convert expressions into webpack module requests.

You have to manually call require. This is what vue-loader does internally.

```<code><q-icon>
  <svg>
    <use :xlink:href="require('~svgmodule/svgs/icons.svg') + '#' + iconParameter"></use>
  </svg>
</q-icon>
</code>```

Title: Use SVG from node_modules

Body:
I created a node_module with all svg files to modularize our architecture.

It works fine when I call it using:

<q-icon>
  <svg>
    <use xlink:href="~svgmodule/svgs/icons.svg#addicon"></use>
  </svg>
</q-icon>

However when doing like this:

<q-icon>
  <svg>
    <use :xlink:href="'~svgmodule/svgs/icons.svg#' + iconParameter"></use>
  </svg>
</q-icon>

And iconParameter is defined below as:

iconParameter: 'addicon'

This is the error I am getting:

vue.runtime.esm.js?0594:6757 GET http://localhost:8080/~svgmodule/svgs/icons.svg net::ERR_ABORTED 404 (Not Found)

I also tried this and it works:

<use xlink:href="../../../../../../../../node_modules/svgmodule/svgs/icons.svg#addicon"></use>

But this one doesnt:

<use :xlink:href="'../../../../../../../../node_modules/svgmodule/svgs/icons.svg#' + iconParameter"></use>

Nor

<use :xlink:href="'../../../../../../../../node_modules/svgmodule/svgs/icons.svg#addicon'"></use>

Help!!

Body:
vue-loader does not convert expressions into webpack module requests.

You have to manually call require. This is what vue-loader does internally.

<q-icon>
  <svg>
    <use :xlink:href="require('~svgmodule/svgs/icons.svg') + '#' + iconParameter"></use>
  </svg>
</q-icon>


问:
Extending enums in C++?
Is there a way in C++ to extend/"inherit" enums?

I.E:

```<code>enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};
</code>```

or at least define a conversion between them?

答:
I do this</p>
```<code>enum OPC_t // frame Operation Codes
{
      OPC_CVSND = 0 // Send CV value
    , OPC_CVREQ = 1 // Request CV (only valid for master app)
    , OPC_COMND = 2 // Command
    , OPC_HRTBT = 3 // Heart Beat
};
enum rxStatus_t     // this extends OPC_t
{
      RX_CVSND = OPC_CVSND  // Send CV value
    , RX_CVREQ = OPC_CVREQ  // Request CV
    , RX_COMND = OPC_COMND  // Command
    , RX_HRTBT = OPC_HRTBT  // Heart Beat
    , RX_NONE       // No new Rx
    , RX_NEWCHIP        // new chip detected
};
</code>```

ContentLicense: CC BY-SA 2.5

Title: Extending enums in C++?

Body:
Is there a way in C++ to extend/"inherit" enums?

I.E:

enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};

or at least define a conversion between them?

Body:
I do this

enum OPC_t // frame Operation Codes
{
      OPC_CVSND = 0 // Send CV value
    , OPC_CVREQ = 1 // Request CV (only valid for master app)
    , OPC_COMND = 2 // Command
    , OPC_HRTBT = 3 // Heart Beat
};
enum rxStatus_t     // this extends OPC_t
{
      RX_CVSND = OPC_CVSND  // Send CV value
    , RX_CVREQ = OPC_CVREQ  // Request CV
    , RX_COMND = OPC_COMND  // Command
    , RX_HRTBT = OPC_HRTBT  // Heart Beat
    , RX_NONE       // No new Rx
    , RX_NEWCHIP        // new chip detected
};