问:
Subsetting a dataframe in R by retaining first occurrences of unique elements from all columns
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))
</code>```

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

答:
A data.table version, following @PaulS's tidyverse approach; Might help speed wise with 1,000,000 rows, etc.

```<code>library(data.table)
setDT(df)

df = cbind(df[,1], df[,-1][, lapply(.SD, \(x) fifelse(duplicated(x),"",x))])
df[rowSums(df[,-1]=="")<5]
</code>```

Output

```<code>   Hits category1 category2 category3 category4 category5
1: Hit1         a         c                             i
2: Hit3         b                   e
3: Hit4                   d         f                   j
</code>```

Body:
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

Body:
A data.table version, following @PaulS's tidyverse approach; Might help speed wise with 1,000,000 rows, etc.

library(data.table)
setDT(df)

df = cbind(df[,1], df[,-1][, lapply(.SD, \(x) fifelse(duplicated(x),"",x))])
df[rowSums(df[,-1]=="")<5]

Output

   Hits category1 category2 category3 category4 category5
1: Hit1         a         c                             i
2: Hit3         b                   e
3: Hit4                   d         f                   j


来源: stackexchange

问:
Error decoding data with Codable even though parameters are optional
I have the following struct:

```<code>struct Recipe: Codable {
    @DocumentID var id: String?
    var minutes: Int?

    init(id: String, minutes: Int) {

        self.id = id
        self.minutes = minutes
    }

    init(from decoder: Decoder) throws {

        enum DecodingKeys: CodingKey {
            case minutes
          }

        let container = try decoder.container(keyedBy: DecodingKeys.self)
        minutes = try container.decode(Int.self, forKey: .minutes)
    }
}
</code>```

I'm decoding from a source where minutes is null, so I get the following error message:

```<code>Error parsing response data: keyNotFound(DecodingKeys(stringValue: "minutes", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key DecodingKeys(stringValue: \"minutes\", intValue: nil) (\"minutes\").", underlyingError: nil))
</code>```

However, I thought marking minutes as optional in struct Recipe was sufficient to handle this case? Is there something else I need to implement?

答:
When you implement init(from:) manually you need to use the decodeIfPresent(_:forKey:) variant for optional properties. The decode(_:forKey:) method throws an error if a nullable field in the JSON data is absent whereas the decodeIfPresent(_:forKey:) method just returns nil.

Try this:

```<code>init(from decoder: Decoder) throws {

    enum DecodingKeys: CodingKey {
        case minutes
      }

    let container = try decoder.container(keyedBy: DecodingKeys.self)
    minutes = try container.decodeIfPresent(Int.self, forKey: .minutes)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following struct:

struct Recipe: Codable {
    @DocumentID var id: String?
    var minutes: Int?

    init(id: String, minutes: Int) {

        self.id = id
        self.minutes = minutes
    }

    init(from decoder: Decoder) throws {

        enum DecodingKeys: CodingKey {
            case minutes
          }

        let container = try decoder.container(keyedBy: DecodingKeys.self)
        minutes = try container.decode(Int.self, forKey: .minutes)
    }
}

I'm decoding from a source where minutes is null, so I get the following error message:

Error parsing response data: keyNotFound(DecodingKeys(stringValue: "minutes", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key DecodingKeys(stringValue: \"minutes\", intValue: nil) (\"minutes\").", underlyingError: nil))

However, I thought marking minutes as optional in struct Recipe was sufficient to handle this case? Is there something else I need to implement?

Body:
When you implement init(from:) manually you need to use the decodeIfPresent(_:forKey:) variant for optional properties. The decode(_:forKey:) method throws an error if a nullable field in the JSON data is absent whereas the decodeIfPresent(_:forKey:) method just returns nil.

Try this:

init(from decoder: Decoder) throws {

    enum DecodingKeys: CodingKey {
        case minutes
      }

    let container = try decoder.container(keyedBy: DecodingKeys.self)
    minutes = try container.decodeIfPresent(Int.self, forKey: .minutes)
}


问:
Is there any way to use methods from interface and class specified when creating object from interface referance?
We got this scenario:

```<code>public class Shape{
    private String type;

}

public interface ShapeI{
    String calculateField();
}

public class Circle extends Shape implements ShapeI{

    private double radius;

    @Override
    public String calculateField() {
        return "PiRadisSQ";
    }

    public void circleMethod() {
        System.out.println("circleMethod");
    }
}

public class Main  {
    public static void main(String[] args) {
        ShapeI circle = new Circle();
        circle.calculateField(); // can use it
        circle.circleMethod(); // can't use it
    }
}

</code>```

Is there a way to use Cicrcle class method circleMethod() when creating object with interface referance? I cant figure out how to create such a hierarchy.

答:
circleMethod() is logically spécifique to Circles and does not apply to all Shapes. The interface methods must be implemented by all Classes which implement it.
The interface can therefore include methods which are applicable to all Shapes,area, perimeter etc, but will be implemented in different ways according to the shape in question.</p>

Body:
We got this scenario:

public class Shape{
    private String type;

}

public interface ShapeI{
    String calculateField();
}

public class Circle extends Shape implements ShapeI{

    private double radius;

    @Override
    public String calculateField() {
        return "PiRadisSQ";
    }

    public void circleMethod() {
        System.out.println("circleMethod");
    }
}

public class Main  {
    public static void main(String[] args) {
        ShapeI circle = new Circle();
        circle.calculateField(); // can use it
        circle.circleMethod(); // can't use it
    }
}

Is there a way to use Cicrcle class method circleMethod() when creating object with interface referance? I cant figure out how to create such a hierarchy.


问:
Overlay element at top-left corner of centered image
I have an image which is currently centered on the screen using flexbox:

```<code>.center-flex {
    display: flex;
    justify-content: center;
}

<div class="center-flex">
    <img id="revealImage">
</div>
</code>```

I am attempting to dynamically create a div that needs to be placed at the upper-left hand corner.  I have tried the following to get the computed left on the image but it does not work as it returns auto due to the flex layout.

```<code>const revealImage = document.getElementById('revealImage');

const left = window.getComputedStyle(revealImage,null).getPropertyValue('left');

let square = document.createElement('div');
square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
square.style.left = left;

console.log('left: ' + left);
</code>```

This results in a properly overlayed red box but it is centered and not set left.

答:
I think you made a small mistake(if I do not mistake):

Seem this is mistake:

```<code>square.style.left = left;
</code>```

do:

```<code>square.style.left = 0;
</code>```

is it right?

Body:
I have an image which is currently centered on the screen using flexbox:

.center-flex {
    display: flex;
    justify-content: center;
}

I am attempting to dynamically create a div that needs to be placed at the upper-left hand corner.  I have tried the following to get the computed left on the image but it does not work as it returns auto due to the flex layout.

const revealImage = document.getElementById('revealImage');

const left = window.getComputedStyle(revealImage,null).getPropertyValue('left');

let square = document.createElement('div');
square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
square.style.left = left;

console.log('left: ' + left);

This results in a properly overlayed red box but it is centered and not set left.

Body:
I think you made a small mistake(if I do not mistake):

Seem this is mistake:

square.style.left = left;

do:

square.style.left = 0;

is it right?


问:
.Net Core Entity Framework .Include Eager load does not load entity
My first question - be kind :-).

In the code below, I am attempting to reference an "Include(d)" entity (Schedules) to obtain its Name property. In EF 6, both "schedule" and "schedule_2" return the correct value of Name. In EF Core, "schedule" returns NULL and "schedule_2" returns the correct value of Name.

I do not understand why I should have to load the "schedules" List. Shouldn't the .Include force an Eager Load of the Schedules for each Election such that each Election Schedule's Name property would be available for the "schedule" assignment?

```<code>// Relevant Model entities in database
//         DbSet<Election> Elections { get; set; }
//
// The following are the related classes defined in the database context...
public class Election
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Schedule> Schedules { get; set; }
}
public class Schedule
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public int? CfsElectionId { get; set; }
    public string Name { get; set; }

    [Required] // sets cascade delete
    [ForeignKey("CFSElectionID")]
    public virtual Election Election { get; set; }
}

class Program
{
    static void Main()
    {
        var db = new FfmsDbContext();
        var elections = db.Elections
            .Include(i => i.Schedules)
            .ToList();

        //The following returns NULL?
        var schedule = elections.First().Schedules?.First().Name ?? "NULL";

        var schedules = db.Schedules
            .ToList();

        //The following returns the correct Name property?
        var schedule_2 = elections.First().Schedules?.First().Name ?? "NULL";

        Console.WriteLine($@"sched: {schedule}");
        Console.WriteLine($@"schedules.First().Name: {schedules.First().Name}");
        Console.WriteLine($@"sched2: {schedule_2}");

        Console.WriteLine("Done...");
        Console.ReadLine();
    }
}

/*
  Output...
    sched: NULL
    schedules.First().Name: Candidates
    sched2: Candidates
    Done...
*/
</code>```

答:
Turns out that my problem ended up being in the References of the Class.

I had accidentally chosen System.Data.Entity as the offered choice for .Include.

The correct reference should have been Microsoft.EntityFrameworkCore.

Once I adjusted the reference, the .Include worked as desired.

Body:
My first question - be kind :-).

In the code below, I am attempting to reference an "Include(d)" entity (Schedules) to obtain its Name property. In EF 6, both "schedule" and "schedule_2" return the correct value of Name. In EF Core, "schedule" returns NULL and "schedule_2" returns the correct value of Name.

I do not understand why I should have to load the "schedules" List. Shouldn't the .Include force an Eager Load of the Schedules for each Election such that each Election Schedule's Name property would be available for the "schedule" assignment?

// Relevant Model entities in database
//         DbSet<Election> Elections { get; set; }
//
// The following are the related classes defined in the database context...
public class Election
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Schedule> Schedules { get; set; }
}
public class Schedule
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public int? CfsElectionId { get; set; }
    public string Name { get; set; }

    [Required] // sets cascade delete
    [ForeignKey("CFSElectionID")]
    public virtual Election Election { get; set; }
}

class Program
{
    static void Main()
    {
        var db = new FfmsDbContext();
        var elections = db.Elections
            .Include(i => i.Schedules)
            .ToList();

        //The following returns NULL?
        var schedule = elections.First().Schedules?.First().Name ?? "NULL";

        var schedules = db.Schedules
            .ToList();

        //The following returns the correct Name property?
        var schedule_2 = elections.First().Schedules?.First().Name ?? "NULL";

        Console.WriteLine($@"sched: {schedule}");
        Console.WriteLine($@"schedules.First().Name: {schedules.First().Name}");
        Console.WriteLine($@"sched2: {schedule_2}");

        Console.WriteLine("Done...");
        Console.ReadLine();
    }
}

/*
  Output...
    sched: NULL
    schedules.First().Name: Candidates
    sched2: Candidates
    Done...
*/


问:
Can't get route to /manifest.webmanifest to work
I've had a look around and I can't seem to find anything that really solves this (thanks in advance for the help).

I've built a website in Ionic. It's live at https://www.fairydustgame.com/

I am trying to make it a PWA. When I load the site I can see that it's throwing the following error;

Manifest: Line: 1, column: 1, Syntax error.

My manifest file is at /manifest.webmanifest - which is referenced in the index.html file of my app.

If I run the site locally I don't get that error. Relatedly - if I access /manifest.webmanifest via localhost I am able to load the page. However - if I try to access the same page online I get a routing error.

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'manifest.webmanifest'

Here is my app-routing-module.ts

```<code>  {
    path: '',
    loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)

  }
];
</code>```

I am aware that I am loading the /home module at root so I've also tried copying the manifest file into the /home directory. No dice.

I am currently hosting with AWS Amplify, cached using Cloudflare, however - accessing the site with the direct Amplify URL has the same behaviour.

I have tried including cross-origin and adding necessary redirects as per this answer

I have also tried duplicating manifest.webmanifest to create a manifest.json file - if I do that and try to access manifest.json locally - I get the same routing error. I have tried manually repeating the copy within the /www folder, and tried this auto-copy solution to try to get manifest.json working locally, but if I change the index.html reference to read manifest.json I get the same routing error and Manifest: Line: 1, column: 1, Syntax error. as I get with the hosted manifest.webmanifest.

I have also tried copying manifest.json into the /home directory just in case. Again - no dice.

At this point I have no idea where to go next - I'm not sure if I'm just fundamentally misunderstanding how routing works. Though even in that case - it's very weird to me that a route would work locally but not when hosted on amplify. Unless, perhaps, amplify can't cope with the webmanifest file extension, but I can't seem to get even my local instance to understand the .json rename so I don't know how I can test that.

Any help would be much appreciated.

答: Turns out I had to reorder the redirects in AWS Amplify - put the redirects first and started picking up the manifest file fine.</p>

Body:
I've had a look around and I can't seem to find anything that really solves this (thanks in advance for the help).

I've built a website in Ionic. It's live at https://www.fairydustgame.com/

I am trying to make it a PWA. When I load the site I can see that it's throwing the following error;

Manifest: Line: 1, column: 1, Syntax error.

My manifest file is at /manifest.webmanifest - which is referenced in the index.html file of my app.

If I run the site locally I don't get that error. Relatedly - if I access /manifest.webmanifest via localhost I am able to load the page. However - if I try to access the same page online I get a routing error.

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'manifest.webmanifest'

Here is my app-routing-module.ts

  {
    path: '',
    loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)

  }
];

I am aware that I am loading the /home module at root so I've also tried copying the manifest file into the /home directory. No dice.

I am currently hosting with AWS Amplify, cached using Cloudflare, however - accessing the site with the direct Amplify URL has the same behaviour.

I have tried including cross-origin and adding necessary redirects as per this answer

I have also tried duplicating manifest.webmanifest to create a manifest.json file - if I do that and try to access manifest.json locally - I get the same routing error. I have tried manually repeating the copy within the /www folder, and tried this auto-copy solution to try to get manifest.json working locally, but if I change the index.html reference to read manifest.json I get the same routing error and Manifest: Line: 1, column: 1, Syntax error. as I get with the hosted manifest.webmanifest.

I have also tried copying manifest.json into the /home directory just in case. Again - no dice.

At this point I have no idea where to go next - I'm not sure if I'm just fundamentally misunderstanding how routing works. Though even in that case - it's very weird to me that a route would work locally but not when hosted on amplify. Unless, perhaps, amplify can't cope with the webmanifest file extension, but I can't seem to get even my local instance to understand the .json rename so I don't know how I can test that.

Any help would be much appreciated.


问:
I get an error when I do 'yarn start'(Required package: @babel/plugin-proposal-private-property-in-object)
I get an error when I do yarn start. I search that in the other relevant questions of the stack, but I did not find the solution to my problem. I thinks dependencies of my package.json is correct.

This is my error:

Edit:

I get this error after of run:

```<code>yarn add @babel/plugin-proposal-private-property-in-object --dev && yarn
</code>```

答:
As stated by the error message, it appears yarn was expecting this package as a dependency. So the problem may be solved by installing it with:

yarn add @babel/plugin-proposal-private-property-in-object --dev && yarn

Body:
I get an error when I do yarn start. I search that in the other relevant questions of the stack, but I did not find the solution to my problem. I thinks dependencies of my package.json is correct.

This is my error:

Edit:

I get this error after of run:

yarn add @babel/plugin-proposal-private-property-in-object --dev && yarn


问:
ASP.NET Session State in Cluster
Our project was implemented originally with in memory session state. We need to scale up and add another server in an IIS server farm. I did all the steps to get the session state stored in a sql server database, but not all my objects are serializable, and db session state does require serializable objects.

My current thought is to create another layer of structs to mirror all the data that need to be serializable, and store them in session. When I need access to my object, I would use an adapter to morph the session struct into the object I need. Is this the way to go, or are there better options (other than manually making sure my current classes are serializable)?

答: The Load Balancer of the farm should be configured to serve all requests of a client to the same server.</p>

ContentLicense: CC BY-SA 3.0

Title: ASP.NET Session State in Cluster


问:
Help with Python UnboundLocalError: local variable referenced before assignment
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.

```<code>from numpy import *
import math as M

#initial condition  All in SI unit
G=6.673*10**-11   #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10           #time step
#Creat arrays
vs=array([[0,0,0]])     #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])
re=array([[0,1.4960*10**11,0]])

#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms
ve=ve+fe*dt/me

n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
    rs,re=update_r(rs,re,n,dt)
    fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
    fe=-fs
    return fs,fe

#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
    fs,fe=force(n,ms,me,rs,re,G)
    i=arange(n)
    vs=vs+fs[:]*i[:,newaxis]*dt/ms
    ve=ve+fe[:]*i[:,newaxis]*dt/me
    return vs,ve

#update position
def update_r(rs,re,n,dt):
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    i=arange(n)
    rs=rs+vs[:]*i[:,newaxis]*dt
    re=re+ve[:]*i[:,newaxis]*dt
    return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? –
</code>```

when i call force python gives:

```<code>please enter the number of timestep you want it evolve:4Traceback (most recent call last):
  File "<pyshell#391>", line 1, in <module>
    force(n,ms,me,rs,re,G)
  File "/Users/Code.py", line 24, in force
    rs,re=update_r(rs,re,n,dt)
  File "/Users/Code.py", line 39, in update_r
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment
</code>```

can anyone give me some tips?thanks......

答: I got that error when my class name was assigned to a variable that is called exactly like its name. example ClassName = ClassName. You may do this if you come from .Net

ContentLicense: CC BY-SA 2.5

Body:
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.

from numpy import *
import math as M

#initial condition  All in SI unit
G=6.673*10**-11   #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10           #time step
#Creat arrays
vs=array([[0,0,0]])     #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])
re=array([[0,1.4960*10**11,0]])

#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms
ve=ve+fe*dt/me

n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
    rs,re=update_r(rs,re,n,dt)
    fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
    fe=-fs
    return fs,fe

#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
    fs,fe=force(n,ms,me,rs,re,G)
    i=arange(n)
    vs=vs+fs[:]*i[:,newaxis]*dt/ms
    ve=ve+fe[:]*i[:,newaxis]*dt/me
    return vs,ve

#update position
def update_r(rs,re,n,dt):
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    i=arange(n)
    rs=rs+vs[:]*i[:,newaxis]*dt
    re=re+ve[:]*i[:,newaxis]*dt
    return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? –

when i call force python gives:

please enter the number of timestep you want it evolve:4Traceback (most recent call last):
  File "<pyshell#391>", line 1, in <module>
    force(n,ms,me,rs,re,G)
  File "/Users/Code.py", line 24, in force
    rs,re=update_r(rs,re,n,dt)
  File "/Users/Code.py", line 39, in update_r
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment

can anyone give me some tips?thanks......


问:
PHP formula needed to calculate a simple format
I am trying to take an amount and convert it to a units type format...

For example:

( note: don't worry about the dollar sign )

Total is $400

I need to display it as 4 * 100

Another Example

Total is $450

I need to display it as 4 * 100 |  50 * 1

So another words there are only 100 and 1 units.

I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?

答:
Here's a simple implementation

```<code>$amount = 450;

$hundreds = floor($amount / 100);
$ones     = $amount % 100;

$string = array();
if( $hundreds )
    $string[] = "$hundreds * 100";

if( $ones )
    $string[] = "$ones * 1";

echo implode(' | ', $string);
</code>```

Check out the modulus (%) operator

Body:
Here's a simple implementation

$amount = 450;

$hundreds = floor($amount / 100);
$ones     = $amount % 100;

$string = array();
if( $hundreds )
    $string[] = "$hundreds * 100";

if( $ones )
    $string[] = "$ones * 1";

echo implode(' | ', $string);

Check out the modulus (%) operator


问:
How to write statement that deletes extra space in C++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?</p>
```<code>//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

</code>```

答:
In the section

```<code>      else
      {
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
</code>```

You seem to have accidentally omitted the braces around the final else clause. It probably should read:

```<code>      else
      {
         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
            std::cout << day << " ";
            std::cout << " ";
         }
      }
</code>```

This ensures that the dangling std::cout << " "; mentioned by @Igor-Tandetnik is part of the else clause, as you seem to have intended.

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?

//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

Body:
In the section

      else
      {
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }

You seem to have accidentally omitted the braces around the final else clause. It probably should read:

      else
      {
         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
            std::cout << day << " ";
            std::cout << " ";
         }
      }

This ensures that the dangling std::cout << " "; mentioned by @Igor-Tandetnik is part of the else clause, as you seem to have intended.


答:
Hoping I am not doing your homework. Try this:</p>

```<code>$num = 450;
$ones = $num % 100;
$hundreds = floor($num / 100);
echo "$hundreds * 100 | $ones * 1";
</code>```

Title: PHP formula needed to calculate a simple format

Body:
I am trying to take an amount and convert it to a units type format...

For example:

( note: don't worry about the dollar sign )

Total is $400

I need to display it as 4 * 100

Another Example

Total is $450

I need to display it as 4 * 100 |  50 * 1

So another words there are only 100 and 1 units.

I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?

Body:
Hoping I am not doing your homework. Try this:

$num = 450;
$ones = $num % 100;
$hundreds = floor($num / 100);
echo "$hundreds * 100 | $ones * 1";


问:
Adding object inside state's array
I'm trying to add an object in the array defined in the state, which (object) I get from a child then moving up to the parent, setting it to  parent's state and giving it to another(that child's code is down below) child as a prop. I saw some solutions but they are not working. The present solution gives me an infinite loop, props item is added over and over. So my question is how to add an item in the array which is defined in the state and the item that we are getting is a prop. Here's my code</p>
```<code>import React, { Component } from "react";

import "./ShoppingCart.css";

class ShoppingCart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
    };
  }

  onAddItem = () => {

    if(Object.keys(this.props.item).length !== 0)
    //checking initial empty prop
    {

      const item = this.props.item;
      //an object consist of {id,title,price...etc}

      //the solution i found on the internet
      const newList = this.state.items.concat(item);
      console.log("New List",newList);

      this.setState({
        items:newList
      })

    }

  };

  render() {
    this.onAddItem();
    return (
      <React.Fragment>
        <button className="cart-button">
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );
  }
}

export default ShoppingCart;

</code>```

答:
You are calling the function on every render and then setting state, causing another render, and then the render call the function again.... it's an infinite loop.

```<code>  render() {
    this.onAddItem(); // ❌ REMOVE THIS LINE
    return (
      <React.Fragment>
        <button className="cart-button" onClick={this.onAddItem}> //✅ add onclick event to add item here
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );
</code>```

Update constructor

```<code>constructor(props) {
super(props);

this.state = {
  items: [],
};
this.onAddItem = this.onAddItem.bind(this)
</code>```

}

Updated onAddItem

```<code> onAddItem = (item) => {

    const newList = [...this.props.item, item]

      this.setState({
        items: newList
      })

    }

  };
</code>```

Title: Adding object inside state's array

Body:
I'm trying to add an object in the array defined in the state, which (object) I get from a child then moving up to the parent, setting it to  parent's state and giving it to another(that child's code is down below) child as a prop. I saw some solutions but they are not working. The present solution gives me an infinite loop, props item is added over and over. So my question is how to add an item in the array which is defined in the state and the item that we are getting is a prop. Here's my code

import React, { Component } from "react";

import "./ShoppingCart.css";

class ShoppingCart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
    };
  }

  onAddItem = () => {

    if(Object.keys(this.props.item).length !== 0)
    //checking initial empty prop
    {

      const item = this.props.item;
      //an object consist of {id,title,price...etc}

      //the solution i found on the internet
      const newList = this.state.items.concat(item);
      console.log("New List",newList);

      this.setState({
        items:newList
      })

    }

  };

  render() {
    this.onAddItem();
    return (
      <React.Fragment>
        <button className="cart-button">

          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );
  }
}

export default ShoppingCart;

Body:
You are calling the function on every render and then setting state, causing another render, and then the render call the function again.... it's an infinite loop.

  render() {
    this.onAddItem(); // ❌ REMOVE THIS LINE
    return (
      <React.Fragment>
        <button className="cart-button" onClick={this.onAddItem}> //✅ add onclick event to add item here
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );

Update constructor

constructor(props) {
super(props);

this.state = {
  items: [],
};
this.onAddItem = this.onAddItem.bind(this)

}

Updated onAddItem

 onAddItem = (item) => {

    const newList = [...this.props.item, item]

      this.setState({
        items: newList
      })

    }

  };


问:
Java Math issue incorrect output
(51^43)Mod77 in scientific calculator gives 2 as the output however,

(int)(Math.pow(51,43)%(double)77) gives 12 which should be 2 instead.

Can you please help ?

答:
A double doesn't have enough precision to hold all the digits of Math.pow(51,43). So when you take it mod 77, the answer is prone to significant rounding errors.

I suggest using BigInteger for arbitrary precision integer arithmetic.

Title: Java Math issue incorrect output


问:
How can I get rid of the parentheses in the dataframe column?(Python)
I have dataframe like this

I want to remove the parentheses in the Movie_Name column.

Here is a few example

```<code>df_Movie["Movie Name"].str.findall(r'\([^()]*\)').sum()

['(500)',
 '(Eksiteu)',
 '(Mumbai Diaries)',
 '(Geukhanjikeob)',
 '(Erkekler Ne İster?)',
 '(The Witch)',
 '(Ji Hun)']
</code>```

And then ı tried this solution.

```<code>import re
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'\([^()]*\)', ' ', regex = True)
</code>```

Here is the output of the solution for one example.

```<code>df_Movie.iloc[394, :]
Movie Name      Days of Summer
Year                      2009
IMDB                       7.7
Name: 394, dtype: object
</code>```

In this case, the values between the parentheses are completely lost. I don't want that.

I want output like this : (500) Days of Summer --> 500 Days of Summer

How can ı solve this ?

答:
You can remove all parentheses from a dataframe column using

df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'[()]+', '', regex=True)
```

The [()]+ regex pattern matches one or more ( or ) chars.

See the regex demo.

Body:
I have dataframe like this

I want to remove the parentheses in the Movie_Name column.

Here is a few example

df_Movie["Movie Name"].str.findall(r'\([^()]*\)').sum()

['(500)',
 '(Eksiteu)',
 '(Mumbai Diaries)',
 '(Geukhanjikeob)',
 '(Erkekler Ne İster?)',
 '(The Witch)',
 '(Ji Hun)']

And then ı tried this solution.

import re
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'\([^()]*\)', ' ', regex = True)

Here is the output of the solution for one example.

df_Movie.iloc[394, :]
Movie Name      Days of Summer
Year                      2009
IMDB                       7.7
Name: 394, dtype: object

In this case, the values between the parentheses are completely lost. I don't want that.

I want output like this : (500) Days of Summer --> 500 Days of Summer

How can ı solve this ?

Body:
You can remove all parentheses from a dataframe column using

df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'[()]+', '', regex=True)

The [()]+ regex pattern matches one or more ( or ) chars.

See the regex demo.


问:
Moq - verify that no methods were called
This is a unit-test from one of my controllers in an ASP.NET MVC project, using NUnit and Moq:

```<code>[Test]
public void Create_job_with_modelstate_errors_fails()
{
    var job = new JobDto();
    this.controller.ModelState.AddModelError("", "");

    ActionResult result = this.controller.Create(job);

    this.jobService.Verify(p => p.SaveJob(It.IsAny<JobDto>()), Times.Never());

    // some other asserts removed for brevity
}
</code>```

This works fine, but from a maintenance point of view I think this line is more verbose than it needs to be:

```<code>this.postService.Verify(p => p.SavePost(It.IsAny<PostDto>()), Times.Never());
</code>```

What i'd really like to be able to do is something equivalent to...

```<code>this.postService.VerifyNoMethodsCalled();
</code>```

...as all i'm interested in is that my controller doesn't call any methods on the service. Is this possible using Moq?

答:
Modern answer (Moq 4.8 or later):

```<code>mock.VerifyNoOtherCalls();
</code>```

That method makes sure no calls were made except for any previously verified ones.  In this particular case, there are no mock.Verify(...) statements before it.  Thus, it will make sure the mock was never called at all.

You will get a failure message like this if any calls were made:

```<code>This mock failed verification due to the following unverified invocations:
...
</code>```

This does not require making the mock strict.

Source: Moq Quickstart

Body:
This is a unit-test from one of my controllers in an ASP.NET MVC project, using NUnit and Moq:

[Test]
public void Create_job_with_modelstate_errors_fails()
{
    var job = new JobDto();
    this.controller.ModelState.AddModelError("", "");

    ActionResult result = this.controller.Create(job);

    this.jobService.Verify(p => p.SaveJob(It.IsAny<JobDto>()), Times.Never());

    // some other asserts removed for brevity
}

This works fine, but from a maintenance point of view I think this line is more verbose than it needs to be:

this.postService.Verify(p => p.SavePost(It.IsAny<PostDto>()), Times.Never());

What i'd really like to be able to do is something equivalent to...

this.postService.VerifyNoMethodsCalled();

...as all i'm interested in is that my controller doesn't call any methods on the service. Is this possible using Moq?

Body:
Modern answer (Moq 4.8 or later):

mock.VerifyNoOtherCalls();

That method makes sure no calls were made except for any previously verified ones.  In this particular case, there are no mock.Verify(...) statements before it.  Thus, it will make sure the mock was never called at all.

You will get a failure message like this if any calls were made:

This mock failed verification due to the following unverified invocations:
...

This does not require making the mock strict.

Source: Moq Quickstart


问:
VBA lookup with multiple returns
I am looking for help with applying VLOOKUP function to add extension to my pre existing table,

TABLE 1:

CAR
TOP SPEED
COLOR

BMW
200
BLACK

TESLA
220
WHITE

Table 2:

CAR
MODEL
YEAR

FORD
MUSTANG
2022

BMW
X5
2020

HONDA
ACCORD
2019

TESLA
Model S
2021

NISSAN
MAXIMA
2017

I am aiming to have the Table B as follows:

CAR
TOP SPEED
COLOR
MODEL
YEAR

BMW
200
BLACK
X5
2020

TESLA
220
WHITE
Model S
2021

```<code>sub CARSPEC()

Dim R As Long
Dim C As Long
Table1 = Sheets("Sheet1").Range("A2:A" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
Table2 = Sheets("Sheet2").Range("A2:H" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
R = Sheets("Sheet1").Range("D2").Row
C = Sheets("Sheet1").Range("D2").Column
For Each cell In Table1
 Sheets("Sheet1").Cells(R, C) = Application.WorksheetFunction.VLookup(cell, Table2, 2, False)
 R = R + 1
Next cell

End sub
</code>```

With the code above I am only getting the table without the year, meaning :

BMW
200
BLACK
X5

TESLA
220
WHITE
Model S

How could I expand the return values to cover the years as well.

Very much appreciated and THX Ahead.

答:
Sub CARSPEC()

    Dim lastrow As Long, awf
    Dim Table1 As Range, Table2 As Range, cell As Range

    With Sheets("Sheet2")
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set Table2 = .Range("A2:H" & lastrow)
    End With

    Set awf = Application.WorksheetFunction
    With Sheets("Sheet1")
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set Table1 = .Range("A2:A" & lastrow)

        For Each cell In Table1
            .Cells(cell.Row, "D") = awf.VLookup(cell.Value, Table2, 2, False)
            .Cells(cell.Row, "E") = awf.VLookup(cell.Value, Table2, 3, False)
        Next
    End With

End Sub
```

Title: VBA lookup with multiple returns

Body:
I am looking for help with applying VLOOKUP function to add extension to my pre existing table,

TABLE 1:

CAR
TOP SPEED
COLOR

BMW
200
BLACK

TESLA
220
WHITE

Table 2:

CAR
MODEL
YEAR

FORD
MUSTANG
2022

BMW
X5
2020

HONDA
ACCORD
2019

TESLA
Model S
2021

NISSAN
MAXIMA
2017

I am aiming to have the Table B as follows:

CAR
TOP SPEED
COLOR
MODEL
YEAR

BMW
200
BLACK
X5
2020

TESLA
220
WHITE
Model S
2021

sub CARSPEC()

Dim R As Long
Dim C As Long
Table1 = Sheets("Sheet1").Range("A2:A" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
Table2 = Sheets("Sheet2").Range("A2:H" & Sheets("Sheet1").cells(rows.count,1).end(XLUP).row)
R = Sheets("Sheet1").Range("D2").Row
C = Sheets("Sheet1").Range("D2").Column
For Each cell In Table1
 Sheets("Sheet1").Cells(R, C) = Application.WorksheetFunction.VLookup(cell, Table2, 2, False)
 R = R + 1
Next cell

End sub

With the code above I am only getting the table without the year, meaning :

BMW
200
BLACK
X5

TESLA
220
WHITE
Model S

How could I expand the return values to cover the years as well.

Very much appreciated and THX Ahead.


问:
Where is lib/main.dart in Android Studio?
I am trying to learn Flutter and I am following this tutorial here.

I was able to successfully able to set up flutter and I opened Android Studio and hit play and I see the template base app showing. The tutorial then asks me to edit lib/dart.main

But I do not see that file anywhere in the file tree to edit it... I feel Like I am missing something really obvious.

What's frustrating is I can see main.dart file is running but I cant find it in Android Studio to edit it in Android Studio...

答:
I figured out my issue! In the top left where it says "Android" I had to click the drop down and change it to "Project"

and now you can see the /lib directory :-)


问:
I can't figure out why hash[0] is being assigned the value 1 in the output . Any help would be appreciated
This is my code:-

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

int main()
{
    string magazine="aab";
    string ransomNote="aa";
    int hash[123]={};
        int i;
        for(i=0;i<=magazine.length();i++)
        {
            hash[magazine[i]]++;
        }
        for(i=0;i<123;i++)
        {
            cout<<hash[i]<<" ";
        }
        cout<<endl;
}
</code>```

The output is:-

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

答:
In c++ chars are almost the same thing as integers and they are stored as integers. So when you are performing hash[magazine[i]]++; what really happens is that the magazine[3] (which is the NULL character) will be promoted to an int (Source: cpp reference: Implicit Conversions, the equivalent of which is 0 based on the cpp reference: ASCII codes.

Thus, the statement hash[3] = 0 is true.
That said, the below code which is similar to the code used in the example

```<code>string x = hash[magazine[3]]++; //first x is assigned with the value of hash[magazine[3]], then hash[magazine[3]] is incremented.
cout << "output: " << x << "\n";
</code>```

will produce output: 0.

That happens because the hash[0] is assigned with the value of hash[magazine[3]] before the increment operator.Equivalently, the increment (++ operator) will be evaluated after the rest of the expression is -- after the assignment has been done.

If you want to avoid this behavior, you can do the below:

```<code>string x = ++hash[magazine[3]]; //first hash[magazine[0]] is incremented, then it is assigned to x.
cout << "output: " << x << "\n";
</code>```

which will produce output: 1.

However, hash[magazine[i]]++ is inside a loop. This means that after the loop concludes, the expression has already been evaluated and the hash array contains the new values, thus, hash[0] will be equal to 1.

Cheers,

Body:
This is my code:-

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string magazine="aab";
    string ransomNote="aa";
    int hash[123]={};
        int i;
        for(i=0;i<=magazine.length();i++)
        {
            hash[magazine[i]]++;
        }
        for(i=0;i<123;i++)
        {
            cout<<hash[i]<<" ";
        }
        cout<<endl;
}

The output is:-

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Body:
In c++ chars are almost the same thing as integers and they are stored as integers. So when you are performing hash[magazine[i]]++; what really happens is that the magazine[3] (which is the NULL character) will be promoted to an int (Source: cpp reference: Implicit Conversions, the equivalent of which is 0 based on the cpp reference: ASCII codes.

Thus, the statement hash[3] = 0 is true.
That said, the below code which is similar to the code used in the example

string x = hash[magazine[3]]++; //first x is assigned with the value of hash[magazine[3]], then hash[magazine[3]] is incremented.
cout << "output: " << x << "\n";

will produce output: 0.

That happens because the hash[0] is assigned with the value of hash[magazine[3]] before the increment operator.Equivalently, the increment (++ operator) will be evaluated after the rest of the expression is -- after the assignment has been done.

If you want to avoid this behavior, you can do the below:

string x = ++hash[magazine[3]]; //first hash[magazine[0]] is incremented, then it is assigned to x.
cout << "output: " << x << "\n";

which will produce output: 1.

However, hash[magazine[i]]++ is inside a loop. This means that after the loop concludes, the expression has already been evaluated and the hash array contains the new values, thus, hash[0] will be equal to 1.

Cheers,


问:
Sharing link for my website
I wish to have a sharing bar like in this page. http://www.templatebasics.com/wt00784bl/

How to make a sharing tab like this ?

I found that shareaholic is available only for blogs ? So, can I implement it on my website ??

Thanks in advance :)

答:
code:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
    <title>Demo - Integrate SexyBookmarks into your Personal page with JavaScript</title>
</head>

<body>

                        <center style="margin-top: 40px; color: silver;">
<div style="width: 600px;">
<p class="sexy-bookmarks-content" style="font-size: 22px; color: #000000;">Integrate SexyBookmarks into your Personal page with JavaScript</p>
<script type="text/javascript" src="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/jquery.js"></script>

    <script type="text/javascript" src="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/sexy-bookmarks-public.js"></script>
    <link rel="stylesheet" type="text/css" href="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/sexy-bookmarks-style.css" media="screen" />
                        <div class="sexy-bookmarks sexy-bookmarks-expand sexy-bookmarks-center sexy-bookmarks-bg-sexy">
                            <ul class="socials">
                                <li class="sexy-twittley"><a href="http://twittley.com/submit/" rel="nofollow" class="external" title="Submit this to Twittley">Submit this to Twittley</a></li>
                                <li class="sexy-digg"><a href="http://digg.com/submit" rel="nofollow" class="external" title="Digg this!">Digg this!</a></li>
                                <li class="sexy-twitter"><a href="http://twitter.com/home" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a></li>

                                <li class="sexy-scriptstyle"><a href="http://scriptandstyle.com/submit" rel="nofollow" class="external" title="Submit this to Script & Style">Submit this to Script & Style</a></li>
                                <li class="sexy-reddit"><a href="http://reddit.com/submit" rel="nofollow" class="external" title="Share this on Reddit">Share this on Reddit</a></li>
                                <li class="sexy-delicious"><a href="http://del.icio.us/post" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a></li>
                                <li class="sexy-stumbleupon"><a href="http://www.stumbleupon.com/submit" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a></li>
                                <li class="sexy-mixx"><a href="http://www.mixx.com/submit" rel="nofollow" class="external" title="Share this on Mixx">Share this on Mixx</a></li>

                                <li class="sexy-technorati"><a href="http://technorati.com/faves" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a></li>
                                <li class="sexy-blinklist"><a href="http://www.blinklist.com/index.php" rel="nofollow" class="external" title="Share this on Blinklist">Share this on Blinklist</a></li>
                                <li class="sexy-diigo"><a href="http://www.diigo.com/post">Post this on Diigo</a></li>
                                <li class="sexy-yahoobuzz"><a href="http://buzz.yahoo.com/submit/" rel="nofollow" class="external" title="Buzz up!">Buzz up!</a></li>
                                <li class="sexy-myspace"><a href="http://www.myspace.com/Modules/PostTo/Pages/" rel="nofollow" class="external" title="Post this to MySpace">Post this to MySpace</a></li>
                                <li class="sexy-facebook"><a href="http://www.facebook.com/share.php" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a></li>

                                <li class="sexy-designfloat"><a href="http://www.designfloat.com/submit.php" rel="nofollow" class="external" title="Submit this to DesignFloat">Submit this to DesignFloat</a></li>
                                <li class="sexy-devmarks"><a href="http://devmarks.com/index.php" rel="nofollow" class="external" title="Share this on Devmarks">Share this on Devmarks</a></li>
                                <li class="sexy-newsvine"><a href="http://www.newsvine.com/_tools/seed&save" rel="nofollow" class="external" title="Seed this on Newsvine">Seed this on Newsvine</a></li>
                                <li class="sexy-google"><a href="http://www.google.com/bookmarks/mark" rel="nofollow" class="external" title="Add this to Google Bookmarks">Add this to Google Bookmarks</a></li>
                            </ul>
                        </div>
</div><i>Live demo by <a href="http://www.javascriptbank.com">JavaScriptBank.com</a></i></center>

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

Tutorial:
http://www.1stwebdesigner.com/css/integrate-sexybookmarks-html-page-javascript/

Live Demo:
http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/demo.html

Title: Sharing link for my website

Body:
code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
    <title>Demo - Integrate SexyBookmarks into your Personal page with JavaScript</title>
</head>

<body>

                        <center style="margin-top: 40px; color: silver;">
<div style="width: 600px;">
<p class="sexy-bookmarks-content" style="font-size: 22px; color: #000000;">Integrate SexyBookmarks into your Personal page with JavaScript</p>
<script type="text/javascript" src="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/jquery.js"></script>

    <script type="text/javascript" src="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/sexy-bookmarks-public.js"></script>
    <link rel="stylesheet" type="text/css" href="http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/sexy-bookmarks-style.css" media="screen" />
                        <div class="sexy-bookmarks sexy-bookmarks-expand sexy-bookmarks-center sexy-bookmarks-bg-sexy">
                            <ul class="socials">
                                <li class="sexy-twittley"><a href="http://twittley.com/submit/" rel="nofollow" class="external" title="Submit this to Twittley">Submit this to Twittley</a></li>
                                <li class="sexy-digg"><a href="http://digg.com/submit" rel="nofollow" class="external" title="Digg this!">Digg this!</a></li>
                                <li class="sexy-twitter"><a href="http://twitter.com/home" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a></li>

                                <li class="sexy-scriptstyle"><a href="http://scriptandstyle.com/submit" rel="nofollow" class="external" title="Submit this to Script &amp; Style">Submit this to Script &amp; Style</a></li>
                                <li class="sexy-reddit"><a href="http://reddit.com/submit" rel="nofollow" class="external" title="Share this on Reddit">Share this on Reddit</a></li>
                                <li class="sexy-delicious"><a href="http://del.icio.us/post" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a></li>
                                <li class="sexy-stumbleupon"><a href="http://www.stumbleupon.com/submit" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a></li>
                                <li class="sexy-mixx"><a href="http://www.mixx.com/submit" rel="nofollow" class="external" title="Share this on Mixx">Share this on Mixx</a></li>

                                <li class="sexy-technorati"><a href="http://technorati.com/faves" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a></li>
                                <li class="sexy-blinklist"><a href="http://www.blinklist.com/index.php" rel="nofollow" class="external" title="Share this on Blinklist">Share this on Blinklist</a></li>
                                <li class="sexy-diigo"><a href="http://www.diigo.com/post">Post this on Diigo</a></li>
                                <li class="sexy-yahoobuzz"><a href="http://buzz.yahoo.com/submit/" rel="nofollow" class="external" title="Buzz up!">Buzz up!</a></li>
                                <li class="sexy-myspace"><a href="http://www.myspace.com/Modules/PostTo/Pages/" rel="nofollow" class="external" title="Post this to MySpace">Post this to MySpace</a></li>
                                <li class="sexy-facebook"><a href="http://www.facebook.com/share.php" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a></li>

                                <li class="sexy-designfloat"><a href="http://www.designfloat.com/submit.php" rel="nofollow" class="external" title="Submit this to DesignFloat">Submit this to DesignFloat</a></li>
                                <li class="sexy-devmarks"><a href="http://devmarks.com/index.php" rel="nofollow" class="external" title="Share this on Devmarks">Share this on Devmarks</a></li>
                                <li class="sexy-newsvine"><a href="http://www.newsvine.com/_tools/seed&amp;save" rel="nofollow" class="external" title="Seed this on Newsvine">Seed this on Newsvine</a></li>
                                <li class="sexy-google"><a href="http://www.google.com/bookmarks/mark" rel="nofollow" class="external" title="Add this to Google Bookmarks">Add this to Google Bookmarks</a></li>
                            </ul>
                        </div>
</div><i>Live demo by <a href="http://www.javascriptbank.com">JavaScriptBank.com</a></i></center>

</body>
</html>

Tutorial:
http://www.1stwebdesigner.com/css/integrate-sexybookmarks-html-page-javascript/

Live Demo:
http://www.javascriptbank.com/javascript/article/Integrate_SexyBookmarks_into_your_Personal_page_with_JavaScript/demo.html


问:
Unit Conversion in Python
I'm working on a project that lets users track different data types over time. Part of the base idea is that a user should be able to enter data using any units that they need to. I've been looking at both units:

http://pypi.python.org/pypi/units/

and quantities:

http://pypi.python.org/pypi/quantities/

However I'm not sure the best way to go. From what I can tell, quantities is more complex, but includes a better initial list of units.

答:
I find the units packages to be more than what want.  It doesn't take much code to start building your own functions that refer back to the very few basic fundamental numbers.  Also, It forces you to do the dimensional analysis to prevent errors.

```<code>def FtoC(Tf):
    return (Tf-32)*5/9
def CtoF(Tc):
    return 9*Tc/5+32
def CtoK(Tc):
    return Tc+273.15
def INCHtoCM(Inch):
    return 2.54 * Inch
def CMtoINCH(cm):
    return cm / INCHtoCM(1)
def INCHtoMETER(inch):
    return .01*INCHtoCM(inch)
def FOOTtoMETER(foot):
    return INCHtoMETER(12*foot)
def METERtoINCH(Meter):
    return CMtoINCH(100 * Meter)
def METERtoFOOT(Meter):
    return METERtoINCH(Meter)/12
def M3toINCH3(M3):
    return (METERtoINCH(M3))**3
def INCH3toGALLON(Inch3):
    return Inch3 / 231
def M3toGALLON(M3):
    return INCH3toGALLON(M3toINCH3(M3))
def KG_M3toLB_GALLON(KGperM3):
    return KGtoLBM(KGperM3) / M3toGALLON(1)
def BARtoPASCAL(bar):
    return 100000 * bar
def KGtoLBM(kilogram):
    return kilogram * 2.20462262185
def LBMtoKG(lbm):
    return lbm/KGtoLBM(1)
def NEWTONtoLBF(newton):
    return newton * KGtoLBM(1) * METERtoFOOT(1) / STANDARD_GRAVITY_IMPERIAL()
def LBFtoNEWTON(lbf):
    return lbf * STANDARD_GRAVITY_IMPERIAL() * LBMtoKG(1) * FOOTtoMETER(1)
def STANDARD_GRAVITY_IMPERIAL():
    return 32.174049
def STANDARD_GRAVITY_SI():
    return 9.80665
def PASCALtoPSI(pascal):
    return pascal * NEWTONtoLBF(1) / METERtoINCH(1)**2
def PSItoPASCAL(psi):
    return psi * LBFtoNEWTON(1) / INCHtoMETER(1)**2
</code>```

Then let's say you want to plot the static head pressure of 1,3 Butadiene @44 F and use gauges in PSI because you live in the US but the density tables are in SI units as they should be........................

```<code># butadiene temperature in Fahrenheit
Tf = 44

# DIPPR105 Equation Parameters (Density in kg/m3, T in K)
# valid in temperature 165 to 424 Kelvin
A=66.9883
B=0.272506
C=425.17
D=0.288139

# array of pressures in psi
Pscale = np.arange(0,5,.1, dtype=float)
Tk = CtoK(FtoC(44))
Density = A / (B**(1+(1-Tk/C)**D)) # KG/M3
Height = [PSItoPASCAL(P) / (Density * STANDARD_GRAVITY_SI()) for P in Pscale]
Height_inch =  METERtoINCH(1) * np.array(Height, dtype=np.single)
</code>```

Title: Unit Conversion in Python

Body:
I find the units packages to be more than what want.  It doesn't take much code to start building your own functions that refer back to the very few basic fundamental numbers.  Also, It forces you to do the dimensional analysis to prevent errors.

def FtoC(Tf):
    return (Tf-32)*5/9
def CtoF(Tc):
    return 9*Tc/5+32
def CtoK(Tc):
    return Tc+273.15
def INCHtoCM(Inch):
    return 2.54 * Inch
def CMtoINCH(cm):
    return cm / INCHtoCM(1)
def INCHtoMETER(inch):
    return .01*INCHtoCM(inch)
def FOOTtoMETER(foot):
    return INCHtoMETER(12*foot)
def METERtoINCH(Meter):
    return CMtoINCH(100 * Meter)
def METERtoFOOT(Meter):
    return METERtoINCH(Meter)/12
def M3toINCH3(M3):
    return (METERtoINCH(M3))**3
def INCH3toGALLON(Inch3):
    return Inch3 / 231
def M3toGALLON(M3):
    return INCH3toGALLON(M3toINCH3(M3))
def KG_M3toLB_GALLON(KGperM3):
    return KGtoLBM(KGperM3) / M3toGALLON(1)
def BARtoPASCAL(bar):
    return 100000 * bar
def KGtoLBM(kilogram):
    return kilogram * 2.20462262185
def LBMtoKG(lbm):
    return lbm/KGtoLBM(1)
def NEWTONtoLBF(newton):
    return newton * KGtoLBM(1) * METERtoFOOT(1) / STANDARD_GRAVITY_IMPERIAL()
def LBFtoNEWTON(lbf):
    return lbf * STANDARD_GRAVITY_IMPERIAL() * LBMtoKG(1) * FOOTtoMETER(1)
def STANDARD_GRAVITY_IMPERIAL():
    return 32.174049
def STANDARD_GRAVITY_SI():
    return 9.80665
def PASCALtoPSI(pascal):
    return pascal * NEWTONtoLBF(1) / METERtoINCH(1)**2
def PSItoPASCAL(psi):
    return psi * LBFtoNEWTON(1) / INCHtoMETER(1)**2

Then let's say you want to plot the static head pressure of 1,3 Butadiene @44 F and use gauges in PSI because you live in the US but the density tables are in SI units as they should be........................

# butadiene temperature in Fahrenheit
Tf = 44

# DIPPR105 Equation Parameters (Density in kg/m3, T in K)
# valid in temperature 165 to 424 Kelvin
A=66.9883
B=0.272506
C=425.17
D=0.288139

# array of pressures in psi
Pscale = np.arange(0,5,.1, dtype=float)
Tk = CtoK(FtoC(44))
Density = A / (B**(1+(1-Tk/C)**D)) # KG/M3
Height = [PSItoPASCAL(P) / (Density * STANDARD_GRAVITY_SI()) for P in Pscale]
Height_inch =  METERtoINCH(1) * np.array(Height, dtype=np.single)


问:
Swift: Getting type(of:) to return the name of my typealias instead of the final type
Is there anyway to get the below to return "MyStringType" instead of "String"</p>
```<code>typealias MyStringType = String

let myVar: MyStringType = "Some string"
let result = type(of: myVar)
print(result) //this prints out String, but I would prefer to get MyStringType.
</code>```

答:
No. And it doesn't matter if it's something you defined.

"\(MyStringType.self)" // "String"
"\([String: String].Element.self)" // "(key: String, value: String)"
```

https://developer.apple.com/documentation/swift/dictionary/element

Body:
Is there anyway to get the below to return "MyStringType" instead of "String"

typealias MyStringType = String

let myVar: MyStringType = "Some string"
let result = type(of: myVar)
print(result) //this prints out String, but I would prefer to get MyStringType.

Body:
No. And it doesn't matter if it's something you defined.

"\(MyStringType.self)" // "String"
"\([String: String].Element.self)" // "(key: String, value: String)"

https://developer.apple.com/documentation/swift/dictionary/element


问:
Create STATIC and SHARED libraries with Clang
What is the minimal commmand line way to create an static and a dynamic library with Clang under Linux and Windows, and then, link it against an executable?

Suppose the project contains a main.cpp file with the main function, an lib_header.h file under /include/project_name and a lib_source.c or lib_source.cpp under /src

Thanks

答:
For both static and dynamic libraries, you first compile the source files individually:

```<code>clang -c -o lib_source.o lib_source.c -fPIC
</code>```

For the static library on Linux, archive all .o files together:

```<code>ar r library.a lib_source.o
</code>```

For the shared library, link with the -shared flag:

```<code>clang -shared -o library.so lib_source.o
</code>```

Body:
For both static and dynamic libraries, you first compile the source files individually:

clang -c -o lib_source.o lib_source.c -fPIC

For the static library on Linux, archive all .o files together:

ar r library.a lib_source.o

For the shared library, link with the -shared flag:

clang -shared -o library.so lib_source.o


问:
How to create quantiles with non-unique bin edges? Python or R
I want to divide my data into quantiles (quintiles to be more specific). However, when using qcut in Pandas or ntile in R, I either get the error that "bin edges must be unique" (qcut) or equal values get assigned to different quintiles (ntile).

Looking at the following data: [1, 8, 2, 1, 8]
I would like the ouput to be:

1 assigned to quintile 1

8 assigned to quintile 5

2 assigned to quintile 3

1 assigned to quintile 1 again

8 assigned to quintile 5 again

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

Do you have any ideas on how I can achieve this?

Thank you very much for your input!

Some data to use:

```<code>import pandas as pd
df = pd.DataFrame({'Date': ['2011-01-01', '2011-01-02', '2011-01-03','2011-01-01', '2011-01-02',
'2011-01-03','2011-01-01', '2011-01-02', '2011-01-03', '2011-01-01','2011-01-02', '2011-01-03',
'2011-01-01', '2011-01-02', '2011-01-03'], 'Name': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'],
'Value':[1, 3, 2, 8, 6, 5, 2, 10, 4, 1, 5, 3, 8, 4, 9]})
</code>```

Code I used in R:

```<code>df = df %>% group_by(Date) %>% mutate(Quint = ntile(Value, 5))
</code>```

This assigned qual values to different bins.

Code I used in Python:

```<code>df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(lambda x: pd.qcut(x, 5, labels=["XS", "S", "M", "L", "XL"]))
</code>```

This resulted in the error of bin edges having to be unique.

答:
Update

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

```<code>cut_rank = lambda x: pd.cut(x.rank(method='min'), 5, labels=["XS", "S", "M", "L", "XL"])
df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(cut_rank)
</code>```

Output:

```<code>>>> df[df['Date'] == '2011-01-01']
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
3   2011-01-01    B      8        XL
6   2011-01-01    C      2         L
9   2011-01-01    D      1        XS
12  2011-01-01    E      8        XL

>>> df
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
1   2011-01-02    A      3        XS
2   2011-01-03    A      2        XS
3   2011-01-01    B      8        XL
4   2011-01-02    B      6         L
5   2011-01-03    B      5         L
6   2011-01-01    C      2         L
7   2011-01-02    C     10        XL
8   2011-01-03    C      4         M
9   2011-01-01    D      1        XS
10  2011-01-02    D      5         M
11  2011-01-03    D      3         S
12  2011-01-01    E      8        XL
13  2011-01-02    E      4         S
14  2011-01-03    E      9        XL
</code>```

Old answer

You have to use rank with method='first' on each group before qcut:

```<code>qcut_rank = lambda x: pd.qcut(x.rank(method='first'), 5, labels=["XS", "S", "M", "L", "XL"])
df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(qcut_rank)
</code>```

Output:

```<code>>>> df
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
1   2011-01-02    A      3        XS
2   2011-01-03    A      2        XS
3   2011-01-01    B      8         L
4   2011-01-02    B      6         L
5   2011-01-03    B      5         L
6   2011-01-01    C      2         M
7   2011-01-02    C     10        XL
8   2011-01-03    C      4         M
9   2011-01-01    D      1         S
10  2011-01-02    D      5         M
11  2011-01-03    D      3         S
12  2011-01-01    E      8        XL
13  2011-01-02    E      4         S
14  2011-01-03    E      9        XL
</code>```

All explanation are here

Body:
I want to divide my data into quantiles (quintiles to be more specific). However, when using qcut in Pandas or ntile in R, I either get the error that "bin edges must be unique" (qcut) or equal values get assigned to different quintiles (ntile).

Looking at the following data: [1, 8, 2, 1, 8]
I would like the ouput to be:

1 assigned to quintile 1

8 assigned to quintile 5

2 assigned to quintile 3

1 assigned to quintile 1 again

8 assigned to quintile 5 again

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

Do you have any ideas on how I can achieve this?

Thank you very much for your input!

Some data to use:

import pandas as pd
df = pd.DataFrame({'Date': ['2011-01-01', '2011-01-02', '2011-01-03','2011-01-01', '2011-01-02',
'2011-01-03','2011-01-01', '2011-01-02', '2011-01-03', '2011-01-01','2011-01-02', '2011-01-03',
'2011-01-01', '2011-01-02', '2011-01-03'], 'Name': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'],
'Value':[1, 3, 2, 8, 6, 5, 2, 10, 4, 1, 5, 3, 8, 4, 9]})

Code I used in R:

df = df %>% group_by(Date) %>% mutate(Quint = ntile(Value, 5))

This assigned qual values to different bins.

Code I used in Python:

df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(lambda x: pd.qcut(x, 5, labels=["XS", "S", "M", "L", "XL"]))

This resulted in the error of bin edges having to be unique.

Body:
Update

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

cut_rank = lambda x: pd.cut(x.rank(method='min'), 5, labels=["XS", "S", "M", "L", "XL"])
df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(cut_rank)

Output:

>>> df[df['Date'] == '2011-01-01']
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
3   2011-01-01    B      8        XL
6   2011-01-01    C      2         L
9   2011-01-01    D      1        XS
12  2011-01-01    E      8        XL

>>> df
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
1   2011-01-02    A      3        XS
2   2011-01-03    A      2        XS
3   2011-01-01    B      8        XL
4   2011-01-02    B      6         L
5   2011-01-03    B      5         L
6   2011-01-01    C      2         L
7   2011-01-02    C     10        XL
8   2011-01-03    C      4         M
9   2011-01-01    D      1        XS
10  2011-01-02    D      5         M
11  2011-01-03    D      3         S
12  2011-01-01    E      8        XL
13  2011-01-02    E      4         S
14  2011-01-03    E      9        XL

Old answer

You have to use rank with method='first' on each group before qcut:

qcut_rank = lambda x: pd.qcut(x.rank(method='first'), 5, labels=["XS", "S", "M", "L", "XL"])
df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(qcut_rank)

Output:

>>> df
          Date Name  Value Quintiles
0   2011-01-01    A      1        XS
1   2011-01-02    A      3        XS
2   2011-01-03    A      2        XS
3   2011-01-01    B      8         L
4   2011-01-02    B      6         L
5   2011-01-03    B      5         L
6   2011-01-01    C      2         M
7   2011-01-02    C     10        XL
8   2011-01-03    C      4         M
9   2011-01-01    D      1         S
10  2011-01-02    D      5         M
11  2011-01-03    D      3         S
12  2011-01-01    E      8        XL
13  2011-01-02    E      4         S
14  2011-01-03    E      9        XL

All explanation are here


问:
how payment can be deposited to merchants acc who(merchants) gave permissions to my application
For account of US based.

Currently  merchants gave  permission to my application to accept payment on their behalf to accept payments. but issue is i am always getting payment in my account not in registered merchant accounts.

i have used merchant onboarding APIs : https://developer.paypal.com/docs/archive/paypal-here/merchant-onboarding/permissions/

https://api-m.sandbox.paypal.com/v1/oauth2/token

https://www.sandbox.paypal.com/signin/authorize

gettting refresh token for merchant using below api

/v1/identity/openidconnect/tokenservice

.field("grant_type", "refresh_token")
.field("refresh_token", refreshToken)

can someone please help me to solve this ? or any other solution then please give me some details about that.

答:
The document you referenced is for PayPal Here, which is a PayPal application. It is probably not related to what you want to be doing.

With PayPal Checkout, payments can be directed to a different destination account by including a payee object in the purchase_units of the request.

Example using an email_address:

    {
      intent: 'CAPTURE',
      purchase_units: [{
        amount: {
          currency_code: 'USD',
          value: '220.00'
        },
        payee: {
          email_address: 'receiveraccount@emaildomain.com'
        }
      }]
    }
```

If you used the correct Multiparty (not PayPal Here) onboarding API, you may have their merchant_id. The merchant_id is more permanent than the email_address (cannot be changed on the PayPal account), so use that instead.

The merchant id can also be included in the JS SDK line as merchant-id when loading the script, which helps determine payment method eligibility; but you still need to include the payee object in the request as well, and these two ids must match.

Body:
The document you referenced is for PayPal Here, which is a PayPal application. It is probably not related to what you want to be doing.

With PayPal Checkout, payments can be directed to a different destination account by including a payee object in the purchase_units of the request.

Example using an email_address:

    {
      intent: 'CAPTURE',
      purchase_units: [{
        amount: {
          currency_code: 'USD',
          value: '220.00'
        },
        payee: {
          email_address: 'receiveraccount@emaildomain.com'
        }
      }]
    }

If you used the correct Multiparty (not PayPal Here) onboarding API, you may have their merchant_id. The merchant_id is more permanent than the email_address (cannot be changed on the PayPal account), so use that instead.

The merchant id can also be included in the JS SDK line as merchant-id when loading the script, which helps determine payment method eligibility; but you still need to include the payee object in the request as well, and these two ids must match.


问:
React native Firebase Firestore query
I'm trying to display a user's order history using query. The users' orders, dubbed "items", is an array and I can see the array being logged in the console with my code below. But nothing is being displayed in the app. What am I missing? Also attached my Firestore db for reference.

```<code>const q = query(ordersCollectionRef, where("items", "==", "userId"));
onSnapshot(q, (snapshot) => {
let orders = [];
snapshot.docs.forEach((doc) => {
  orders.push({ ...doc.data(), id: doc.id });
});
console.log(orders);
});
</code>```

...and in the return:

```<code>{orders.map((order) => {
        if (order.id === currentUser.uid) {
          return (
            <View>
              <Text>test{orders.items}</Text>
            </View>
          );
         };
      })}
</code>```

答:
For React to properly "understand" that you have updated data in a state variable, you need to use the "set state function" and NOT update the state variable directly.

In your code, put the data into a new and temporary variable, the after the forEach() call: setOrders(theTempVariable)

That puts the data in theTempVariable into the orders variable and it tells React that the variable has a new value....so React will "react" to state changing and it will re-render your component.

Title: React native Firebase Firestore query

Body:
I'm trying to display a user's order history using query. The users' orders, dubbed "items", is an array and I can see the array being logged in the console with my code below. But nothing is being displayed in the app. What am I missing? Also attached my Firestore db for reference.

const q = query(ordersCollectionRef, where("items", "==", "userId"));
onSnapshot(q, (snapshot) => {
let orders = [];
snapshot.docs.forEach((doc) => {
  orders.push({ ...doc.data(), id: doc.id });
});
console.log(orders);
});

...and in the return:

{orders.map((order) => {
        if (order.id === currentUser.uid) {
          return (
            <View>
              <Text>test{orders.items}</Text>
            </View>
          );
         };
      })}


问:
AJAX Using a REST API Without Server Side Framework
I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information.

Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs.

My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?

答:
Well, the AJAX calls need to pull data from a server somewhere.  If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small.

I've written a simple exapmle below.  The first class would be where you put the logic for your ReST API.  The code below the class is all you need to get the server up and running.

Install Python 2.6, save the code below to restExample.py.  Then in your command line run the python file by doing "python restExample.py".  Point your browser to http://localhost:8080/blog/999 and see some JSON come back.

```<code>import cherrypy
import json

# Create the controller
class Blog_Controller(object):
    def get(self, entryID):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
    def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
        # Update DB with passed in arguments.  entryID comes from URL,
        # other two entries come from POST
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps({'success':True})

# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
          controller=Blog_Controller(),
          conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
          controller=Blog_Controller(),
          conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)

# Start the webserver
engine = cherrypy.engine
try:
    engine.start()
except:
    sys.exit(1)
else:
    engine.block()
</code>```

OwnerDisplayName: Chris Dail

Body:
Well, the AJAX calls need to pull data from a server somewhere.  If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small.

I've written a simple exapmle below.  The first class would be where you put the logic for your ReST API.  The code below the class is all you need to get the server up and running.

Install Python 2.6, save the code below to restExample.py.  Then in your command line run the python file by doing "python restExample.py".  Point your browser to http://localhost:8080/blog/999 and see some JSON come back.

import cherrypy
import json

# Create the controller
class Blog_Controller(object):
    def get(self, entryID):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
    def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
        # Update DB with passed in arguments.  entryID comes from URL,
        # other two entries come from POST
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps({'success':True})

# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
          controller=Blog_Controller(),
          conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
          controller=Blog_Controller(),
          conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)

# Start the webserver
engine = cherrypy.engine
try:
    engine.start()
except:
    sys.exit(1)
else:
    engine.block()

OwnerDisplayName: Eric Palakovich Carr

LastEditorDisplayName: Eric Palakovich Carr


问:
Need help reading xml file in C#
I am making a program for Windows phone that will get weather data from a xml file and display it on screen. However, I keep getting null values and I am not sure what I am doing wrong.

Sample XML file: http://forecast.weather.gov/MapClick.php?lat=44.52160&lon=-87.98980&FcstType=dwml

Here is what I have:

```<code>try
{
    // get the stream containing the response from the async call
    streamResult = forecastState.AsyncResponse.GetResponseStream();

    // load the XML
    XElement xmlWeather = XElement.Load(streamResult);

    // find the source element
    XElement xmlCurrent = xmlWeather.Descendants("source").First();

    // get city and height
    xmlCurrent = xmlWeather.Descendants("location").First();
    mTempCityName = (string)(xmlCurrent.Element("city"));
    mTempHeight = (int)(xmlCurrent.Element("height"));

    //Find the forecast time
    xmlCurrent = xmlWeather.Descendants("time-layout").First();

    //store time of day in array
    mTimeOfDay = (string)(xmlCurrent.Attribute("period-name"));

    //Find the temperature
    xmlCurrent = xmlWeather.Descendants("temperature").First();
    mTemp = (int)(xmlCurrent.Element("value"));

    //now get the current weather conditions for each time period
    xmlCurrent = xmlWeather.Descendants("weather").First();
    mDescription = (string)(xmlCurrent.Attribute("weather-summary"));

    //now get icon links for weather
    xmlCurrent = xmlWeather.Descendants("conditions-icon").First();
    mIcon = (string)(xmlCurrent.Attribute("icon-link"));
}
</code>```

答:
Well:

time-layout doesn't have an attribute called period-name (it has subelements with that attribute)

temperature should be okay, I think

weather doesn't have a weather-summary attribute - it has subelements with that attribute

conditions-icon doesn't have an icons-link attribute, it has icons-link elements

In other words, for each bit you need to look at exactly what the XML contains, and then exactly what you're asking for, being careful to distinguish between elements and attributes.

Note that for the values you're casting to int (which don't need extra brackets around them, btw) you should be getting an exception in this case - you clearly can't be getting actual null values. Is it possible that an exception is being thrown and you're not noticing it? What's in your catch block?

Title: Need help reading xml file in C#

Body:
I am making a program for Windows phone that will get weather data from a xml file and display it on screen. However, I keep getting null values and I am not sure what I am doing wrong.

Sample XML file: http://forecast.weather.gov/MapClick.php?lat=44.52160&lon=-87.98980&FcstType=dwml

Here is what I have:

try
{
    // get the stream containing the response from the async call
    streamResult = forecastState.AsyncResponse.GetResponseStream();

    // load the XML
    XElement xmlWeather = XElement.Load(streamResult);

    // find the source element
    XElement xmlCurrent = xmlWeather.Descendants("source").First();

    // get city and height
    xmlCurrent = xmlWeather.Descendants("location").First();
    mTempCityName = (string)(xmlCurrent.Element("city"));
    mTempHeight = (int)(xmlCurrent.Element("height"));

    //Find the forecast time
    xmlCurrent = xmlWeather.Descendants("time-layout").First();

    //store time of day in array
    mTimeOfDay = (string)(xmlCurrent.Attribute("period-name"));

    //Find the temperature
    xmlCurrent = xmlWeather.Descendants("temperature").First();
    mTemp = (int)(xmlCurrent.Element("value"));

    //now get the current weather conditions for each time period
    xmlCurrent = xmlWeather.Descendants("weather").First();
    mDescription = (string)(xmlCurrent.Attribute("weather-summary"));

    //now get icon links for weather
    xmlCurrent = xmlWeather.Descendants("conditions-icon").First();
    mIcon = (string)(xmlCurrent.Attribute("icon-link"));
}


问:
Download .img file from given link using wget-module
I am trying to download a file in python using the wget module. The problem is, that the original file size is about 125mb, the file size of my download is just ~7kb

My code:

```<code>import wget
download_link = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"
wget.download(download_link)
</code>```

Output:

```<code>100% [................................................................................] 6846 / 6846'twrp-3.5.2_10-0-gauguin.img'
</code>```

File size:

```<code>francesco@francesco-ubuntu:~/Dokumente/GIT/python_adb$ ls -al twrp-3.5.2_10-0-gauguin.img
-rw-rw-r-- 1 francesco francesco 6846 Feb  6 22:26 twrp-3.5.2_10-0-gauguin.img
</code>```

Am I doing something wrong? Like I said, the original file size is ca 125mb, the file I downloaded around 7kb

Thanks in advance!

答:
To correctly download the file, try to set Referer and User-Agent HTTP header (example with requests module):

import requests

url = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0",
    "Referer": "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img",
}

r = requests.get(url, headers=headers)
with open("twrp-3.5.2_10-0-gauguin.img", "wb") as f_out:
    f_out.write(r.content)
```
<p>Download the file:</p>
<pre class="lang-none prettyprint-override"><code>-rw-r--r-- 1 root root 134217728 feb  6 22:49 twrp-3.5.2_10-0-gauguin.img
</code>```

Body:
I am trying to download a file in python using the wget module. The problem is, that the original file size is about 125mb, the file size of my download is just ~7kb

My code:

import wget
download_link = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"
wget.download(download_link)

Output:

100% [................................................................................] 6846 / 6846'twrp-3.5.2_10-0-gauguin.img'

File size:

francesco@francesco-ubuntu:~/Dokumente/GIT/python_adb$ ls -al twrp-3.5.2_10-0-gauguin.img
-rw-rw-r-- 1 francesco francesco 6846 Feb  6 22:26 twrp-3.5.2_10-0-gauguin.img

Am I doing something wrong? Like I said, the original file size is ca 125mb, the file I downloaded around 7kb

Thanks in advance!

Body:
To correctly download the file, try to set Referer and User-Agent HTTP header (example with requests module):

import requests

url = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0",
    "Referer": "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img",
}

r = requests.get(url, headers=headers)
with open("twrp-3.5.2_10-0-gauguin.img", "wb") as f_out:
    f_out.write(r.content)

Download the file:

-rw-r--r-- 1 root root 134217728 feb  6 22:49 twrp-3.5.2_10-0-gauguin.img


答:
So i found the solution but using request library, but I think you will be able to fix your code.

The fix is easy, you just need to specify Referer header

```<code>Referer: https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img
</code>```

So, my code with requests

```<code>import requests

image_url = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"

headers = {
    "Referer": "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img",
}

img_data = requests.get(image_url, headers=headers).content
with open('image_name.img', 'wb') as handler:
    handler.write(img_data)
</code>```

Title: Download .img file from given link using wget-module

Body:
So i found the solution but using request library, but I think you will be able to fix your code.

The fix is easy, you just need to specify Referer header

Referer: https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img

So, my code with requests

import requests

image_url = "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img"

headers = {
    "Referer": "https://dl.twrp.me/gauguin/twrp-3.5.2_10-0-gauguin.img",
}

img_data = requests.get(image_url, headers=headers).content
with open('image_name.img', 'wb') as handler:
    handler.write(img_data)


问:
How to replace character in nginx variable?
I have a variable that has in it
first_name_domain

And I want to transform it in
first.name.domain

I have tried something like

```<code>if ($subdomain ~ ^(.+&|)(LAYERS=[^&]+)_(.*)$) {
    set $subdomain2 $1$2.$3;
}
</code>```

Thank you.

答:
I don't think there is a way to replace some character multiply times like you want to (except of using third party modules). As a workaround, to replace limited quantity of characters, you can try a chain of the map blocks:

map $layers $first_replacement {
    ~^(?<first_prefix>.*?)_(?<first_suffix>.*)$  $first_prefix.$second_replacement;
    default  $layers;
}
map $first_suffix $second_replacement {
    ~^(?<second_prefix>.*?)_(?<second_suffix>.*)$  $second_prefix.$third_replacement;
    default  $first_suffix;
}
map $second_suffix $third_replacement {
    ~^(?<third_prefix>.*?)_(?<third_suffix>.*)$  $third_prefix.$third_suffix;
    default  $second_suffix;
}

server {
    ...
    if ($subdomain ~ ^(?<prefix>.+&|)(?<fixed>LAYERS=[^&]*?)_(?<layers>[^&]*)(?<suffix>&.*|$) {
        set $subdomain2 $prefix$fixed.$first_replacement$suffix;
    }
    ...
}
```

This example will replace maximum of four underscores, but you can increase the number of map blocks if you need.

Body:
I have a variable that has in it
first_name_domain

And I want to transform it in
first.name.domain

I have tried something like

if ($subdomain ~ ^(.+&|)(LAYERS=[^&]+)_(.*)$) {
    set $subdomain2 $1$2.$3;
}

Thank you.

Body:
I don't think there is a way to replace some character multiply times like you want to (except of using third party modules). As a workaround, to replace limited quantity of characters, you can try a chain of the map blocks:

map $layers $first_replacement {
    ~^(?<first_prefix>.*?)_(?<first_suffix>.*)$  $first_prefix.$second_replacement;
    default  $layers;
}
map $first_suffix $second_replacement {
    ~^(?<second_prefix>.*?)_(?<second_suffix>.*)$  $second_prefix.$third_replacement;
    default  $first_suffix;
}
map $second_suffix $third_replacement {
    ~^(?<third_prefix>.*?)_(?<third_suffix>.*)$  $third_prefix.$third_suffix;
    default  $second_suffix;
}

server {
    ...
    if ($subdomain ~ ^(?<prefix>.+&|)(?<fixed>LAYERS=[^&]*?)_(?<layers>[^&]*)(?<suffix>&.*|$) {
        set $subdomain2 $prefix$fixed.$first_replacement$suffix;
    }
    ...
}

This example will replace maximum of four underscores, but you can increase the number of map blocks if you need.


问:
How to do count fuction inside MAX()
I have these tables:

medic (idm(PK), name, address, salary)

consult (idm, idp, data)

pacient (idp, name, date, sex)

I want to select the medic that has done more consults to females. How can I do this?

I believe I need to do COUNT of the consults and select the MAX count possible, but I just can't figure it out.

Thanks in advance.

答:
You don't need MAX, you just need a TOP (1).

You can either do this in an apply:

SELECT TOP (1)
  m.idm,
  m.name,
  m.address,
  m.salary
FROM medic m
CROSS APPLY (
    SELECT numConsults = COUNT(*)
    FROM consult c
    JOIN pacient p ON p.idp = c.idp
      AND p.sex = 'F'
    WHERE c.idm = m.idm
    GROUP BY ()
) c
ORDER BY
  c.numConsults DESC;
```
<p>Or as a normal join</p>
<pre class="lang-sql prettyprint-override"><code>SELECT TOP (1)
  m.idm,
  m.name,
  m.address,
  m.salary,
  numConsults = COUNT(*)
FROM medic m
JOIN consult c ON c.idm = m.idm
JOIN pacient p ON p.idp = c.idp
  AND p.sex = 'F'
GROUP BY
  m.idm,
  m.name,
  m.address,
  m.salary
ORDER BY
  COUNT(*) DESC;
</code>```

Title: How to do count fuction inside MAX()

Body:
You don't need MAX, you just need a TOP (1).

You can either do this in an apply:

SELECT TOP (1)
  m.idm,
  m.name,
  m.address,
  m.salary
FROM medic m
CROSS APPLY (
    SELECT numConsults = COUNT(*)
    FROM consult c
    JOIN pacient p ON p.idp = c.idp
      AND p.sex = 'F'
    WHERE c.idm = m.idm
    GROUP BY ()
) c
ORDER BY
  c.numConsults DESC;

Or as a normal join

SELECT TOP (1)
  m.idm,
  m.name,
  m.address,
  m.salary,
  numConsults = COUNT(*)
FROM medic m
JOIN consult c ON c.idm = m.idm
JOIN pacient p ON p.idp = c.idp
  AND p.sex = 'F'
GROUP BY
  m.idm,
  m.name,
  m.address,
  m.salary
ORDER BY
  COUNT(*) DESC;