问:
Getting a screenshot of a UIScrollView, including offscreen parts
I have a UIScrollView decendent that implements a takeScreenshot method that looks like this:

```<code>-(void)takeScreenshot {
  CGRect contextRect  = CGRectMake(0, 0, 768, 1004);
  UIGraphicsBeginImageContext(contextRect.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  // do something with the viewImage here.
}
</code>```

This basically moves to the top of the scroll view, and takes a screenshot of the visible area. It works fine when the iPad is oriented portrait, but when it's in landscape the bottom of the image is cut off (as the height of the visible area is only 748, not 1004).

Is it possible to get a snapshot of the UIScrollView, including areas not on screen? Or do I need to scroll the view down, take a second photo and stitch them together?

答:
Here's another way of doing it, which takes the zoom level into account. I have a scrollview with 4 different UIImageView layers in it, and I want to take a screenshot of their current state:

```<code>float theScale = 1.0f / theScrollView.zoomScale;
// The viewing rectangle in absolute coordinates
CGRect visibleArea = CGRectMake((int)(theScrollView.contentOffset.x * theScale), (int)(theScrollView.contentOffset.y * theScale),
                                (int)(theScrollView.bounds.size.width * theScale), (int)(theScrollView.bounds.size.height * theScale));

NSArray *layers = [NSArray arrayWithObjects:imageLayer1, imageLayer2, imageLayer3, imageLayer4, nil];
UIGraphicsBeginImageContext(visibleArea.size);
for (UIImageView *layer in layers) {
    CALayer *coreLayer = layer.layer;
    coreLayer.bounds = CGRectMake(layer.frame.origin.x - visibleArea.origin.x, layer.frame.origin.y - visibleArea.origin.y, layer.frame.size.width, layer.frame.size.height);
    [coreLayer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

This takes the screenshot in absolute coordinates. That is, if you have a 2048*2048 image in the scrollview and you can see about a quarter of it, then regardless of the resolution of your screen it would take a screenshot of 512*512. If you want to take a screenshot at your screen resolution (say, 320*480) then you have to adjust the image as follows, directly after the above code:

```<code>UIGraphicsBeginImageContext(theScrollView.frame.size);
[screenshot drawInRect:CGRectMake(0, 0, theScrollView.frame.size.width, theScrollView.frame.size.height)];
UIImage *smallScreenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

Body:
I have a UIScrollView decendent that implements a takeScreenshot method that looks like this:

-(void)takeScreenshot {
  CGRect contextRect  = CGRectMake(0, 0, 768, 1004);
  UIGraphicsBeginImageContext(contextRect.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  // do something with the viewImage here.
}

This basically moves to the top of the scroll view, and takes a screenshot of the visible area. It works fine when the iPad is oriented portrait, but when it's in landscape the bottom of the image is cut off (as the height of the visible area is only 748, not 1004).

Is it possible to get a snapshot of the UIScrollView, including areas not on screen? Or do I need to scroll the view down, take a second photo and stitch them together?

Body:
Here's another way of doing it, which takes the zoom level into account. I have a scrollview with 4 different UIImageView layers in it, and I want to take a screenshot of their current state:

float theScale = 1.0f / theScrollView.zoomScale;
// The viewing rectangle in absolute coordinates
CGRect visibleArea = CGRectMake((int)(theScrollView.contentOffset.x * theScale), (int)(theScrollView.contentOffset.y * theScale),
                                (int)(theScrollView.bounds.size.width * theScale), (int)(theScrollView.bounds.size.height * theScale));

NSArray *layers = [NSArray arrayWithObjects:imageLayer1, imageLayer2, imageLayer3, imageLayer4, nil];
UIGraphicsBeginImageContext(visibleArea.size);
for (UIImageView *layer in layers) {
    CALayer *coreLayer = layer.layer;
    coreLayer.bounds = CGRectMake(layer.frame.origin.x - visibleArea.origin.x, layer.frame.origin.y - visibleArea.origin.y, layer.frame.size.width, layer.frame.size.height);
    [coreLayer renderInContext:UIGraphicsGetCurrentContext()];
}
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This takes the screenshot in absolute coordinates. That is, if you have a 2048*2048 image in the scrollview and you can see about a quarter of it, then regardless of the resolution of your screen it would take a screenshot of 512*512. If you want to take a screenshot at your screen resolution (say, 320*480) then you have to adjust the image as follows, directly after the above code:

UIGraphicsBeginImageContext(theScrollView.frame.size);
[screenshot drawInRect:CGRectMake(0, 0, theScrollView.frame.size.width, theScrollView.frame.size.height)];
UIImage *smallScreenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


来源: stackexchange

问:
zlib inflation corrupts when using small buffers
I need to inflate big strings with zlib (around 500 KiB) and i noticed that when using a small buffer the output is corrupted (random letters get converted into giberish) but when switching to a large buffer the output is not corrupted.

This is my code:

                std::string str;
                std::lock_guard<std::mutex> lock(mutex_);

                stream_.next_in = (unsigned char*)deflated.data();
                stream_.avail_in = deflated.size();

                int result = Z_OK;

                do
                {
                    char buffer[1024] = { 0 };

                    stream_.next_out = reinterpret_cast<unsigned char*>(buffer);
                    stream_.avail_out = sizeof(buffer);

                    result = ::inflate(&stream_, Z_NO_FLUSH);

                    str.append(buffer);
                } while (result == Z_OK);

                inflated = std::move(str);
```

Now at 1024 the output gets corrupted but if i switch it to 256 KiB (char buffer[263168]) the output is fine. How can I solve this problem without having to switch to such a big buffer?

答:
If inflate() writes all 1024 bytes to the char array, then the char array won't have any NUL-terminator byte, so when you do your str.append(buffer), what gets added to your inflated string will be the 1024 chars in the array, plus whatever garbage bytes happen to be on the stack after the array, until the first NUL byte is encountered.

I suggest setting stream._avail_out = sizeof(buffer)-1; to avoid that problem.

ContentLicense: CC BY-SA 4.0

Body:
I need to inflate big strings with zlib (around 500 KiB) and i noticed that when using a small buffer the output is corrupted (random letters get converted into giberish) but when switching to a large buffer the output is not corrupted.

This is my code:

                std::string str;
                std::lock_guard<std::mutex> lock(mutex_);

                stream_.next_in = (unsigned char*)deflated.data();
                stream_.avail_in = deflated.size();

                int result = Z_OK;

                do
                {
                    char buffer[1024] = { 0 };

                    stream_.next_out = reinterpret_cast<unsigned char*>(buffer);
                    stream_.avail_out = sizeof(buffer);

                    result = ::inflate(&stream_, Z_NO_FLUSH);

                    str.append(buffer);
                } while (result == Z_OK);

                inflated = std::move(str);

Now at 1024 the output gets corrupted but if i switch it to 256 KiB (char buffer[263168]) the output is fine. How can I solve this problem without having to switch to such a big buffer?


问:
How to embed a script tag into Angular component
I've got an Angular/Typescript website. I need to embed a third party script. The script generates a table.

How can I display that table inside home.component.html. Not at the start or at the beginning, within. Like so.

I've been able to get the script embedded but it doesn't look like the script is rendering so it just displays it in the source but doesn't render the table.

Update

The table can now rendered but only outside of app-root. It should be inside of home.component.html. Source Image

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { DOCUMENT } from '@angular/common'

declare var myExtObject: any;

@Component({
  selector: 'app-careers',
  templateUrl: './careers.component.html',
  styleUrls: ['./careers.component.scss']
})

export class CareersComponent implements OnInit {
  private iife: any

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.iife = myExtObject()
  }

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

<p><strong>home.component.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="BambooHR">
    <script src="https://xxxxxxx.xxx.com" type="text/javascript"></script>
    <div></div>
</div></code>```

The code behind the script is found below. I have that in an external.js file.

var myExtObject = function() {

 //add css file to dom so IE8 recognizes it
 document.write('<link href="https://xxx.css" rel="stylesheet" />');

 var divId="BambooHR-ATS";
 var el=document.getElementById(divId);
 if(!el) {
  document.write("

");
 }

 var xmlhttp;
 var ieFlag = 0;
 if (('XDomainRequest' in window && window.XDomainRequest !== null) && document.documentMode < 10) {
  xmlhttp=new XDomainRequest();
  ieFlag = 1;
 } else if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
 } else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var embedUrl = "https://xxx.php";

 var departmentId = "0";

 if (departmentId) {
  embedUrl += '?departmentId=' + encodeURIComponent(departmentId);
 }

 document.addEventListener('readystatechange', function(event) {
  if (event.target.readyState === "complete") {
   if (ieFlag == 1) { //needed for IE9 CORS
    xmlhttp.onload = loadd;
    xmlhttp.open("GET",embedUrl);
    xmlhttp.send();

   } else {
    xmlhttp.onreadystatechange=function() {
     if(xmlhttp.readyState==4 && xmlhttp.status==200) {

      var content = xmlhttp.responseText;
      var footerId="BambooHR-Footer";
      var fel=document.getElementById(footerId);

      el=document.getElementById(divId);

      if(el && !fel) {
       content += "

";
      }

      if(el) el.innerHTML=content;
     }
    }

    xmlhttp.open("GET",embedUrl,true);
    xmlhttp.send();
   }
  }
 });

 function loadd() { //needed for IE9 CORS
  var content = xmlhttp.responseText;
  var footerId="BambooHR-Footer";
  var fel=document.getElementById(footerId);

  el=document.getElementById(divId);

  if(el && !fel) {
   content += "
Powered by
";
  }
  el.innerHTML=content;
 }
};```

答:
Don't insert the script tag manually. Import the library in your angular.json, in scripts section:

```<code>"scripts": [
  "./node_modules/yourtablelibrary/build/yourtablelibrary.min.js"
]
</code>```

Reference: https://medium.com/@clintpitzak/how-to-use-external-javascript-libraries-in-angular-8-247baacbdccf

Body:
I've got an Angular/Typescript website. I need to embed a third party script. The script generates a table.

How can I display that table inside home.component.html. Not at the start or at the beginning, within. Like so.

I've been able to get the script embedded but it doesn't look like the script is rendering so it just displays it in the source but doesn't render the table.

Update

The table can now rendered but only outside of app-root. It should be inside of home.component.html. Source Image

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { DOCUMENT } from '@angular/common'

declare var myExtObject: any;

@Component({
  selector: 'app-careers',
  templateUrl: './careers.component.html',
  styleUrls: ['./careers.component.scss']
})

export class CareersComponent implements OnInit {
  private iife: any

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.iife = myExtObject()
  }

}

home.component.html

The code behind the script is found below. I have that in an external.js file.

var myExtObject = function() {

 //add css file to dom so IE8 recognizes it
 document.write('<link href="https://xxx.css" rel="stylesheet" />');

 var divId="BambooHR-ATS";
 var el=document.getElementById(divId);
 if(!el) {
  document.write("

");
 }

 var xmlhttp;
 var ieFlag = 0;
 if (('XDomainRequest' in window && window.XDomainRequest !== null) && document.documentMode < 10) {
  xmlhttp=new XDomainRequest();
  ieFlag = 1;
 } else if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
 } else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var embedUrl = "https://xxx.php";

 var departmentId = "0";

 if (departmentId) {
  embedUrl += '?departmentId=' + encodeURIComponent(departmentId);
 }

 document.addEventListener('readystatechange', function(event) {
  if (event.target.readyState === "complete") {
   if (ieFlag == 1) { //needed for IE9 CORS
    xmlhttp.onload = loadd;
    xmlhttp.open("GET",embedUrl);
    xmlhttp.send();

   } else {
    xmlhttp.onreadystatechange=function() {
     if(xmlhttp.readyState==4 && xmlhttp.status==200) {

      var content = xmlhttp.responseText;
      var footerId="BambooHR-Footer";
      var fel=document.getElementById(footerId);

      el=document.getElementById(divId);

      if(el && !fel) {
       content += "

";
      }

      if(el) el.innerHTML=content;
     }
    }

    xmlhttp.open("GET",embedUrl,true);
    xmlhttp.send();
   }
  }
 });

 function loadd() { //needed for IE9 CORS
  var content = xmlhttp.responseText;
  var footerId="BambooHR-Footer";
  var fel=document.getElementById(footerId);

  el=document.getElementById(divId);

  if(el && !fel) {
   content += "
Powered by
";
  }
  el.innerHTML=content;
 }
};

Body:
Don't insert the script tag manually. Import the library in your angular.json, in scripts section:

"scripts": [
  "./node_modules/yourtablelibrary/build/yourtablelibrary.min.js"
]

Reference: https://medium.com/@clintpitzak/how-to-use-external-javascript-libraries-in-angular-8-247baacbdccf


问:
How to modify the price of the dual spec?
I would like to change the price of the dual spec in AzerothCore, how can I do that?

How to build the SQL query to accomplish that?

答:
Short answer

```<code>UPDATE gossip_menu_option SET BoxMoney = XXXXXX WHERE OptionType = 18
</code>```

replace with XXXXXX the actual price (in bronze) that you wish to apply. For example, for 500g it's 500x100x100 = 5000000

Explaination

If you use Keira3 and open any Gossip Menu Option, you'll see that different Option Type can be applied:

and you'll notice that 18 is what we are looking for, thus we query for OptionType = 18

You can find more info about how the tables gossip_menu and gossip_menu_options work in the official documentation:

http://www.azerothcore.org/wiki/gossip_menu

http://www.azerothcore.org/wiki/gossip_menu_option

Body:
Short answer

UPDATE gossip_menu_option SET BoxMoney = XXXXXX WHERE OptionType = 18

replace with XXXXXX the actual price (in bronze) that you wish to apply. For example, for 500g it's 500x100x100 = 5000000

Explaination

If you use Keira3 and open any Gossip Menu Option, you'll see that different Option Type can be applied:

and you'll notice that 18 is what we are looking for, thus we query for OptionType = 18

You can find more info about how the tables gossip_menu and gossip_menu_options work in the official documentation:

http://www.azerothcore.org/wiki/gossip_menu

http://www.azerothcore.org/wiki/gossip_menu_option


问:
How to fetch a launch plan using flyte api's without specifying a sha?
I would like to use the flyte api's to fetch the latest a launchplan for a deployment environment without specifying the sha. </p>

答:
Users are encouraged to specify the SHA when referencing Launch Plans or any other Flyte entity.  However, there is one exception.  Flyte has the notion of an active launch plan. For a given project/domain/name combination, a Launch Plan can have any number of versions. All four fields combined identify one specific Launch Plan.  Those four fields are the primary key. One, at most one, of those launch plans can also be what we call 'active'.

To see which ones are active, you can use the list-active-launch-plans command in flyte-cli

```<code>(flyte) captain@captain-mbp151:~ [k8s: flytemain] $ flyte-cli -p skunkworks -d production list-active-launch-plans -l 200 | grep TestFluidDynamics
NONE                           248935c0f189c9286f0fe13d120645ddf003f339           lp:skunkworks:production:TestFluidDynamics:248935c0f189c9286f0fe13d120645ddf003f339
</code>```

However, please be aware that if a launch plan is active, and has a schedule, that schedule will run. There is no way to make a launch plan "active" but disable its schedule (if it has one).

If you would like to set a launch plan as active, you can do so with the update-launch-plan command.

First find the version you want (results truncated):

```<code>(flyte) captain@captain-mbp151:~ [k8s: flytemain] $ flyte-cli -p skunkworks -d staging list-launch-plan-versions -n TestFluidDynamics
Using default config file at /Users/captain/.flyte/config
Welcome to Flyte CLI! Version: 0.7.0b2
Launch Plan Versions Found for skunkworks:staging:TestFluidDynamics

Version                                            Urn                                                                              Schedule                       Schedule State
d4cf71c20ce987a4899545ae01286f42297a8f3b           lp:skunkworks:staging:TestFluidDynamics:d4cf71c20ce987a4899545ae01286f42297a8f3b
9d3e8d156f7ba0c9ac338b5d09949e88eed1f6c2           lp:skunkworks:staging:TestFluidDynamics:9d3e8d156f7ba0c9ac338b5d09949e88eed1f6c2
248935c0f189c928b6ffe13d120645ddf003f339           lp:skunkworks:staging:TestFluidDynamics:248935c0f189c928b6ffe13d120645ddf003f339
...
</code>```

Then

```<code>flyte-cli update-launch-plan --state active -u lp:skunkworks:staging:TestFluidDynamics:d4cf71c20ce987a4899545ae01286f42297a8f3b
</code>```

Body:
Users are encouraged to specify the SHA when referencing Launch Plans or any other Flyte entity.  However, there is one exception.  Flyte has the notion of an active launch plan. For a given project/domain/name combination, a Launch Plan can have any number of versions. All four fields combined identify one specific Launch Plan.  Those four fields are the primary key. One, at most one, of those launch plans can also be what we call 'active'.

To see which ones are active, you can use the list-active-launch-plans command in flyte-cli

(flyte) captain@captain-mbp151:~ [k8s: flytemain] $ flyte-cli -p skunkworks -d production list-active-launch-plans -l 200 | grep TestFluidDynamics
NONE                           248935c0f189c9286f0fe13d120645ddf003f339           lp:skunkworks:production:TestFluidDynamics:248935c0f189c9286f0fe13d120645ddf003f339

However, please be aware that if a launch plan is active, and has a schedule, that schedule will run. There is no way to make a launch plan "active" but disable its schedule (if it has one).

If you would like to set a launch plan as active, you can do so with the update-launch-plan command.

First find the version you want (results truncated):

(flyte) captain@captain-mbp151:~ [k8s: flytemain] $ flyte-cli -p skunkworks -d staging list-launch-plan-versions -n TestFluidDynamics
Using default config file at /Users/captain/.flyte/config
Welcome to Flyte CLI! Version: 0.7.0b2
Launch Plan Versions Found for skunkworks:staging:TestFluidDynamics

Version                                            Urn                                                                              Schedule                       Schedule State
d4cf71c20ce987a4899545ae01286f42297a8f3b           lp:skunkworks:staging:TestFluidDynamics:d4cf71c20ce987a4899545ae01286f42297a8f3b
9d3e8d156f7ba0c9ac338b5d09949e88eed1f6c2           lp:skunkworks:staging:TestFluidDynamics:9d3e8d156f7ba0c9ac338b5d09949e88eed1f6c2
248935c0f189c928b6ffe13d120645ddf003f339           lp:skunkworks:staging:TestFluidDynamics:248935c0f189c928b6ffe13d120645ddf003f339
...

Then

flyte-cli update-launch-plan --state active -u lp:skunkworks:staging:TestFluidDynamics:d4cf71c20ce987a4899545ae01286f42297a8f3b


问:
In puremvc, how to wait for sendNotification/notifyObservers finishes
In PureMVC / ActionScript, after sending out notifications using send Notification or notify-observers, how do I make sure all the observers has received the notification and finished the work?

On the other words, is sendNotification in synchronized way.

Thanks

答:
As far as I know, the proper way to do this is to put all of your tasks in SimpleCommands, and then add all of these to a single MacroCommand.  As long as the SimpleCommands are synchronous (eg, you don't start any load processes), when the MacroCommand finished, you are guaranteed that all of the SimpleCommands in it have finished.

You may also want to investigate the AsyncCommand utility.  I am not a huge fan of this, but some of my colleagues like it.

ContentLicense: CC BY-SA 3.0


问:
PostgreSQL check parent of parent in query
Okay, I'll try to be as precise as possible. I have a database with comments who have a parent_comment_id. I want to select a number of comments from this table and a matching number of answers to these comments. Here comes my problem: If I arbitrarily select comments, I might grab some who don't have any answers. However, if I select comment answers first, I might grab answers who are an answer to another comment already. So, what I want to do is grab answers who are immediate answers to a comment (parent_comment_id = NULL) and then get those comments base on the parent_comment_id. How would I go about this in a query?

Assume this layout of a database

```<code>comment_id    parent_comment_id
1             NULL
2             NULL
3             1
4             3
5             1
6             3
7             1
8             4
9             NULL
10            NULL
...
</code>```

Now, I would select, let's say 2 answers and the corresponding comments. If I just select the first 2 answers, I would get comment 3 and 4, but if I backtrace those, I would only get comment 1, because comment 4 is an answer to an answer. Instead, I would want to find only comments whose parent comment has no parent comment, which would be comment 3 and 5 in this example.

I haven't really tried anything beyound realizing it doesn't work without somehow recursively getting parents which I have no clue how to do in SQL queries.

答:
I solved it with a pretty easy solution. Might be horrible practice, but works for my use-case ^^

For the given example it would be something like this:

```<code>select distinct on (parent_comment_id) c.id, c.parent_comment_id, c.text
from comments c
where parent_comment_id is not null
and (select parent_comment_id from comments p where id = c.parent_comment_id) is null
</code>```

Body:
Okay, I'll try to be as precise as possible. I have a database with comments who have a parent_comment_id. I want to select a number of comments from this table and a matching number of answers to these comments. Here comes my problem: If I arbitrarily select comments, I might grab some who don't have any answers. However, if I select comment answers first, I might grab answers who are an answer to another comment already. So, what I want to do is grab answers who are immediate answers to a comment (parent_comment_id = NULL) and then get those comments base on the parent_comment_id. How would I go about this in a query?

Assume this layout of a database

comment_id    parent_comment_id
1             NULL
2             NULL
3             1
4             3
5             1
6             3
7             1
8             4
9             NULL
10            NULL
...

Now, I would select, let's say 2 answers and the corresponding comments. If I just select the first 2 answers, I would get comment 3 and 4, but if I backtrace those, I would only get comment 1, because comment 4 is an answer to an answer. Instead, I would want to find only comments whose parent comment has no parent comment, which would be comment 3 and 5 in this example.

I haven't really tried anything beyound realizing it doesn't work without somehow recursively getting parents which I have no clue how to do in SQL queries.

Body:
I solved it with a pretty easy solution. Might be horrible practice, but works for my use-case ^^

For the given example it would be something like this:

select distinct on (parent_comment_id) c.id, c.parent_comment_id, c.text
from comments c
where parent_comment_id is not null
and (select parent_comment_id from comments p where id = c.parent_comment_id) is null


问:
In Powershell, how do I make use of byte array as key type to one of my C# Generic class please?
I have C# class in an external DLL which I cannot modify. Two of the classes in the library are defined as follows which I need to use in my Powershell script.

```<code>public class MyCsharpClass<TKey, TValue> : ISomeBaseClass<TKey, TValue>
{
    public MyCsharpClass(string path, ISomeBaseTranslator<TKey, TValue> translator)
    {
        ...
    }
}
...
...
public class MyByteTranslatorCSharpClass: ISomeBaseTranslator<byte[], byte[]>
{
    ...
}
</code>```

I want to create instance of MyCsharpClass in Powershell script as follows:

```<code>$MyType = [MyCsharpClass[byte[],byte[]]]::new($Path, [MyByteTranslatorCSharpClass]::new())
</code>```

But the above line fails with below error. I can just enter type name in PS ISE command window and get the same error.

```<code>PS C:\> [MyCsharpClass[byte[],byte[]]]
At line:1 char:30
+ [MyCsharpClass[byte[],byte[]]]
+                                                                     ~
Unexpected token ']' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
</code>```

Below line works fine though showing me the type info of my class when I just use byte type for TKey:

```<code>PS C:\> [MyCsharpClass[byte,byte[]]]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MyCsharpClass                           System.Object
</code>```

It seems the first closing bracket ']' for my Key type of byte[] confuses Powershell that type definition is being closed and so it raises error when it observes Unexpected token ']' in the end of expression.

I also tried to replace byte[] type with System.Collections.Generic.List type which works fine now for declaring a type.

```<code>PS C:\> MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MyCsharpClass                           System.Object
</code>```

However the constructor invocation fails this time while passing instance of MyByteTranslatorCSharpClass as second argument in constructor (at the end of below line).

```<code>$MyType = [MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]::new($Path, [MyByteTranslatorCSharpClass]::new())
</code>```

This gives exception of 'System.Management.Automation.MethodException: Cannot convert argument "translator", with value: "MyByteTranslatorCSharpClass", for ".ctor" to type "ISomeBaseTranslator[System.Collections.Generic.List1[System.Byte],System.Collections.Generic.List1[System.Byte]]"

Please let me know in this context, how can I create instance of MyCsharpClass with byte[] type for TKey and TValue generic arguments in Powershell. Please note that I can neither change the DLL side nor do I have its source.

答:
This appears to be a type name parsing bug.

Fortunately, you can easily work around this by "qualifying" the type parameter literals with an extra pair of square brackets ([]) :

```<code>[MyCsharpClass[[byte[]],[byte[]]]]::new(...)
</code>```

... or by constructing the concrete type directly using reflection:

```<code>$myType = [MyCsharpClass`2].MakeGenericType(@([byte[]],[byte[]]))

$myType::new(...)
</code>```

Body:
I have C# class in an external DLL which I cannot modify. Two of the classes in the library are defined as follows which I need to use in my Powershell script.

public class MyCsharpClass<TKey, TValue> : ISomeBaseClass<TKey, TValue>
{
    public MyCsharpClass(string path, ISomeBaseTranslator<TKey, TValue> translator)
    {
        ...
    }
}
...
...
public class MyByteTranslatorCSharpClass: ISomeBaseTranslator<byte[], byte[]>
{
    ...
}

I want to create instance of MyCsharpClass in Powershell script as follows:

$MyType = [MyCsharpClass[byte[],byte[]]]::new($Path, [MyByteTranslatorCSharpClass]::new())

But the above line fails with below error. I can just enter type name in PS ISE command window and get the same error.

PS C:\> [MyCsharpClass[byte[],byte[]]]
At line:1 char:30
+ [MyCsharpClass[byte[],byte[]]]
+                                                                     ~
Unexpected token ']' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

Below line works fine though showing me the type info of my class when I just use byte type for TKey:

PS C:\> [MyCsharpClass[byte,byte[]]]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MyCsharpClass                           System.Object

It seems the first closing bracket ']' for my Key type of byte[] confuses Powershell that type definition is being closed and so it raises error when it observes Unexpected token ']' in the end of expression.

I also tried to replace byte[] type with System.Collections.Generic.List type which works fine now for declaring a type.

PS C:\> MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MyCsharpClass                           System.Object

However the constructor invocation fails this time while passing instance of MyByteTranslatorCSharpClass as second argument in constructor (at the end of below line).

$MyType = [MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]::new($Path, [MyByteTranslatorCSharpClass]::new())

This gives exception of 'System.Management.Automation.MethodException: Cannot convert argument "translator", with value: "MyByteTranslatorCSharpClass", for ".ctor" to type "ISomeBaseTranslator[System.Collections.Generic.List1[System.Byte],System.Collections.Generic.List1[System.Byte]]"

Please let me know in this context, how can I create instance of MyCsharpClass with byte[] type for TKey and TValue generic arguments in Powershell. Please note that I can neither change the DLL side nor do I have its source.

Body:
This appears to be a type name parsing bug.

Fortunately, you can easily work around this by "qualifying" the type parameter literals with an extra pair of square brackets ([]) :

[MyCsharpClass[[byte[]],[byte[]]]]::new(...)

... or by constructing the concrete type directly using reflection:

$myType = [MyCsharpClass`2].MakeGenericType(@([byte[]],[byte[]]))

$myType::new(...)


问:
Python MusicalBeeps Causing Errors
I started using the module MusicalBeeps to try and play music in Python, however, whenever I try making a player play a noise, I get a huge error. My code looks like this right now:

```<code>import musicalbeeps as music

global TempPlayer

def PlayNote(Note, Octive, Accidental, Duration, Volume):
  #Accidental is either # (sharp) or b (flat) or '' (none)
  global TempPlayer
  TempPlayer = music.Player(volume = float(Volume), mute_output = False)
  TempPlayer.play_note("{}{}{}".format(Note, Octive, Accidental), Duration)
  TempPlayer = None

print("Running...")
PlayNote("B", 4, "#", 5, 1)
print("Done!")
</code>```

This is the example they showed on the website, however whenever I try to run it I get this weird error:

```<code>ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5007:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    PlayNote("B", 4, "#", 5, 1)
  File "main.py", line 9, in PlayNote
    TempPlayer.play_note("{}{}{}".format(Note, Octive, Accidental), Duration)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/musicalbeeps/beepsplayer.py", line 138, in play_note
    self.__write_stream(duration)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/musicalbeeps/beepsplayer.py", line 118, in __write_stream
    self._play_obj = sa.play_buffer(audio, 1, 2, self.rate)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/simpleaudio/shiny.py", line 60, in play_buffer
    play_id = _sa._play_buffer(audio_data, num_channels, bytes_per_sample,
_simpleaudio.SimpleaudioError: Error opening PCM device. -- CODE: -2 -- MSG: No such file or directory
</code>```

BTW I'm using repl.it to make this, and I've already downloaded the musicbeeps module into the file.

Please help, I'm just trying to make a simple project

答: Thanks for the links to the installed package - it makes it easier to find a solution.  MusicalBeeps depends on simpleaudio which requires (on linux at least - and as you posted ALSA errors, I'll assume this is Linux) the libasound2-dev development library to be installed.  See https://simpleaudio.readthedocs.io/en/latest/installation.html#linux-dependencies</p>

Title: Python MusicalBeeps Causing Errors

Body:
I started using the module MusicalBeeps to try and play music in Python, however, whenever I try making a player play a noise, I get a huge error. My code looks like this right now:

import musicalbeeps as music

global TempPlayer

def PlayNote(Note, Octive, Accidental, Duration, Volume):
  #Accidental is either # (sharp) or b (flat) or '' (none)
  global TempPlayer
  TempPlayer = music.Player(volume = float(Volume), mute_output = False)
  TempPlayer.play_note("{}{}{}".format(Note, Octive, Accidental), Duration)
  TempPlayer = None

print("Running...")
PlayNote("B", 4, "#", 5, 1)
print("Done!")

This is the example they showed on the website, however whenever I try to run it I get this weird error:

ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5007:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    PlayNote("B", 4, "#", 5, 1)
  File "main.py", line 9, in PlayNote
    TempPlayer.play_note("{}{}{}".format(Note, Octive, Accidental), Duration)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/musicalbeeps/beepsplayer.py", line 138, in play_note
    self.__write_stream(duration)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/musicalbeeps/beepsplayer.py", line 118, in __write_stream
    self._play_obj = sa.play_buffer(audio, 1, 2, self.rate)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/simpleaudio/shiny.py", line 60, in play_buffer
    play_id = _sa._play_buffer(audio_data, num_channels, bytes_per_sample,
_simpleaudio.SimpleaudioError: Error opening PCM device. -- CODE: -2 -- MSG: No such file or directory

BTW I'm using repl.it to make this, and I've already downloaded the musicbeeps module into the file.

Please help, I'm just trying to make a simple project


问:
How to underline a field on a form except text in the cell
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

```<code>First Name: ________
Last Name: ________
Street Address: ________
</code>```

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>This is a test.</p>
  <table>
    <tbody>
      <tr>
        <td>Word: __________________</td>
      </tr>
      <tr>
        <td>Word word: ______________</td>
      </tr>
      <tr>
        <td>Word word word: _________</td>
      </tr>
      <tr>
        <td>Word word word word: ____</td>
      </tr>
    </tbody>
  </table>
  <p>End of test.</p>
</div></code>```

答:
You can try this code

  First Name:

```

Body:
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

First Name: ________
Last Name: ________
Street Address: ________

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}

This is a test.

        Word: __________________

        Word word: ______________

        Word word word: _________

        Word word word word: ____

End of test.

Body:
You can try this code

<p style="width: 250px; display: table;">
  <span style="display: table-cell; width: 80px;">First Name:</span>
  <span style="display: table-cell; border-bottom: 1px solid black;"></span>
</p>


问:
How do I round a number to a number of significant leading digits in JavaScript?
I would like to round a number to 2 leading digits, using pure JavaScript.
I want to give a rough idea of the number and its size, but I don't want to bother the listener with too many digits.

So 6832 should round to 6800, but 8773278475 should round to 8800000000, not 8773278400.

答:
This function gives me the right results for integers:

```<code>/**
 * @param {integer} num - The number to round
 * @param {integer} leadingDigits - How many significant digits at the start to keep
 * @returns {integer} rounded num
 */
function round(num, leadingDigits) {
  let precision = Math.pow(10, num.toString().length - leadingDigits);
  return Math.round(num / precision) * precision;
}

console.log(round(6832, 2));
console.log(round(8773278475, 2));
console.log(round(8, 2));
</code>```

This returns, as expected:

```<code>6800
8800000000
8
</code>```

But it fails for float, due to the .toString().length hack. If somebody has a better solution, please feel free to post it.

A good solution is short and easy to understand.

Body:
This function gives me the right results for integers:

/**
 * @param {integer} num - The number to round
 * @param {integer} leadingDigits - How many significant digits at the start to keep
 * @returns {integer} rounded num
 */
function round(num, leadingDigits) {
  let precision = Math.pow(10, num.toString().length - leadingDigits);
  return Math.round(num / precision) * precision;
}

console.log(round(6832, 2));
console.log(round(8773278475, 2));
console.log(round(8, 2));

This returns, as expected:

6800
8800000000
8

But it fails for float, due to the .toString().length hack. If somebody has a better solution, please feel free to post it.

A good solution is short and easy to understand.


问:
WPF window properties only visible at runtime
I'm a XAML-beginner and also learning it by myself.
So in the App.xaml I have the following Styles:

```<code><Application.Resources>
        <Style x:Key="Colors" TargetType="{x:Type Control}">
            <Setter Property="Background" Value="#FF404040"/>
            <Setter Property="Foreground" Value="#FF25CBDA"/>
            <Setter Property="BorderBrush" Value="#FF25CBDA"/>
        </Style>

        <Style x:Key="BaseWindowStyle" TargetType="Window" BasedOn="{StaticResource Colors}">
            <Setter Property="Title" Value="MainWindow"/>
            <Setter Property="WindowState" Value="Normal"/>
            <Setter Property="Icon" Value="Icon.ico"/>
        </Style>

        <Style x:Key="MainWindowStyle" TargetType="{x:Type Window}" BasedOn="{StaticResource BaseWindowStyle}">
            <Setter Property="ResizeMode" Value="CanResize"/>
            <Setter Property="ShowInTaskbar" Value="True"/>
        </Style>
</Application.Resources>
</code>```

That's how I use the Style in the MainWindow.xaml:

```<code>Style="{DynamicResource MainWindowStyle}"
</code>```

My problem is that the properties, like the background, are only visible at runtime. It's probably obvious but I really don't get it.

答:
Welcome, DeJoon! It's unclear exactly what it is that you don't get.  What do you want to happen, or expect to happen?  Are you saying that you don't know what the background color looks like until you run the app, but you want to see it at design time? You should be able to see the color and the properties via the XAML Designer.

I took your code, commented out one line related to "icon.ico" because I don't have that file, and I was able to see your background color as a dark grey color from the designer.  See here:

Here is my MainWindow.xaml.cs:

```<code><Window x:Class="StyleTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StyleTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Style="{DynamicResource MainWindowStyle}">
    <Grid>

    </Grid>
</Window>
</code>```

Body:
I'm a XAML-beginner and also learning it by myself.
So in the App.xaml I have the following Styles:

<Application.Resources>

</Application.Resources>

That's how I use the Style in the MainWindow.xaml:

Style="{DynamicResource MainWindowStyle}"

My problem is that the properties, like the background, are only visible at runtime. It's probably obvious but I really don't get it.

Body:
Welcome, DeJoon! It's unclear exactly what it is that you don't get.  What do you want to happen, or expect to happen?  Are you saying that you don't know what the background color looks like until you run the app, but you want to see it at design time? You should be able to see the color and the properties via the XAML Designer.

I took your code, commented out one line related to "icon.ico" because I don't have that file, and I was able to see your background color as a dark grey color from the designer.  See here:

Here is my MainWindow.xaml.cs:

<Window x:Class="StyleTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StyleTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Style="{DynamicResource MainWindowStyle}">
    <Grid>

    </Grid>
</Window>


问:
SQL script to make another SQL script
I would need a SQL script that reads the data in the table based on an ID and then generates another SQL script. The generated script should be able to update and insert data previously selected by ID.

I know the update and insert commands, but I don’t know exactly how to create a script that builds a script from existing data. Can anyone help?

答:
Not sure what you trying to accomplish here.

Here I use a query to find what id I going to update.
update table set updated=now() where id in (select id from table where updated is null);

Here I create a query that I run (command differs depending on sql engine, you have to google yours)
SET SQL = select 'select * from table where id = ' + select max(id) from table where updated is null; -- Will generate something like 'select * from table where id = 2'
SELECT SQL; -- Print the query that will rune
exec(SQL); -- Run the query you generated

Title: SQL script to make another SQL script


问:
Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings what to do?

So my problem is I am getting this weird error message from the title of my question and I really don´t know why. I have took the oAuth url that firebase authentification provided me and pasted into the twitter app developers site in the callback url field. So why is it telling me that I need to register it ?

Posted my code here if it is for some reason my code that has to do with it:

```<code>twitterRealButton.setCallback(new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> result) {
                        Toast.makeText(LoginActivity.this, "Signed in to twitter successful", Toast.LENGTH_LONG).show();
                        handleTwitterSignIn(result.data);

                    }

                    @Override
                    public void failure(TwitterException exception) {
                        Toast.makeText(LoginActivity.this, "Login failed. No internet or No Twitter app found on your phone", Toast.LENGTH_LONG).show();

                    }
                });
                twitterRealButton.performClick();
}

 private void handleTwitterSignIn(TwitterSession session){
        AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token,
                session.getAuthToken().secret);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Toast.makeText(LoginActivity.this, "Signed in firebase twitter successful", Toast.LENGTH_LONG).show();
                        if (!task.isSuccessful()){
                            Toast.makeText(LoginActivity.this, "Auth firebase twitter failed", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }
</code>```

答: Ok this is really weird and I don´t know why this has worked but for some reason if you add: twittersdk:// as your callback url it works I guess ?</p>

Body:
So my problem is I am getting this weird error message from the title of my question and I really don´t know why. I have took the oAuth url that firebase authentification provided me and pasted into the twitter app developers site in the callback url field. So why is it telling me that I need to register it ?

Posted my code here if it is for some reason my code that has to do with it:

twitterRealButton.setCallback(new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> result) {
                        Toast.makeText(LoginActivity.this, "Signed in to twitter successful", Toast.LENGTH_LONG).show();
                        handleTwitterSignIn(result.data);

                    }

                    @Override
                    public void failure(TwitterException exception) {
                        Toast.makeText(LoginActivity.this, "Login failed. No internet or No Twitter app found on your phone", Toast.LENGTH_LONG).show();

                    }
                });
                twitterRealButton.performClick();
}

 private void handleTwitterSignIn(TwitterSession session){
        AuthCredential credential = TwitterAuthProvider.getCredential(session.getAuthToken().token,
                session.getAuthToken().secret);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Toast.makeText(LoginActivity.this, "Signed in firebase twitter successful", Toast.LENGTH_LONG).show();
                        if (!task.isSuccessful()){
                            Toast.makeText(LoginActivity.this, "Auth firebase twitter failed", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }


问:
Django Rest Framework JWT Unit Test
I am using DRF with the JWT package for authentication. Now, I'm trying to write a unit test that authenticates itself with a JWT token. No matter how I try it, I can't get the test API client to authenticate itself via JWT. If I do the same with an API client (in my case, Postman), everything works.

This is the test case:

```<code>from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework_jwt.settings import api_settings

from backend.factories import member_factory

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class MemberTests(APITestCase):
    def test_get_member(self):
        member = member_factory()

        payload = jwt_payload_handler(member.user)
        token = jwt_encode_handler(payload)

        self.client.credentials(Authorization='JWT {0}'.format(token))
        response = self.client.get(reverse('member-detail', kwargs={'pk': member.pk}))
        assert response.status_code == 200
</code>```

But I always get a 401 Authentication credentials were not provided.

In response.request I see the token is there, it's just not being applied I guess.

If I rewrite the test to use rest_framework.test.RequestsClient and actually send it to the live_server URL, it works.

Any help on this?

P.S.: I am aware of force_authenticate() and login, but I would like my unit tests to access the API the same as the API client will in production.

答: Postman interacts with your actual database. Django uses separate database for it's test case running. Therefore a new user record needs to be created again inside your test definition before authentication testing. Hope this helps.</p>

Title: Django Rest Framework JWT Unit Test

Body:
I am using DRF with the JWT package for authentication. Now, I'm trying to write a unit test that authenticates itself with a JWT token. No matter how I try it, I can't get the test API client to authenticate itself via JWT. If I do the same with an API client (in my case, Postman), everything works.

This is the test case:

from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework_jwt.settings import api_settings

from backend.factories import member_factory

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class MemberTests(APITestCase):
    def test_get_member(self):
        member = member_factory()

        payload = jwt_payload_handler(member.user)
        token = jwt_encode_handler(payload)

        self.client.credentials(Authorization='JWT {0}'.format(token))
        response = self.client.get(reverse('member-detail', kwargs={'pk': member.pk}))
        assert response.status_code == 200

But I always get a 401 Authentication credentials were not provided.

In response.request I see the token is there, it's just not being applied I guess.

If I rewrite the test to use rest_framework.test.RequestsClient and actually send it to the live_server URL, it works.

Any help on this?

P.S.: I am aware of force_authenticate() and login, but I would like my unit tests to access the API the same as the API client will in production.


问:
How to pass a hidden value in a form in Spring MVC 3.0?
How to pass a hidden value in a form in Spring MVC 3.0

I am not able to assign a value to a hidden field using
<form:hidden path="test" />. How can I set the value of the test field and access it on the server side.

thanks

答:
Often people wrongly pass some values as hidden to form, because they cannot otherwise set those fields in update to previous values. E.g If I don't pass some values while updating to the form, those fields become null. However this is wrong way to update values. There is

@SessionAttributes("Rules")

to do that. After you update, you can set the session to complete using (SessionStatus status)  parameter and status.setComplete() after the update is done. If you want to get some values that is not in model you can always use request.getParameter("yourinputname"); You can use

input type="hidden"

to set some values if you want to use in some parts like javascript (if using

${somevalueIdontwanttoshow}

does not work).

And if you really want to access the hidden filed try using

request.getParameter("yourfiedl")

before looking at binding errors.

ContentLicense: CC BY-SA 2.5


问:
argparse works when calling script but not when incorporated to new script
Here is my basic issue:

I have the following:
file name: parseFastq.py
execution: via command line
code to run it: python3 parseFastq.py --fastq /Users/remaining_dir/test1.fastq

This code works!!!

However, when I copy the components of parseFastq.py issues arise.

Below is the code:

Class is first defined...this part works and runs fine on my new script.

```<code>import argparse
import gzip
#Example use is
# python parseFastq.py --fastq /Users/remaining_dir/test1.fastq

################################################
# You can use this code and put it in your own script
class ParseFastQ(object):
    """Returns a read-by-read fastQ parser analogous to file.readline()"""
    def __init__(self,filePath,headerSymbols=['@','+']):
        """Returns a read-by-read fastQ parser analogous to file.readline().
        Exmpl: parser.__next__()
        -OR-
        Its an iterator so you can do:
        for rec in parser:
            ... do something with rec ...

        rec is tuple: (seqHeader,seqStr,qualHeader,qualStr)
        """
        if filePath.endswith('.gz'):
            self._file = gzip.open(filePath)
        else:
            self._file = open(filePath, 'rU')
        self._currentLineNumber = 0
        self._hdSyms = headerSymbols

    def __iter__(self):
        return self

    def __next__(self):
        """Reads in next element, parses, and does minimal verification.
        Returns: tuple: (seqHeader,seqStr,qualHeader,qualStr)"""
        # ++++ Get Next Four Lines ++++
        elemList = []
        for i in range(4):
            line = self._file.readline()
            self._currentLineNumber += 1 ## increment file position
            if line:
                elemList.append(line.strip('\n'))
            else:
                elemList.append(None)

        # ++++ Check Lines For Expected Form ++++
        trues = [bool(x) for x in elemList].count(True)
        nones = elemList.count(None)
        # -- Check for acceptable end of file --
        if nones == 4:
            raise StopIteration
        # -- Make sure we got 4 full lines of data --
        assert trues == 4,\
               "** ERROR: It looks like I encountered a premature EOF or empty line.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._currentLineNumber)
        # -- Make sure we are in the correct "register" --
        assert elemList[0].startswith(self._hdSyms[0]),\
               "** ERROR: The 1st line in fastq element does not start with '%s'.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._hdSyms[0],self._currentLineNumber)
        assert elemList[2].startswith(self._hdSyms[1]),\
               "** ERROR: The 3rd line in fastq element does not start with '%s'.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._hdSyms[1],self._currentLineNumber)
        # -- Make sure the seq line and qual line have equal lengths --
        assert len(elemList[1]) == len(elemList[3]), "** ERROR: The length of Sequence data and Quality data of the last record aren't equal.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._currentLineNumber)

        # ++++ Return fatsQ data as tuple ++++
        return tuple(elemList)
##########################################################################
</code>```

This is the code that will not work when calling it in the same script; it has to do with putting the pieces in  :

```<code>if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process fasq files and seperaate into 4 categories')
parser.add_argument("-f",  "--fastq", required=True, help="Place fastq inside here")
args = parser.parse_args()

fastqfile = ParseFastQ(args.fastq)
</code>```

I tried the following and I cannot get fastqfile which should contain a tuple with the following:  (seqHeader,seqStr,qualHeader,qualStr)

Attemp:

```<code>parser.add_argument("-/Users/remaining_dir/test1.fastq",  "--fastq", required=True, help="Place fastq inside here")
</code>```

Error:

```<code>argument -/Users/remaining_dir/test1.fastq/--fastq: conflicting option string: --fastq
</code>```

Attemp:

```<code>parser.add_argument("-/Users/remaining_dir/test1.fastq",  "-@", required=True, help="Place fastq inside here")
</code>```

Out[332]:

```<code>_StoreAction(option_strings=['-/Users/remaining_dir/test1.fastq', '-@'], dest='/Users/remaining_dir/test1.fastq', nargs=None, const=None, default=None, type=None, choices=None, help='Place fastq inside here', metavar=None)
</code>```

next line:

Error:

```<code>usage:  [-h] -/Users/remaining_dir/test1.fastq
        /USERS/REMAINING_DIR/TEST1.FASTQ
: error: the following arguments are required: -/Users/remaining_dir/test1.fastq/-@
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

 when %tb selected the following info was give:
 File "/Users/brownbear/opt/anaconda3/lib/python3.7/argparse.py", line 2508, in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

  File "/Users/brownbear/opt/anaconda3/lib/python3.7/argparse.py", line 2495, in exit
    _sys.exit(status)
</code>```

if helpful, I am including some sample fastq data

```<code>@seq13534-419
GCAGTAGCGGTCATAAGTGGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGAGGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGTGTCGTGAGGTGACGTCCGTCACTGGACGAA
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIFFFFDFFDFFDDFDFDFFFFDDFFDDFDDFF
@seq86249-867
GGATTAGCGGTCATAAGTCGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGAGGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGAGGTCAGTATAACCTCTCAAAGCTTTATCTACGGATGGATCCGCGC
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDDFDDDDDDFFDFDDFDDDFDFFDDFFFFFFFFFDDFDFFDDFDDF
@seq46647-928
GACCTAGCGGTCATAAGTGGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGACGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGTAAGTAAATGCCACGGACTCGTCACGTG
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDDDFDFDFFFFFDFFDFDFDDDDDFDFF
</code>```

Any help would be appreciated on why this works when I run the script but now when I try and incorporate within a script

答:
the solution was two main parts

I was trying to run the argparse via an IDE (Spyder), and running only selected code as opposed to the whole scripts.

For those who are new to python and are utilizing argparse for the first time... this tool only works when calling from the command line.

Therefore, once you've created your args table

you will run as belowL

from command line:

```<code>python3 parseFastq.py --fastq test1.fastq
</code>```

To break this down further from the initial set up, you are basically labeling your test1.fastq file, to the tag --fastq... this is critical, if you get error that it is required in a particular format is that you have to add them in pairs... in this particular example, you can also label with the short hand of "-f". Therefore, it could also be run as...

from command line:

```<code>python3 parseFastq.py -f test1.fastq
</code>```

as long as you're py script is run in the same directory as your called files, you do not need the full extension.

Body:
Here is my basic issue:

I have the following:
file name: parseFastq.py
execution: via command line
code to run it: python3 parseFastq.py --fastq /Users/remaining_dir/test1.fastq

This code works!!!

However, when I copy the components of parseFastq.py issues arise.

Below is the code:

Class is first defined...this part works and runs fine on my new script.

import argparse
import gzip
#Example use is
# python parseFastq.py --fastq /Users/remaining_dir/test1.fastq

################################################
# You can use this code and put it in your own script
class ParseFastQ(object):
    """Returns a read-by-read fastQ parser analogous to file.readline()"""
    def __init__(self,filePath,headerSymbols=['@','+']):
        """Returns a read-by-read fastQ parser analogous to file.readline().
        Exmpl: parser.__next__()
        -OR-
        Its an iterator so you can do:
        for rec in parser:
            ... do something with rec ...

        rec is tuple: (seqHeader,seqStr,qualHeader,qualStr)
        """
        if filePath.endswith('.gz'):
            self._file = gzip.open(filePath)
        else:
            self._file = open(filePath, 'rU')
        self._currentLineNumber = 0
        self._hdSyms = headerSymbols

    def __iter__(self):
        return self

    def __next__(self):
        """Reads in next element, parses, and does minimal verification.
        Returns: tuple: (seqHeader,seqStr,qualHeader,qualStr)"""
        # ++++ Get Next Four Lines ++++
        elemList = []
        for i in range(4):
            line = self._file.readline()
            self._currentLineNumber += 1 ## increment file position
            if line:
                elemList.append(line.strip('\n'))
            else:
                elemList.append(None)

        # ++++ Check Lines For Expected Form ++++
        trues = [bool(x) for x in elemList].count(True)
        nones = elemList.count(None)
        # -- Check for acceptable end of file --
        if nones == 4:
            raise StopIteration
        # -- Make sure we got 4 full lines of data --
        assert trues == 4,\
               "** ERROR: It looks like I encountered a premature EOF or empty line.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._currentLineNumber)
        # -- Make sure we are in the correct "register" --
        assert elemList[0].startswith(self._hdSyms[0]),\
               "** ERROR: The 1st line in fastq element does not start with '%s'.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._hdSyms[0],self._currentLineNumber)
        assert elemList[2].startswith(self._hdSyms[1]),\
               "** ERROR: The 3rd line in fastq element does not start with '%s'.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._hdSyms[1],self._currentLineNumber)
        # -- Make sure the seq line and qual line have equal lengths --
        assert len(elemList[1]) == len(elemList[3]), "** ERROR: The length of Sequence data and Quality data of the last record aren't equal.\n\
               Please check FastQ file near line number %s (plus or minus ~4 lines) and try again**" % (self._currentLineNumber)

        # ++++ Return fatsQ data as tuple ++++
        return tuple(elemList)
##########################################################################

This is the code that will not work when calling it in the same script; it has to do with putting the pieces in  :

if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process fasq files and seperaate into 4 categories')
parser.add_argument("-f",  "--fastq", required=True, help="Place fastq inside here")
args = parser.parse_args()

fastqfile = ParseFastQ(args.fastq)

I tried the following and I cannot get fastqfile which should contain a tuple with the following:  (seqHeader,seqStr,qualHeader,qualStr)

Attemp:

parser.add_argument("-/Users/remaining_dir/test1.fastq",  "--fastq", required=True, help="Place fastq inside here")

Error:

argument -/Users/remaining_dir/test1.fastq/--fastq: conflicting option string: --fastq

Attemp:

parser.add_argument("-/Users/remaining_dir/test1.fastq",  "-@", required=True, help="Place fastq inside here")

Out[332]:

_StoreAction(option_strings=['-/Users/remaining_dir/test1.fastq', '-@'], dest='/Users/remaining_dir/test1.fastq', nargs=None, const=None, default=None, type=None, choices=None, help='Place fastq inside here', metavar=None)

next line:

Error:

usage:  [-h] -/Users/remaining_dir/test1.fastq
        /USERS/REMAINING_DIR/TEST1.FASTQ
: error: the following arguments are required: -/Users/remaining_dir/test1.fastq/-@
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

 when %tb selected the following info was give:
 File "/Users/brownbear/opt/anaconda3/lib/python3.7/argparse.py", line 2508, in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

  File "/Users/brownbear/opt/anaconda3/lib/python3.7/argparse.py", line 2495, in exit
    _sys.exit(status)

if helpful, I am including some sample fastq data

@seq13534-419
GCAGTAGCGGTCATAAGTGGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGAGGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGTGTCGTGAGGTGACGTCCGTCACTGGACGAA
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIFFFFDFFDFFDDFDFDFFFFDDFFDDFDDFF
@seq86249-867
GGATTAGCGGTCATAAGTCGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGAGGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGAGGTCAGTATAACCTCTCAAAGCTTTATCTACGGATGGATCCGCGC
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDDFDDDDDDFFDFDDFDDDFDFFDDFFFFFFFFFDDFDFFDDFDDF
@seq46647-928
GACCTAGCGGTCATAAGTGGTACATTACGAGATTCGGAGTACCATAGATTCGCATGAATCCCTGTGGATACGAGAGTGTGAGATATATGTACGCCAATCCAGTGTGATACCCATGAGATTTAGGACCGATGATGGTTGACGACCAAGGATTGACCCGATGGATGCAGATTTGACCCCAGATAGAATAAATGCGATGAGATGATTTGGCCGATAGATAGATAGTAAGTAAATGCCACGGACTCGTCACGTG
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIDDDFDFDFFFFFDFFDFDFDDDDDFDFF

Any help would be appreciated on why this works when I run the script but now when I try and incorporate within a script

Body:
the solution was two main parts

I was trying to run the argparse via an IDE (Spyder), and running only selected code as opposed to the whole scripts.

For those who are new to python and are utilizing argparse for the first time... this tool only works when calling from the command line.

Therefore, once you've created your args table

you will run as belowL

from command line:

python3 parseFastq.py --fastq test1.fastq

To break this down further from the initial set up, you are basically labeling your test1.fastq file, to the tag --fastq... this is critical, if you get error that it is required in a particular format is that you have to add them in pairs... in this particular example, you can also label with the short hand of "-f". Therefore, it could also be run as...

from command line:

python3 parseFastq.py -f test1.fastq

as long as you're py script is run in the same directory as your called files, you do not need the full extension.


问:
How can I delete selected documents in firebase Firestore

I have a lot of files in my Firestore that I want to delete through the firebase website but I want to be able to select and delete them instead of deleting them one by one

答:
It could be a hard task to delete many documents on your Firestore instance manually. Specially if you have hundreds or thousands of them. I think the best option would be doing it programmatically through an Application or a Cloud function.

On this documentation you can learn how to implement the delete() method on many popular languages to delete documents, fields, and collections, and on this document I found a simple way of creating a Cloud Function while learning how to delete collections.

As a summary there is no easy way to delete many documents,field or collections using the user interface. The best way is to implement code to do it.


问:
Pass parameter at the end of a dot string
I'm trying to make a function to get one field from a firebase database

```<code>function getFromDatabase(param1) {
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log(user)
            db.collection("users").doc(user.uid).get().then(function (doc) {
                if (doc.exists) {
                    console.log(doc.data().name) //Passes expected value
                    console.log(doc.data().param1)
                } else {
                    console.warn("No such document!");
                }
            })
        }
    })
}
</code>```

when I call

getFromDatabase(name)

I would like it to return

console.log(doc.data().name)

but it doesn't interpret it as a parameter

I've tried a whole bunch of different variations of console.log(doc.data().param1), but I can't figure this out for the life of me, and it might be because I don't know the correct term to search for, as everything I know is from internet searches.

If anyone could provide insight on what im doing wrong, I would greatly appreciate it.

答:
Thanks @PatrickEvans !

getFromDatabase('name')
with
console.log(doc.data()[param1]);

Gave the expected result.

Body:
I'm trying to make a function to get one field from a firebase database

function getFromDatabase(param1) {
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log(user)
            db.collection("users").doc(user.uid).get().then(function (doc) {
                if (doc.exists) {
                    console.log(doc.data().name) //Passes expected value
                    console.log(doc.data().param1)
                } else {
                    console.warn("No such document!");
                }
            })
        }
    })
}

when I call

getFromDatabase(name)

I would like it to return

console.log(doc.data().name)

but it doesn't interpret it as a parameter

I've tried a whole bunch of different variations of console.log(doc.data().param1), but I can't figure this out for the life of me, and it might be because I don't know the correct term to search for, as everything I know is from internet searches.

If anyone could provide insight on what im doing wrong, I would greatly appreciate it.


问:
Using "~ call" in R with dynamic variables
I'm currently working on regression and classification with R.

Therefore I'm using a formula similar to X ~ Y in order to make predictions about X.
I am now trying to use a function inside a for-loop to make multiple predictions about different values on the X side of the tilde and constant values on the Y side. Something like this:
X1 ~ Y
X2 ~ Y
X3 ~ Y

with X1, X2, X3 and Y all being columns of data (data$X1 <- a, data$X2 <- b, data$X3 <- c, data$Y) if this is somehow important

so how can I dynamically select a variable inside the ~-Expression? I have tried something like this but it's not working:

```<code># referring to "iris" data set with columns (Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)

getFormula <- function(variable){
  variable ~ Sepal.Length + Sepal.Width + Species
}

petal.length.formula <- getFormula(Petal.Length)
petal.width.formula <- getFormula(Petal.Width)
</code>```

i get this:

```<code>petal.length.formula: variable ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: variable ~ Sepal.Lenght + Sepal.Width + Species
</code>```

but i want to achieve this:

```<code>petal.length.formula: Petal.Length ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: Petal.Width ~ Sepal.Lenght + Sepal.Width + Species
</code>```

Since I have over 40 variables on the Y-Side and 10 variables on the X-Side, it would be really messy to type every single formula by hand.
Can anybody help me with this issue?

I could not find a similar question since I have a hard time to figure out the keywords I have to use to find something about this.

If possible, I would prefer not to use any additional library since I'm rather new to R and want to first figure out the basics mechanics of R.

Since english is not my first language, I hope you can understand my question and I am of course happy to explain further if needed. Thank you in advance for your time!

答:
You can try this, you need to pass a character to variable. It's much easier that way and if you have 10 variables on X side, you can easily iterate through them:

```<code>getFormula <- function(variable){
  as.formula(paste(variable,"~ Sepal.Length + Sepal.Width + Species"))
}

petal.length.formula <- getFormula("Petal.Length")
petal.width.formula <- getFormula("Petal.Width")

lm(petal.length.formula,data=iris)
Call:
lm(formula = petal.length.formula, data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor
         -1.63430            0.64631           -0.04058            2.17023
 Speciesvirginica
          3.04911
</code>```

You can also try reformulate, as suggested by @BenBolker and @MrFlick:

```<code>getFormula <- function(variable){
  reformulate(c("Sepal.Length","Sepal.Width","Species"),
response = variable, intercept = TRUE)
}

lm(getFormula("Petal.Length"),data=iris)

Call:
lm(formula = getFormula("Petal.Length"), data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor
         -1.63430            0.64631           -0.04058            2.17023
 Speciesvirginica
          3.04911
</code>```

Body:
I'm currently working on regression and classification with R.

Therefore I'm using a formula similar to X ~ Y in order to make predictions about X.
I am now trying to use a function inside a for-loop to make multiple predictions about different values on the X side of the tilde and constant values on the Y side. Something like this:
X1 ~ Y
X2 ~ Y
X3 ~ Y

with X1, X2, X3 and Y all being columns of data (data$X1 <- a, data$X2 <- b, data$X3 <- c, data$Y) if this is somehow important

so how can I dynamically select a variable inside the ~-Expression? I have tried something like this but it's not working:

# referring to "iris" data set with columns (Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)

getFormula <- function(variable){
  variable ~ Sepal.Length + Sepal.Width + Species
}

petal.length.formula <- getFormula(Petal.Length)
petal.width.formula <- getFormula(Petal.Width)

i get this:

petal.length.formula: variable ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: variable ~ Sepal.Lenght + Sepal.Width + Species

but i want to achieve this:

petal.length.formula: Petal.Length ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: Petal.Width ~ Sepal.Lenght + Sepal.Width + Species

Since I have over 40 variables on the Y-Side and 10 variables on the X-Side, it would be really messy to type every single formula by hand.
Can anybody help me with this issue?

I could not find a similar question since I have a hard time to figure out the keywords I have to use to find something about this.

If possible, I would prefer not to use any additional library since I'm rather new to R and want to first figure out the basics mechanics of R.

Since english is not my first language, I hope you can understand my question and I am of course happy to explain further if needed. Thank you in advance for your time!

Body:
You can try this, you need to pass a character to variable. It's much easier that way and if you have 10 variables on X side, you can easily iterate through them:

getFormula <- function(variable){
  as.formula(paste(variable,"~ Sepal.Length + Sepal.Width + Species"))
}

petal.length.formula <- getFormula("Petal.Length")
petal.width.formula <- getFormula("Petal.Width")

lm(petal.length.formula,data=iris)
Call:
lm(formula = petal.length.formula, data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor
         -1.63430            0.64631           -0.04058            2.17023
 Speciesvirginica
          3.04911

You can also try reformulate, as suggested by @BenBolker and @MrFlick:

getFormula <- function(variable){
  reformulate(c("Sepal.Length","Sepal.Width","Species"),
response = variable, intercept = TRUE)
}

lm(getFormula("Petal.Length"),data=iris)

Call:
lm(formula = getFormula("Petal.Length"), data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor
         -1.63430            0.64631           -0.04058            2.17023
 Speciesvirginica
          3.04911


问:
Google Drive API with Python from server(Backend) without browser autentication
I'd like to save the files of my Saas Appication to my Google Drive Account, all the examples I've seen was with oauth2 autentication and needs the end user autenticate openning the browser, I need to upload files from my server without any user interation, sending files direct to my account!

I have try many tutorials I found on internet with no success, mainly the oficial

Google Drive API with Python

How can I autenticate programatically from my server and upload files and use API features such as share folders and others?

I'm using Python, the lib PyDrive uses the same aproach to autenticate

答:
I know it's quite late for answer but this worked for me:

Use the same API you were using, this time in your computer, it will generate a Storage.json which  using it along with your scripts will solve the issue (specially in read-ony platforms like heroku)


问:
Haskell, consume non-blocking getLine
I'm looking for a method to read from stdin and after a while, if there is no input given, I want to skip that getLine.

I have this code which skips the first getLine after 3 seconds, but when it gets to second getLine I have to enter my input twice. Any advice?

```<code>main :: IO ()
main = do
  putStrLn "x:"
  x <- timeout 3000000 getLine
  putStrLn "y:"
  y <- getLine
  putStrLn y
</code>```

答:
Not a complete answer, but...

I can confirm the behavior on Windows.  The prompt "x:" appears, then after 3 seconds, the prompt "y:" appears, but the first line of input is ignored.  If the program is compiled with -threaded, the "y:" prompt never appears until the first line is entered.  (The timeout is still "processed" in the sense that the value of x will be Nothing if the first line is entered after the timeout, but either way, only the second line of input is processed for y <- getLine.)

I think the underlying issue may be the problems with interrupting I/O via asynchronous exceptions under Windows, as documented in issue #7353.  The bug report there makes it sound like only the threaded runtime is affected, but I think it's an issue whether the threaded or non-threaded runtime is used.  The implementation of timeout has a special code path for handling the Windows threaded runtime, which may explain the differences in behavior, even though in both cases the runtime is failing to cancel the first getLine.

There is ongoing work on a native Windows I/O Manager that is supposed to address issue #7353 among many other problems with I/O under Windows.  I don't have a Windows build machine that I can try to build/test it on, though, to see if it addresses this specific problem.

Title: Haskell, consume non-blocking getLine

Body:
I'm looking for a method to read from stdin and after a while, if there is no input given, I want to skip that getLine.

I have this code which skips the first getLine after 3 seconds, but when it gets to second getLine I have to enter my input twice. Any advice?

main :: IO ()
main = do
  putStrLn "x:"
  x <- timeout 3000000 getLine
  putStrLn "y:"
  y <- getLine
  putStrLn y


问:
Access Contents of  with Javascript
```<code><noscript><div id="example">I want to get this innerHTML</div></noscript>

<script type="text/javascript"> alert($('example').innerHTML);</script>
</code>```

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

答:
If scripting is enabled, the noscript element is defined as containing only text - though it must be parsable text, with some restrictions on content. With that in mind, you should be able to extract the text, parse it, and then find your desired element. A rudimentary example of this follows:

```<code>var nos = document.getElementsByTagName("noscript")[0];
// in some browsers, contents of noscript hang around in one form or another
var nosHtml = nos.textContent||nos.innerHTML;

if ( nosHtml )
{
  var temp = document.createElement("div");
  temp.innerHTML = nosHtml;

  // lazy man's query library: add it, find it, remove it
  document.body.appendChild(temp);
  var ex = document.getElementById("example");
  document.body.removeChild(temp);

  alert(ex.innerHTML);
}
</code>```

Note that when I originally wrote this answer, the above failed in Google Chrome; access to noscript content appears to be somewhat better-supported these days, but it still strikes me as an edge-case that is perhaps somewhat more likely than other elements to exhibit bugs - I would avoid it if you've other options.

OwnerDisplayName: macinjosh

Title: Access Contents of <noscript> with Javascript

Body:
I want to get this innerHTML

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

Body:
If scripting is enabled, the noscript element is defined as containing only text - though it must be parsable text, with some restrictions on content. With that in mind, you should be able to extract the text, parse it, and then find your desired element. A rudimentary example of this follows:

var nos = document.getElementsByTagName("noscript")[0];
// in some browsers, contents of noscript hang around in one form or another
var nosHtml = nos.textContent||nos.innerHTML;

if ( nosHtml )
{
  var temp = document.createElement("div");
  temp.innerHTML = nosHtml;

  // lazy man's query library: add it, find it, remove it
  document.body.appendChild(temp);
  var ex = document.getElementById("example");
  document.body.removeChild(temp);

  alert(ex.innerHTML);
}

Note that when I originally wrote this answer, the above failed in Google Chrome; access to noscript content appears to be somewhat better-supported these days, but it still strikes me as an edge-case that is perhaps somewhat more likely than other elements to exhibit bugs - I would avoid it if you've other options.


问:
JavaScript manipulating DOM (onclick event)
I have this code that is supposed to add a div that is a red square every time I click the button. It happens that it adds the div I want 1 click yes and 1 click no. here's the code:

var btnElement = document.querySelector('button');
console.log(btnElement);
btnElement.onclick = function() {
  var index = 0;
  var squareElementCreator = document.createElement('div');
  squareElementCreator.setAttribute('class', 'box');

  var containElement = document.querySelector('#app');
  containElement.appendChild(squareElementCreator);

  var squareElement = document.querySelectorAll('.box');
  console.log(squareElement[index]);
  squareElement[index].style.width = "100px";
  squareElement[index].style.height = "100px";
  squareElement[index].style.backgroundColor = '#f00';
  squareElement[index].style.margin = '10px';
  //console.log(squareElement);

  var container = document.querySelector('#app');
  container.appendChild(squareElement[index]);
  index++;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <input type="text" name="nome" id="nome" />
  <button class="botao">Adicionar</button>
</div></code>```

答:
You could benefit from HTML Templates and Slots

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots

var btnElement = document.querySelector('button');

btnElement.onclick = function() {
  const template = document.getElementById('my-red-square').content.cloneNode(true);
  document.querySelector('#app').appendChild(template);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <input type="text" name="nome" id="nome" />
  <button class="botao">Adicionar</button>
</div>

<template id='my-red-square'>
<style>
    .box {
      width: 100px;
      height:100px;
      background-color: #00f;
      margin:10px;
    }
  </style>
<div class="box">
</div>
</template></code>```

Body:
I have this code that is supposed to add a div that is a red square every time I click the button. It happens that it adds the div I want 1 click yes and 1 click no. here's the code:

var btnElement = document.querySelector('button');
console.log(btnElement);
btnElement.onclick = function() {
  var index = 0;
  var squareElementCreator = document.createElement('div');
  squareElementCreator.setAttribute('class', 'box');

  var containElement = document.querySelector('#app');
  containElement.appendChild(squareElementCreator);

  var squareElement = document.querySelectorAll('.box');
  console.log(squareElement[index]);
  squareElement[index].style.width = "100px";
  squareElement[index].style.height = "100px";
  squareElement[index].style.backgroundColor = '#f00';
  squareElement[index].style.margin = '10px';
  //console.log(squareElement);

  var container = document.querySelector('#app');
  container.appendChild(squareElement[index]);
  index++;
}

  <input type="text" name="nome" id="nome" />
  <button class="botao">Adicionar</button>

Body:
You could benefit from HTML Templates and Slots

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots

var btnElement = document.querySelector('button');

btnElement.onclick = function() {
  const template = document.getElementById('my-red-square').content.cloneNode(true);
  document.querySelector('#app').appendChild(template);
}

<div id="app">
  <input type="text" name="nome" id="nome" />
  <button class="botao">Adicionar</button>
</div>

<template id='my-red-square'>
<style>
    .box {
      width: 100px;
      height:100px;
      background-color: #00f;
      margin:10px;
    }
  </style>
<div class="box">
</div>
</template>


问:
Generating checkbox for if string in model is null inside List<model> inside viewmodel
I have a viewmodel that includes an icollection of models from the db with a string attribute. I am trying to index those models from the viewmodel in a table but instead of writing the string out, I want to generate a checkbox using razor for whether the string is null or not. Is there a simple way to do this that I am not seeing? I keep getting null reference errors or nothing at all.

here is my viewmodel:

```<code>public class CourseViewModel
{
    public int CourseId { get; set; }

    [Display(Name = "Course Name")]
    public string CourseName { get; set; }

    public ICollection<NewPage> CoursePages { get; set; }
}
</code>```

Here is my view:

```<code>@foreach (var item in Model.CoursePages)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PageNumber)
    </td>
    @*<td>
        @if (item.DrillInstructions == null)
        {
            Html.CheckBox("Instructions", false);
        }
        @if (item.DrillInstructions != null)
        {
            Html.CheckBox("Instructions", true);
        }
    </td>*@
    <td>
        @Html.DisplayFor(modelItem => item.DrillInstructions)
    </td>
</code>```

答:
If it is just for display, you could use a glyphicon or font-awesome. Something like

```<code><td>
    <i class='fa @(item.DrillInstructions == null ? "fa-square" : "fa-checksquare")'></i>
</td>
</code>```

Use fa fa-2x for a bigger checkbox.

Body:
I have a viewmodel that includes an icollection of models from the db with a string attribute. I am trying to index those models from the viewmodel in a table but instead of writing the string out, I want to generate a checkbox using razor for whether the string is null or not. Is there a simple way to do this that I am not seeing? I keep getting null reference errors or nothing at all.

here is my viewmodel:

public class CourseViewModel
{
    public int CourseId { get; set; }

    [Display(Name = "Course Name")]
    public string CourseName { get; set; }

    public ICollection<NewPage> CoursePages { get; set; }
}

Here is my view:

@foreach (var item in Model.CoursePages)
{

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.PageNumber)

    @*
        @if (item.DrillInstructions == null)
        {
            Html.CheckBox("Instructions", false);
        }
        @if (item.DrillInstructions != null)
        {
            Html.CheckBox("Instructions", true);
        }
    	*@

        @Html.DisplayFor(modelItem => item.DrillInstructions)

Body:
If it is just for display, you could use a glyphicon or font-awesome. Something like

<td>
    <i class='fa @(item.DrillInstructions == null ? "fa-square" : "fa-checksquare")'></i>
</td>

Use fa fa-2x for a bigger checkbox.