问:
Clicking Inside the text inside div and table
I am trying to click inside a text boxthat is inside a div which itself is inside a table. I have tried numerous approaches but none seems to work

This is the code for the element:

```<code><tr valign="top"><td id="xNEPk-chdex" style="height:100%"><div id="xNEPk" class="labelRowCnt z-div"><span id="xNEPm" class="z-label">Username:</span></div></td><td id="xNEPk-chdex2" class="z-hbox-separator"><img style="height:0;width:0"></td><td id="xNEPl-chdex" style="height:100%"><div id="xNEPl" class="compRowCnt z-div"><input id="xNEPn" class="login z-textbox" autocomplete="off" value="" type="text" name="j_username"></div></td></tr>
</code>```

I cannot go with the element ID as the element ID keeps changing every time I refresh the page

I have tried the following method some of which are

```<code>element =wait.until(EC.element_to_be_clickable((By.XPATH,'//div[@class=".compRowCnt.z-div"]/input[@class=".login.z-textbox"]')))
element.click()

element = driver.find_element_by_class_name("login.z-textbox")
element.click()

element =wait.until(EC.element_to_be_clickable((By.NAME,"j_username")))
element.click()

</code>```

But none seems to work. Every time I get element not found.

I want to be able to click inside the textbox so that I can provide my username using send keys.

Can anyone please help me? I am using chrome

答:
Seems you were pretty close. As the desired element is a dynamic element so to click() the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.login.z-textbox[name='j_username']"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='login z-textbox' and @name='j_username']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I am trying to click inside a text boxthat is inside a div which itself is inside a table. I have tried numerous approaches but none seems to work

This is the code for the element:

Username:

<input id="xNEPn" class="login z-textbox" autocomplete="off" value="" type="text" name="j_username">

I cannot go with the element ID as the element ID keeps changing every time I refresh the page

I have tried the following method some of which are

element =wait.until(EC.element_to_be_clickable((By.XPATH,'//div[@class=".compRowCnt.z-div"]/input[@class=".login.z-textbox"]')))
element.click()

element = driver.find_element_by_class_name("login.z-textbox")
element.click()

element =wait.until(EC.element_to_be_clickable((By.NAME,"j_username")))
element.click()

But none seems to work. Every time I get element not found.

I want to be able to click inside the textbox so that I can provide my username using send keys.

Can anyone please help me? I am using chrome

Body:
Seems you were pretty close. As the desired element is a dynamic element so to click() the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.login.z-textbox[name='j_username']"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='login z-textbox' and @name='j_username']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


来源: stackexchange

问:
Printing generator objects in python
I created my own iterator (to learn how they work) as follows

```<code>class Reverse():
    def __init__(self, word):
        self.word = word
        self.index = len(word)
    def __iter__(self):
        return self
    def __next__(self):
        self.index -=1
        if self.index < 0:
            raise StopIteration
        return self.word[self.index]

print (char for char in Reverse("word"),end="")
</code>```

I know I can say:

```<code>rev = Reverse("word")
for char in rev:
    print(char, end="")
</code>```

but I was hoping to be able to do it in a single line

```<code>print (char for char in Reverse("word"),end="")
</code>```

This doesn't work and raises an error. If I remove the end="" it prints out a generator object. Surely by including a for loop in the print statement it should iterate through my generator object and print each item?
Why does this not happen

答:
Why not like this?

print(''.join([char for char in Reverse("word")]))

ContentLicense: CC BY-SA 4.0

Title: Printing generator objects in python

Body:
I created my own iterator (to learn how they work) as follows

class Reverse():
    def __init__(self, word):
        self.word = word
        self.index = len(word)
    def __iter__(self):
        return self
    def __next__(self):
        self.index -=1
        if self.index < 0:
            raise StopIteration
        return self.word[self.index]

print (char for char in Reverse("word"),end="")

I know I can say:

rev = Reverse("word")
for char in rev:
    print(char, end="")

but I was hoping to be able to do it in a single line

print (char for char in Reverse("word"),end="")

This doesn't work and raises an error. If I remove the end="" it prints out a generator object. Surely by including a for loop in the print statement it should iterate through my generator object and print each item?
Why does this not happen


问:
gradle: how to enforce versions of the whole subtree?
there is a library x. it has a lot of dependencies and dependencies of dependencies. each version of x has different tree of dependencies

```<code>x
|- x1
|  |- ...
|
|- ...
</code>```

in my project some of my other dependencies include x with some specific version. some other dependencies include dependencies of x1, x2, xk different versions

what i want to do i to explicitly set version of x and enforce all its dependencies to be in a version declared by x i chosen

答:
If there are no other path to the dependencies of x, then fixing the version of x will have that effect.

However, because Gradle does conflict resolution between all participants, if a dependency of x, let's say y, also happens to be a dependency of z, which is another dependency of your project, then both version of y will be used in conflict resolution.

One way of detecting these issues and thus not being surprised by a conflict resolving an unexpected version is to use the failOnVersionConflict resolution strategy, as it will fail resolution if two paths bring y but with different versions.

Gradle 5.4 and before does not have a built-in mechanism to perform what you ask.

Body:
there is a library x. it has a lot of dependencies and dependencies of dependencies. each version of x has different tree of dependencies

x
|- x1
|  |- ...
|
|- ...

in my project some of my other dependencies include x with some specific version. some other dependencies include dependencies of x1, x2, xk different versions

what i want to do i to explicitly set version of x and enforce all its dependencies to be in a version declared by x i chosen


问:
How to find what exception some library code might throw
I am new to Kotlin and I have the following problem: In my project I am using a small library (JAR, no sources). In it there are few custom exception classes defined which inherit Exception class. Some methods throw these exceptions.

In my code I bump into the problem that I don't know what exception the library code might throw so I can catch it and thus sometimes the exception goes trough the roof.

What it is the usual way to handle such situations in Kotlin?

答:
Normaly such exceptions should be declared in the documentation of the library that you are using (either the JavaDoc, KDoc, or a website). There is no structured way to get all exceptions a function can throw, other than decompiling the code and step through it yourself. (by using the build in decompiler, that jet brains ship in IntelliJ for example)

You could also catch all exceptions, but I would always argue, that this is not a good decision in almost all cases.


问:
Disallow JavaScript to POST to an URL
I am currently having issues with Cross Site Scripting (XSS) weaknesses in a web app. Therefore I wonder if there's something like Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript?

My goal is to disallow the (good user's) browser from doing a POST to a specific URL via JavaScript (e.g. using XMLHttpRequest), while the "traditional" POST from the HTML form should be allowed. The idea is to prevent a malicious JavaScript from sending a POST request into the web app without user interaction.

It is similar to frame hijacking: By sending the Content-Security-Policy: frame-ancestors header with a URL, I can tell the browser not to put this URL into a frame. Now, I would like to tell the browser not to load a URL via JavaScript. Is there any such option?

答:
There's no real way to accomplish this... the browser (and the server) can't tell what was loaded "via JavaScript" vs "via HTML" -- and it wouldn't matter anyways, because XSS could simply create an HTML form and submit that automatically.

Your best bet might be to use some sort of anti-CSRF token that loads as part of the server-rendered HTML form. Not 100% foolproof for your use-case, but would do the trick.

Title: Disallow JavaScript to POST to an URL


问:
Need help on how to use onActivityResult() on Adapter Class?
I tried to return a phone number from a contact list on my adapter class, when i use  super.onActivityResult(requestCode, resultCode, data); I got error.

```<code>btnContactGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
                // Show only contacts with phone numbers

intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                // Start the Contacts activity
                context.startActivityForResult(intent, PICK_CONTACT);

            }
        });

public void onActivityResult(int requestCode, int resultCode, Intent data) {

 super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICK_CONTACT :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = conR.query(contactData, projection, null, null, null);
                c.moveToFirst();
int nameIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
                String name = c.getString(nameIdx);
                String phoneNumber = c.getString(phoneNumberIdx);
                String photo = c.getString(photoIdx);
                if (name == null) {
                    name = "No Name";
                }
                String nwPhone = phoneNumber.replace("+251", "0");

                edtPhoneGift.setText(nwPhone);
                c.close();

                // Now you have the phone number

            }
            break;
    }
 }
</code>```

Can not resolve method onActivityResult(int, int, Intent)

答:
Just delete the call to super super.onActivityResult(requestCode, resultCode, data), you don't need that.

Also, you need to change the ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI in your projection to something else, you can get Photo.XXX fields from the Uri returned from a Phone Picker intent, only columns within Phone.XXX or implicitly joined to it, you can try using Contacts.PHOTO_ID instead.

Body:
I tried to return a phone number from a contact list on my adapter class, when i use  super.onActivityResult(requestCode, resultCode, data); I got error.

btnContactGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
                // Show only contacts with phone numbers

intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                // Start the Contacts activity
                context.startActivityForResult(intent, PICK_CONTACT);

            }
        });

public void onActivityResult(int requestCode, int resultCode, Intent data) {

 super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICK_CONTACT :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = conR.query(contactData, projection, null, null, null);
                c.moveToFirst();
int nameIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
                String name = c.getString(nameIdx);
                String phoneNumber = c.getString(phoneNumberIdx);
                String photo = c.getString(photoIdx);
                if (name == null) {
                    name = "No Name";
                }
                String nwPhone = phoneNumber.replace("+251", "0");

                edtPhoneGift.setText(nwPhone);
                c.close();

                // Now you have the phone number

            }
            break;
    }
 }

Can not resolve method onActivityResult(int, int, Intent)


问:
Why is Observable within Observable hanging?
I have an http.get call in my service member.service.ts and I want to wait until that call completes before proceeding in app.component, so I'm trying to wrap the http.get call into an Observable for processing in app.component.

[Note: previously, before I wrapped the service in an Observable, the service was working fine . . . the http.get call on its own works as expected and returns a JSON object.]

But when I wrapped the http.get call in an Observable, as below, the application hangs. I searched online and read about flatMap, forkjoin, etc., but I'd like to keep the current structure, where the http.get call is in the member service, and all the other code is in app.component.

Many thanks if any ideas why it's hanging and how to fix!

member.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MemberService {
  url: string = "http://localhost:3000/sign-up";
  data: string = '';

  constructor(private http: HttpClient) { }

  getMemberForm(): Observable<any> {

   let library = this.http.get(this.url,{responseType: 'json'});

    library.subscribe((data) => {
      this.data = JSON.stringify(data);
    });
    return of(this.data);
  }

}

</code>```

app.component.ts

```<code>import { Component, OnInit, Injectable } from '@angular/core';
import { MemberService } from './member.service';

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

@Injectable()
export class AppComponent implements OnInit {
  got_data: boolean = false;
  data: string;

  constructor(private member: MemberService) {}

  ngOnInit() {

    this.member.getMemberForm().subscribe((data)=>{
      this.data = data;
      if (this.data.length > 0) this.got_data = true;
    });
  }

}

</code>```

答:
Never subscribe in a service this is a "anti pattern" in reactive programming (rxjs), just create the observable(http call) in the service and than subscribe in you component to trigger the http request, {responseType: 'json'} isn't needed all the "latest" versions (>4.3) of angular http client do it by default</p>

```<code>interface MyDataType{
    data: any;
}

 getMemberForm() {
   //no need to type the function return beacuse typescript will do it for you
   //you can type directly the http call
   return this.http.get<MyDataType>(this.url);

  }
</code>```

Body:
I have an http.get call in my service member.service.ts and I want to wait until that call completes before proceeding in app.component, so I'm trying to wrap the http.get call into an Observable for processing in app.component.

[Note: previously, before I wrapped the service in an Observable, the service was working fine . . . the http.get call on its own works as expected and returns a JSON object.]

But when I wrapped the http.get call in an Observable, as below, the application hangs. I searched online and read about flatMap, forkjoin, etc., but I'd like to keep the current structure, where the http.get call is in the member service, and all the other code is in app.component.

Many thanks if any ideas why it's hanging and how to fix!

member.service.ts

import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MemberService {
  url: string = "http://localhost:3000/sign-up";
  data: string = '';

  constructor(private http: HttpClient) { }

  getMemberForm(): Observable<any> {

   let library = this.http.get(this.url,{responseType: 'json'});

    library.subscribe((data) => {
      this.data = JSON.stringify(data);
    });
    return of(this.data);
  }

}

app.component.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { MemberService } from './member.service';

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

@Injectable()
export class AppComponent implements OnInit {
  got_data: boolean = false;
  data: string;

  constructor(private member: MemberService) {}

  ngOnInit() {

    this.member.getMemberForm().subscribe((data)=>{
      this.data = data;
      if (this.data.length > 0) this.got_data = true;
    });
  }

}

Body:
Never subscribe in a service this is a "anti pattern" in reactive programming (rxjs), just create the observable(http call) in the service and than subscribe in you component to trigger the http request, {responseType: 'json'} isn't needed all the "latest" versions (>4.3) of angular http client do it by default

interface MyDataType{
    data: any;
}

 getMemberForm() {
   //no need to type the function return beacuse typescript will do it for you
   //you can type directly the http call
   return this.http.get<MyDataType>(this.url);

  }


问:
Putting applets into a HTML, but how?
I wrote an applet which is called "IdrawApplet.java" and a HTML which is supposed to contain this applet. But somehow when I run the HTML it says that it can't find my java-Class.
This is a "Dynamic-Web-Project". It has a "WebContent"-Folder which contains both, the HTML and the java-Class.

As you will see I tried to insert the applet in two different ways. By putting it in a "applet"-Tag and a "object"-Tag (as suggested) on SELFHTML.org:

```<code><!-- <applet code= "IdrawApplet.class"
        codebase= "../applets"
        width= 320 height= 180></applet> -->

        <object classid="java:IdrawApplet.class"
        codebase="../applets"
        width="800" height="600"></object>
</code>```

Thanks in advance...

答:
for that..first check your environment variables, then see the class file names, if you do not write .class extention than it may be works...and its batter to include applet file..like
in header part of the html code</p>

ContentLicense: CC BY-SA 3.0

Title: Putting applets into a HTML, but how?

Body:
I wrote an applet which is called "IdrawApplet.java" and a HTML which is supposed to contain this applet. But somehow when I run the HTML it says that it can't find my java-Class.
This is a "Dynamic-Web-Project". It has a "WebContent"-Folder which contains both, the HTML and the java-Class.

As you will see I tried to insert the applet in two different ways. By putting it in a "applet"-Tag and a "object"-Tag (as suggested) on SELFHTML.org:

        <object classid="java:IdrawApplet.class"
        codebase="../applets"
        width="800" height="600"></object>

Thanks in advance...


问:
Laravel queue throws FatalThrowableError when trying to send mails
i am trying to send a mail on a named queue (registration.user) as soon as a new user registers in my laravel (5.7) application.

i have created a mailable and a job, the job is dispatched and is working fine util the queue starts running. the job is throwing an error and the stacktrace is pushed in the failed jobs table.

the job is as following:

```<code><?php

namespace App\Jobs;

use App\Mail\testMail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;

class SendRegistrationMailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var User
     */
    private $user;

    /**
     * Create a new job instance.
     *
     * @param User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->user->getAttribute('email'))->send(new testMail());
    }
}
</code>```

stacktrace (pastebin) (~ is where the project is)

答: it turned out to be a mistake I made while defining the queues, I just used the wrong syntax</p>

Body:
i am trying to send a mail on a named queue (registration.user) as soon as a new user registers in my laravel (5.7) application.

i have created a mailable and a job, the job is dispatched and is working fine util the queue starts running. the job is throwing an error and the stacktrace is pushed in the failed jobs table.

the job is as following:

<?php

namespace App\Jobs;

use App\Mail\testMail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;

class SendRegistrationMailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var User
     */
    private $user;

    /**
     * Create a new job instance.
     *
     * @param User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->user->getAttribute('email'))->send(new testMail());
    }
}

stacktrace (pastebin) (~ is where the project is)


问:
when would you get a web request without a host name?
I've been reviewing some nginx configuration docs and i found this:
http://nginx.org/en/docs/http/request_processing.html
I'm specifically reading the section about rejecting requests that don't provide a host name.

I'm wondering how to generate these types of requests for testing purposes, and when would these types of request come in - in real life...aka do i need to care?

What I've tried so far:

I've added the following into my nginx conf file

```<code>server {
    listen      80;
    server_name "";
    return      444;
}
</code>```

Then I tried to play around with curl and send a request with an empty host header like so:

```<code>curl --verbose --header 'Host:' 'http://192.1.6.1/test/hello'
</code>```

That returns the error 400 bad request.

答:
An old version of the Hypertext Transfer Protocol (HTTP/1.0) did not require a Host request header. See this question for details.

You can force curl to use HTTP/1.0 with the --http1.0 command line option.

Body:
I've been reviewing some nginx configuration docs and i found this:
http://nginx.org/en/docs/http/request_processing.html
I'm specifically reading the section about rejecting requests that don't provide a host name.

I'm wondering how to generate these types of requests for testing purposes, and when would these types of request come in - in real life...aka do i need to care?

What I've tried so far:

I've added the following into my nginx conf file

server {
    listen      80;
    server_name "";
    return      444;
}

Then I tried to play around with curl and send a request with an empty host header like so:

curl --verbose --header 'Host:' 'http://192.1.6.1/test/hello'

That returns the error 400 bad request.


问:
How to inject/insert a txt file into another txt file at a specific line in Python
This is a quick problem I have with Python. This is my problem here : I try to inject a txt file inside an other txt file at a specific line. This is what I tried:

# Modify TXT File
with open("avengers.txt", "w") as file1, open("guardians.txt", 'r') as file2:

    for line in file1:
        print line
        if line == 'Blackwidow':
            for line2 in file2:
                file1.write(line2)
```
<p>But it gives me something weird (A lot of break lines)</p>
<h1>avengers.txt</h1>
```This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow

The story is great
About about the movies :
....
....
```
<h1>guardians.txt</h1>
```Groot
Rocket
Star Lord
Gamora
Drax
```
<p>----- RESULT ----</p>
<p>What I want to do is just :</p>
<h1>avengers.txt</h1>
```This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow
Groot <---------------- Insert text here
Rocket
Star Lord
Gamora
Drax

The story is great
About about the movies :
....
....
```

Thank you very much for your help

答:
```<code>with open("avengers.txt", "r+") as f1, open("guardians.txt") as f2:
    line = f1.readline()
    while line:
        if line.startswith("Blackwidow"):
            offset = f1.tell()
            rest_of_file = f1.readlines()
            f1.seek(offset)
            f1.writelines(f2.readlines())
            f1.writelines(rest_of_file)
            break
        line = f1.readline()
</code>```

Body:
This is a quick problem I have with Python. This is my problem here : I try to inject a txt file inside an other txt file at a specific line. This is what I tried:

# Modify TXT File
with open("avengers.txt", "w") as file1, open("guardians.txt", 'r') as file2:

    for line in file1:
        print line
        if line == 'Blackwidow':
            for line2 in file2:
                file1.write(line2)

But it gives me something weird (A lot of break lines)

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow

The story is great
About about the movies :
....
....

guardians.txt

Groot
Rocket
Star Lord
Gamora
Drax

----- RESULT ----

What I want to do is just :

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow
Groot <---------------- Insert text here
Rocket
Star Lord
Gamora
Drax

The story is great
About about the movies :
....
....

Thank you very much for your help


问:
I need to join rows in a query (pivot)
I have some troubles with my query pivot:

SELECT *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
```

<p>This return a table </p>

```usuario | codtrab | hora                fecha       entrada salida
name1   | 600     | 08:02:00.0000000    2019-05-17  0       NULL
name1   | 600     | 16:02:00.0000000    2019-05-17  NULL    1
name2   | 200     | 08:10:00.0000000    2019-05-17  0       NULL
name2   | 200     | 16:10:00.0000000    2019-05-17  NULL    1
name3   | 400     | 08:20:00.0000000    2019-05-17  0       NULL
name3   | 400     | 16:20:00.0000000    2019-05-17  NULL    1
```

<p>I want to show the data into a table like this:</p>

```usuario codtrab hora                fecha       entrada salida
name1   600     08:02:00.0000000    2019-05-17  0       1
name2   200     08:10:00.0000000    2019-05-17  0       1
name3   400     08:20:00.0000000    2019-05-17  0       1
```

答:
I.e. you can aggregated the outcome of your pivot. I'm not sure what are your requirements regarding i.e. hora.

```<code>WITH Pivoted
AS
(
SELECT
    *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
    group by [usuario],
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
)
SELECT
  [usuario],
  [codtrab],
  min([hora]) as [hora],
  [fecha],
  max(entrada) as entrada,
  max(salida) as salida
FROM Pivoted
GROUP BY [usuario], [codtrab], [fecha] ;
</code>```

Title: I need to join rows in a query (pivot)

Body:
I have some troubles with my query pivot:

SELECT *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable

This return a table

usuario | codtrab | hora                fecha       entrada salida
name1   | 600     | 08:02:00.0000000    2019-05-17  0       NULL
name1   | 600     | 16:02:00.0000000    2019-05-17  NULL    1
name2   | 200     | 08:10:00.0000000    2019-05-17  0       NULL
name2   | 200     | 16:10:00.0000000    2019-05-17  NULL    1
name3   | 400     | 08:20:00.0000000    2019-05-17  0       NULL
name3   | 400     | 16:20:00.0000000    2019-05-17  NULL    1

I want to show the data into a table like this:

usuario codtrab hora                fecha       entrada salida
name1   600     08:02:00.0000000    2019-05-17  0       1
name2   200     08:10:00.0000000    2019-05-17  0       1
name3   400     08:20:00.0000000    2019-05-17  0       1

Body:
I.e. you can aggregated the outcome of your pivot. I'm not sure what are your requirements regarding i.e. hora.

WITH Pivoted
AS
(
SELECT
    *
FROM
(
    SELECT [usuario],
           [codtrab],
           [tna],
           [hora],
           [tipo],
           [fecha]
    FROM prueba
    group by [usuario],
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
)
SELECT
  [usuario],
  [codtrab],
  min([hora]) as [hora],
  [fecha],
  max(entrada) as entrada,
  max(salida) as salida
FROM Pivoted
GROUP BY [usuario], [codtrab], [fecha] ;


问:
How can i passing data from recyclerview to fragment
I follow a youtube tutorial to write an application. this codes is a part of my recyclerViewAdapter

```<code>        vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
            TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
            ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
            TextView dialog_detail_tv = (TextView) myDialog.findViewById(R.id.dialog_detail);
            dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
            dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
            dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
            dialog_detail_tv.setText(mData.get(vHolder.getAdapterPosition()).getDetail());
            Toast.makeText(mContext, "Test Click" + String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
            myDialog.show();
            Button dialog_add_tv = (Button) myDialog.findViewById(R.id.dialog_add);
            dialog_add_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText dialog_quantity_tv = (EditText) myDialog.findViewById(R.id.dialog_quantity);
                    quantity = dialog_quantity_tv.getText().toString();
                    name = mData.get(vHolder.getAdapterPosition()).getName()+"\n";
                    price = mData.get(vHolder.getAdapterPosition()).getPhone();
                    Intent i = new
                    Intent(getActivity(),FragmentFav.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("choices",choices);
                    bundle.putDouble("price",price);
                    i.putExtras(bundle);
                    startActivity(i);

                }
            });

        }
    });

    return vHolder;
}
</code>```

I want to Clicking the dialog_add_tv Button to pass the data to the fragment.class

```<code>public class FragmentFav extends Fragment {

View v;

public FragmentFav() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.call_fragment, container, false);
    return v;

}
</code>```

}

I try many times by using intent still happen error.

答:
Using intent you can't open fragment, use below code for open fragment and also pass data to fragment </p>

```<code>// define a framelayout in activity xml

  <FrameLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/fragment_container"></FrameLayout>

 // then write below code on the click of dialog_add_tv button

 Bundle bundle = new Bundle();
 bundle.putString("choices",choices);
 bundle.putDouble("price",price);

 FragmentFav frgFav=new  FragmentFav();
 frgFav.setArguments(bundle);

 FragmentTransaction fragmentTrasaction=getFragmentManager().beginTransaction();
 fragmentTrasaction.add(R.id.fragment_container,frgFav,"frg");
 fragmentTrasaction.commit();

// then get data in fragment like this
 String choice=getArguments().getString("choices");
 String price=getArguments().getString("price");
</code>```

Body:
I follow a youtube tutorial to write an application. this codes is a part of my recyclerViewAdapter

        vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
            TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
            ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
            TextView dialog_detail_tv = (TextView) myDialog.findViewById(R.id.dialog_detail);
            dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
            dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
            dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
            dialog_detail_tv.setText(mData.get(vHolder.getAdapterPosition()).getDetail());
            Toast.makeText(mContext, "Test Click" + String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
            myDialog.show();
            Button dialog_add_tv = (Button) myDialog.findViewById(R.id.dialog_add);
            dialog_add_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText dialog_quantity_tv = (EditText) myDialog.findViewById(R.id.dialog_quantity);
                    quantity = dialog_quantity_tv.getText().toString();
                    name = mData.get(vHolder.getAdapterPosition()).getName()+"\n";
                    price = mData.get(vHolder.getAdapterPosition()).getPhone();
                    Intent i = new
                    Intent(getActivity(),FragmentFav.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("choices",choices);
                    bundle.putDouble("price",price);
                    i.putExtras(bundle);
                    startActivity(i);

                }
            });

        }
    });

    return vHolder;
}

I want to Clicking the dialog_add_tv Button to pass the data to the fragment.class

public class FragmentFav extends Fragment {

View v;

public FragmentFav() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.call_fragment, container, false);
    return v;

}

}

I try many times by using intent still happen error.

Body:
Using intent you can't open fragment, use below code for open fragment and also pass data to fragment

// define a framelayout in activity xml

  <FrameLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/fragment_container"></FrameLayout>

 // then write below code on the click of dialog_add_tv button

 Bundle bundle = new Bundle();
 bundle.putString("choices",choices);
 bundle.putDouble("price",price);

 FragmentFav frgFav=new  FragmentFav();
 frgFav.setArguments(bundle);

 FragmentTransaction fragmentTrasaction=getFragmentManager().beginTransaction();
 fragmentTrasaction.add(R.id.fragment_container,frgFav,"frg");
 fragmentTrasaction.commit();

// then get data in fragment like this
 String choice=getArguments().getString("choices");
 String price=getArguments().getString("price");


问:
Left-hand operand of comma has no effect vs Right-hand operand of comma has no effect
I'm very beginner in C++ and I'm currently reading a book to get better in it. While reading a section about C++'s only ternary operator, I played around some code and got a question:

So, when I do this:

```<code>std::cout << "Hello ", "Mars";
</code>```

I get a warning:

warning: right operand of comma operator has no effect [-Wunused-value]

And when I do this:

```<code>std::cout << (5 > 4 ? "Hello ", "Mars" : "Bye ", "World");
</code>```

for the second operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

for the third operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

So my question is, why do I get the first warning for the second operand of ?:, while I get the second warning for the third operand of ?:?

答:
It's because of how you're using them.  If you'd written

```<code>"Mars", std::cout<<"Hello ";
</code>```

you'd get the "left operand has no effect" warning.  If you'd have assigned your expression to a variable

```<code>const char *msg = std::cout << "Hello ", "Mars";
</code>```

you wouldn't get any warnings.  When this code is executed, "Hello " would be sent to cout, and msg would be pointing to "Mars".

For the ternary operator, the right operand of the comma operator is the result of the operator, which is the expression value for the ternary operator.  Your example is the same as if you'd have written

```<code>std::cout << (5 > 4 ? "Mars" : "World");
</code>```

Body:
I'm very beginner in C++ and I'm currently reading a book to get better in it. While reading a section about C++'s only ternary operator, I played around some code and got a question:

So, when I do this:

std::cout << "Hello ", "Mars";

I get a warning:

warning: right operand of comma operator has no effect [-Wunused-value]

And when I do this:

std::cout << (5 > 4 ? "Hello ", "Mars" : "Bye ", "World");

for the second operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

for the third operand of ?: I get:

warning: left operand of comma operator has no effect [-Wunused-value]

So my question is, why do I get the first warning for the second operand of ?:, while I get the second warning for the third operand of ?:?

Body:
It's because of how you're using them.  If you'd written

"Mars", std::cout<<"Hello ";

you'd get the "left operand has no effect" warning.  If you'd have assigned your expression to a variable

const char *msg = std::cout << "Hello ", "Mars";

you wouldn't get any warnings.  When this code is executed, "Hello " would be sent to cout, and msg would be pointing to "Mars".

For the ternary operator, the right operand of the comma operator is the result of the operator, which is the expression value for the ternary operator.  Your example is the same as if you'd have written

std::cout << (5 > 4 ? "Mars" : "World");


问:
Slowness observed in obtaining connection using neo4j java jdbc driver
I have my java application deployed in websphere application server. I am successfully able to connect to neo4j from my java application using jdbc driver. But there are some performance issues with the approach i have followed. Currently neo4j server is running on Xms - 8G and Xmx-16GB. I have less amount of data that is aprox 40mb with 3100 nodes. When we test the performance over http with cypher, the performance is outstanding. But in the  java application we are using the jdbc driver to connect to neo4j via bolt. Every connection creation is taking around 100ms which is adding up delay. We are able to achieve only 160 hits/sec with this approach with 500 concurrent requests. With 500 concurrent calls, the requests are queuing up and the response time is shooting to 3 seconds. Any pointers of improvement would be helpful. (Application and neo4j are on different physical servers under the same VLAN).

Code used to create connection is below.

Class.forName("org.neo4j.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:neo4j:bolt://localhost:port") ;

答:
If you do DriverManager.getConnection() you are bypassing the WebSphere connection pool since you are getting connections directly from the JDBC driver here.

To improve performance, I recommend configuring a DataSource using the admin console, and then updating your application to get connections from the DataSource instead of directly from the driver. This way, connections will be pooled by WebSphere and you will likely get much better performance.

EDIT:
Gas pointed out in the comments that Neo4j does not provide a DataSource implementation. To work around this, you can implement a simple one like this:

public class Neo4jDataSource implements javax.sql.DataSource {

    private PrintWriter pw;

    @Override
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:neo4j:bolt://localhost:port");
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // change URL here if you want to authenticate differently for different
        // user/pass combos
        return DriverManager.getConnection("jdbc:neo4j:bolt://localhost:port");
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return pw;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        pw = out;
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new SQLFeatureNotSupportedException();
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}
```

Alternatively, if you switch to WebSphere Liberty, then you can configure a DataSource without needing to write your own DataSource.

Body:
If you do DriverManager.getConnection() you are bypassing the WebSphere connection pool since you are getting connections directly from the JDBC driver here.

To improve performance, I recommend configuring a DataSource using the admin console, and then updating your application to get connections from the DataSource instead of directly from the driver. This way, connections will be pooled by WebSphere and you will likely get much better performance.

EDIT:
Gas pointed out in the comments that Neo4j does not provide a DataSource implementation. To work around this, you can implement a simple one like this:

public class Neo4jDataSource implements javax.sql.DataSource {

    private PrintWriter pw;

    @Override
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:neo4j:bolt://localhost:port");
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // change URL here if you want to authenticate differently for different
        // user/pass combos
        return DriverManager.getConnection("jdbc:neo4j:bolt://localhost:port");
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return pw;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        pw = out;
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new SQLFeatureNotSupportedException();
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

Alternatively, if you switch to WebSphere Liberty, then you can configure a DataSource without needing to write your own DataSource.


问:
Do the dependencies in build.gradle generated automatically?
Does gradle work like go mod ? First importing some dependencies in java file such as import org.apache.hadoop.mapreduce.Mapper, then calling gradle build and gradle would generate dependencies in build.gradle automatically, also download all the jars needed to gradle cache.

Or, all the denpendencies we need must add to build.gradle manully? Which version should append to the denpendency, search in the maven repo one by one?

Thank~

答:
Gradle uses the dependencies declared in the build file to create the compile classpath. Similarly it will use test dependencies for the test compile classpath and the test runtime classpath.

So you have to declare the dependencies first, including figuring out which version you want to use in your project, and then you will be able to compile and run code that leverages these libraries.


问:
Javascript onClick Before After Image effect with slider
I want do a before/after image effect slider like, when click on a image it will replace with another image. And again when click on replace image it will back to previous image.

Onclick function can change image only at once.
This is my working demo Codepen

```<code>  <img src="https://i.ibb.co/ccsnkJS/image-11.jpg"
    onclick="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';">
</code>```

Before that I've tried with mouseover and mouseout function. Demo Codepen

```<code><img src="https://i.ibb.co/wNsz0MW/image-11.jpg" onmouseover="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';" onmouseout="this.src = 'https://i.ibb.co/ccsnkJS/image-11.jpg';">
</code>```

But unfortunately mouseover and mouseout function does not work on mobile device. Using mouseover and mouseout , when tap on screen new image replace but when I tap on screen again image not back to previous image.

It would be a best solution if I can achieve it with mouseOver and mouseOut in all device.

答:
If you want to have all your code defined within the html element itself, things are a little tricky.

Basically you can use the html data-* attribute to store arbitrary data - like the url for the second image.

```<code><img src="https://i.ibb.co/ccsnkJS/image-11.jpg" data-secondImg="https://i.ibb.co/R7d7Lw6/image-13.jpg">
</code>```

Inside the onclick handler we need to check which url is currently set for the img element's src property and compare it to data-secondImg. If it's different use the url from secondImg and store the current url in a backup variable. If it's not different use the url from the backup variable.

Here's an example:

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

<h2>Followup</h2>

<p>If you want to use multiple events - onMouseOver and onClick - which should trigger the same action and in case you have a lot of images, it's better to define the action as a function once and just reference it by it's name.</p>

<p>This example reacts to both onMouseOver and onClick events:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function swap(t) {
  if (t.src != t.getAttribute('data-secondImg')) {
    t.old = t.src;
    t.src = t.getAttribute('data-secondImg')
  } else {
    t.src = t.old;
  }
}</code>```

```

Body:
I want do a before/after image effect slider like, when click on a image it will replace with another image. And again when click on replace image it will back to previous image.

Onclick function can change image only at once.
This is my working demo Codepen

Before that I've tried with mouseover and mouseout function. Demo Codepen

But unfortunately mouseover and mouseout function does not work on mobile device. Using mouseover and mouseout , when tap on screen new image replace but when I tap on screen again image not back to previous image.

It would be a best solution if I can achieve it with mouseOver and mouseOut in all device.

Body:
If you want to have all your code defined within the html element itself, things are a little tricky.

Basically you can use the html data-* attribute to store arbitrary data - like the url for the second image.

<img src="https://i.ibb.co/ccsnkJS/image-11.jpg" data-secondImg="https://i.ibb.co/R7d7Lw6/image-13.jpg">

Inside the onclick handler we need to check which url is currently set for the img element's src property and compare it to data-secondImg. If it's different use the url from secondImg and store the current url in a backup variable. If it's not different use the url from the backup variable.

Here's an example:

<img src="https://i.ibb.co/ccsnkJS/image-11.jpg" onclick="if(this.src!=this.getAttribute('data-secondImg')){this.old=this.src;this.src=this.getAttribute('data-secondImg')}else{this.src=this.old;}" data-secondImg="https://i.ibb.co/R7d7Lw6/image-13.jpg">

Followup

If you want to use multiple events - onMouseOver and onClick - which should trigger the same action and in case you have a lot of images, it's better to define the action as a function once and just reference it by it's name.

This example reacts to both onMouseOver and onClick events:

function swap(t) {
  if (t.src != t.getAttribute('data-secondImg')) {
    t.old = t.src;
    t.src = t.getAttribute('data-secondImg')
  } else {
    t.src = t.old;
  }
}

<img src="https://picsum.photos/id/88/64/64" onClick="swap(this)" onMouseOver="swap(this)" data-secondImg="https://picsum.photos/id/76/64/64">


问:
How to get most frequent word or in case of tie first alphabetically, from dictionary.values() Python
Trying to get the most frequent value for each key from a dictionary like:

{'cars': ['sedan', 'sedan', 'van', 'van'], 'snack': ['chips', 'chips', 'cheetos'], 'computer': ['laptop', 'desktop']}

However, if there is a tie it should return the first word in value list alphabetically.

Have already tried collections.Counter but that returns arbitrary values if there's a tie. I'm also aware that there are posts that show how to find the most frequent values for dictionaries, but they don't address alphabet ordering in case of a tie.

For instance, the above dictionary should return:

{'cars': 'sedan', 'snack':'chips', 'computer':'desktop'}

Any help is much appreciated.

答:
I would suggest something that is not a one-liner. One-liners might proof that you are a good coder, but are really bad coding style.

This is the perfect time to write a helper function:

from collections import Counter

def most_common(items):
    # Protect against empty input
    if not items:
        return None

    # This does the actual computing
    counter = Counter(items)

    # Initialize the result variables
    result, max_count = counter.most_common(1)[0]

    # most_common are sorted, so we can stop once the count is not the max count
    for elem, count in counter.most_common():
        if count != max_count:
            break
        # replace with alphabetically better result
        result = min(result,elem)

    return result

inp = {'cars': ['sedan', 'sedan', 'van', 'van'], 'snack': ['chips', 'chips', 'cheetos'], 'computer': ['laptop', 'desktop']}

results = {key: most_common(val) for key, val in inp.items()}
print(results)
# {'cars': 'sedan', 'snack': 'chips', 'computer': 'desktop'}
```


问:
makeObjectsPerformSelector:
I want to make all objects in an array perform a selector. I've discovered the appropriately named makeObjectsPerformSelector: method, but I have a question with it. If I use it on an array, will it change the existing array or return a new one? If it modifies the existing object, what be the easiest way to return a new array with the selector applied?

答:
If I use it on an array, will it change the existing array or return a new one?

No.

First off, read the signature:

```<code>- (void)makeObjectsPerformSelector:(SEL)aSelector
</code>```

void, with no stars after it, means “does not return anything”.

Second, note that this is a method of NSArray, which is an immutable class. Therefore, makeObjectsPerformSelector: does not mutate the receiving array, because that's impossible.

There is NSMutableArray, and since that's a subclass of NSArray, it inherits makeObjectsPerformSelector:. However, if NSMutableArray changed that method's behavior, its documentation would have its own listing for the method (see the many definitions of init in various classes' documentation). There's no such listing, so you can safely (and correctly) infer that -[NSMutableArray makeObjectsPerformSelector:] works exactly the same way as -[NSArray makeObjectsPerformSelector:].

The objects can modify themselves in response to your message, but the array itself will contain the same objects after makeObjectsPerformSelector: as before it.

OwnerDisplayName: Allyn

Title: makeObjectsPerformSelector:

Body:
If I use it on an array, will it change the existing array or return a new one?

No.

First off, read the signature:

- (void)makeObjectsPerformSelector:(SEL)aSelector

void, with no stars after it, means “does not return anything”.

Second, note that this is a method of NSArray, which is an immutable class. Therefore, makeObjectsPerformSelector: does not mutate the receiving array, because that's impossible.

There is NSMutableArray, and since that's a subclass of NSArray, it inherits makeObjectsPerformSelector:. However, if NSMutableArray changed that method's behavior, its documentation would have its own listing for the method (see the many definitions of init in various classes' documentation). There's no such listing, so you can safely (and correctly) infer that -[NSMutableArray makeObjectsPerformSelector:] works exactly the same way as -[NSArray makeObjectsPerformSelector:].

The objects can modify themselves in response to your message, but the array itself will contain the same objects after makeObjectsPerformSelector: as before it.

OwnerDisplayName: Peter Hosey

ContentLicense: CC BY-SA 2.5


问:
PyCharm 2019.01 and Anaconda 3 Don't Work Together
I recently upgraded to the latest version of PyCharm (2019.01) and my Anaconda 3 install no longer starts up in the Python Console. I get the following error:

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevconsole.py", line 5, in <module>
    from _pydev_comm.rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\rpc.py", line 4, in <module>
    from _pydev_comm.server import TSingleThreadedServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\server.py", line 4, in <module>
    from _shaded_thriftpy.server import TServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\server.py", line 9, in <module>
    from _shaded_thriftpy.transport import (
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\__init__.py", line 57, in <module>
    from .sslsocket import TSSLSocket, TSSLServerSocket  # noqa
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\sslsocket.py", line 7, in <module>
    import ssl
  File "C:\Users\bnielson\AppData\Local\Continuum\anaconda3\lib\ssl.py", line 98, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: DLL load failed: The specified module could not be found.
</code>```

I have Googled this and there are a number of sites that talk about similar errors but none of their fixes have worked for me so far.

Strangely, I can go to the Terminal tab and start up Anaconda 3's Python Manually and this works just fine.

I have tried uninstalling and reinstalling Anaconda 3 and PyCharm. I have tried not importing previous settings so that I'm getting a fresh start. None of this has worked.

Anaconda 2.7 works just fine.

I tried this link already:

Python 3.7 anaconda environment - import _ssl DLL load fail error

I'm not even clear why I'd be getting this error in the first place, so it's hard to troubleshoot.

Note: I am intentionally trying to start up Anaconda 3 as originally installed and not a Conda or Virtual Environment (as this loses all the installed items that come as default.)

I am on Windows.

答:
Per our discussions in comments:

There's a new kid on the block. Suggest that you consider VSCode. Although it is from Microsoft, it is free and built on open source. It also has integrated Git, debugging and extensions. Also has an active and responsive issues forum on github for reporting bugs and requesting features.

Steps to happiness: (a) uninstall PyCharm (b) completely uninstall Anaconda (c) install VSCode (d) install Python extension (e) watch a few YouTube videos to see how it works (f) never look back.

Suggest you also review this SO question/answer for important tweaking tip

Note that it is imperative to fully uninstall Anaconda, and install Python comme il faut, as Anaconda will likely continue to cause you grief if you don't.

Extensions are installed within the app, just using the square boxy icon on the left-side toolbar. I suggest you consider:

Python extension

Code Runner

Bracket Pair Colorizer

highlight-words

Numbered Bookmarks

Git History /and/ GitLens Git supercharged (if you use git)

VSCode keyboard cheatsheet

Important keystrokes to know off-the-start:

F9 - add/remove breakpoint (right-click on breakpoint to add conditions)

F5 - run in debugger mode

Ctrl Alt n - run full speed (via CodeRunner extension)

Body:
I recently upgraded to the latest version of PyCharm (2019.01) and my Anaconda 3 install no longer starts up in the Python Console. I get the following error:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevconsole.py", line 5, in <module>
    from _pydev_comm.rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\rpc.py", line 4, in <module>
    from _pydev_comm.server import TSingleThreadedServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\server.py", line 4, in <module>
    from _shaded_thriftpy.server import TServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\server.py", line 9, in <module>
    from _shaded_thriftpy.transport import (
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\__init__.py", line 57, in <module>
    from .sslsocket import TSSLSocket, TSSLServerSocket  # noqa
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\sslsocket.py", line 7, in <module>
    import ssl
  File "C:\Users\bnielson\AppData\Local\Continuum\anaconda3\lib\ssl.py", line 98, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: DLL load failed: The specified module could not be found.

I have Googled this and there are a number of sites that talk about similar errors but none of their fixes have worked for me so far.

Strangely, I can go to the Terminal tab and start up Anaconda 3's Python Manually and this works just fine.

I have tried uninstalling and reinstalling Anaconda 3 and PyCharm. I have tried not importing previous settings so that I'm getting a fresh start. None of this has worked.

Anaconda 2.7 works just fine.

I tried this link already:

Python 3.7 anaconda environment - import _ssl DLL load fail error

I'm not even clear why I'd be getting this error in the first place, so it's hard to troubleshoot.

Note: I am intentionally trying to start up Anaconda 3 as originally installed and not a Conda or Virtual Environment (as this loses all the installed items that come as default.)

I am on Windows.


问:
Python .count String function - Counting an exact word occurrence from string or line
I want to count the word occurrence from a string. But I only want to count the exact occurrence, not from a substring.

For eg. If the string which I want to count is -> "This is good" and If the word I want to count the occurrence is "is", I only want to get occurrence of is to be 1 not 2. But my code counts "is" from "This" word. How can I do this. Sorry for my poor english.

text = "This is good"
text.count("is")

>>> 2
```

<pre class="lang-py prettyprint-override"><code>text = "This is good"
text.count("is")

>>> 1
</code>```

答:
You first must get the individual words by splitting the string by whitespace:

```<code>words = text.split()
</code>```

Now sum all of the items in the list where the word equals the string you are checking:

```<code>sum(char for char in words if char == string_to_check)
</code>```

In a function, you obtain the following:

```<code>def count(string, check):
    return sum(char for char in string.split() if char == check)
</code>```

Body:
I want to count the word occurrence from a string. But I only want to count the exact occurrence, not from a substring.

For eg. If the string which I want to count is -> "This is good" and If the word I want to count the occurrence is "is", I only want to get occurrence of is to be 1 not 2. But my code counts "is" from "This" word. How can I do this. Sorry for my poor english.

text = "This is good"
text.count("is")

>>> 2

text = "This is good"
text.count("is")

>>> 1

Body:
You first must get the individual words by splitting the string by whitespace:

words = text.split()

Now sum all of the items in the list where the word equals the string you are checking:

sum(char for char in words if char == string_to_check)

In a function, you obtain the following:

def count(string, check):
    return sum(char for char in string.split() if char == check)


问:
How do I create multiple chats using the same app key?
We allow our creators to create their own site, so how do we get one chat per site? How do we create multiple chats using one single getsteam app? Each site will have multiple users also. The users of each site have to participate in the corresponding chat.</p>

答:
One simple approach is to namespace users and channels with sites' unique ID. This way you can keep everything under one account and use the same API key without mixing data.

When doing so, make sure to enforce a naming convention for the namespace (ie. site-{id}-{user_id}) and only create channels and users server-side.


问:
Python: symbolic use of hyp2f1 with sympy
In Python, I want to use the hypergeometric function hyp2f1 while keeping at least one symbolic argument. However, there is a TypeError

cannot create mpf from d

where d is the (last) argument of the hypergeometric function.

Someone asked a similar question

sympy and mpmath give "TypeError: cannot create mpf" when using the erf() function within solveset()

after encountering the same problem with the error function erf.
The proposed solution was to use the mpmath library instead of the sympy library, but mpmath cannot be used while keeping arguments symbolic.

I also tried to import mpmath and sympy together as proposed in the sympy documentation:

from sympy.mpmath import *
```

<p>https://docs.sympy.org/0.7.6/modules/mpmath/functions/hypergeometric.html#common-hypergeometric-series</p>

<p>But this is not accepted, as the output is:</p>

<blockquote>
  <p>ModuleNotFoundError: No module named `sympy.mpmath'</p>
</blockquote>

<p>My code is</p>

<pre class="lang-py prettyprint-override"><code>from sympy import *

d = Symbol('d')

hyp2f1(1,1,1,d)
</code>```

I hoped to get a simplification to 1/(1-d) or at least hoped that Python can 'store' hyp2f1(1,1,1,d) for symbolic manipulations.

I get an error

TypeError: cannot create mpf from d

The bottom line is, with sympy imported, Python cannot use hyp2f1 with symbolic arguments.

答:
Use the SymPy hyper function:

In [4]: from sympy import hyper, simplify, Symbol

In [5]: d = Symbol('d')

In [6]: f = hyper([1, 1], [1], d)

In [7]: f
Out[7]:
 ┌─  ⎛1, 1 │  ⎞
 ├─  ⎜     │ d⎟
2╵ 1 ⎝ 1   │  ⎠

In [8]: simplify(f)
Out[8]:
  1
─────
1 - d
```

Body:
In Python, I want to use the hypergeometric function hyp2f1 while keeping at least one symbolic argument. However, there is a TypeError

cannot create mpf from d

where d is the (last) argument of the hypergeometric function.

Someone asked a similar question

sympy and mpmath give "TypeError: cannot create mpf" when using the erf() function within solveset()

after encountering the same problem with the error function erf.
The proposed solution was to use the mpmath library instead of the sympy library, but mpmath cannot be used while keeping arguments symbolic.

I also tried to import mpmath and sympy together as proposed in the sympy documentation:

from sympy.mpmath import *

https://docs.sympy.org/0.7.6/modules/mpmath/functions/hypergeometric.html#common-hypergeometric-series

But this is not accepted, as the output is:

ModuleNotFoundError: No module named `sympy.mpmath'

My code is

from sympy import *

d = Symbol('d')

hyp2f1(1,1,1,d)

I hoped to get a simplification to 1/(1-d) or at least hoped that Python can 'store' hyp2f1(1,1,1,d) for symbolic manipulations.

I get an error

TypeError: cannot create mpf from d

The bottom line is, with sympy imported, Python cannot use hyp2f1 with symbolic arguments.


答:
if you want to use this method you can just insert space(if you will alway searching for the word)

```<code>text = "This is good"
print (text.count(" is"))
</code>```

output:

1

the better solution will be:

```<code>text = "This is good"
num = text.split().count('is')
print (num)
</code>```

output:

1

to make this counter be case-insensitive, for example in this case:

```<code>text = "Is this ok, it is just example is"
num = text.lower().split().count('is')
print (num)
</code>```

output:

3

The method lower() returns a copy of the string in which all
  case-based characters have been lowercased.

Syntax:

```<code>str.lower()
</code>```

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When max is specified, the list will contain the specified
  number of elements plus one.

Syntax:

```<code>string.split(separator, max)
</code>```

Title: Python .count String function - Counting an exact word occurrence from string or line

Body:
if you want to use this method you can just insert space(if you will alway searching for the word)

text = "This is good"
print (text.count(" is"))

output:

1

the better solution will be:

text = "This is good"
num = text.split().count('is')
print (num)

output:

1

to make this counter be case-insensitive, for example in this case:

text = "Is this ok, it is just example is"
num = text.lower().split().count('is')
print (num)

output:

3

The method lower() returns a copy of the string in which all
  case-based characters have been lowercased.

Syntax:

str.lower()

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When max is specified, the list will contain the specified
  number of elements plus one.

Syntax:

string.split(separator, max)


问:
How to replace a column value which is missing?
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

```<code>                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN
</code>```

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

```<code>df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)
</code>```

Then I tried:

```<code>df_74034.at[0, 'data/hora'] = 0
</code>```

And I got:

```<code>A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value
</code>```

Thanks for any help!

答:
Try:</p>

```<code>missing_hour = df['data/hora'].isna()

df.loc[missing_hour, 'data/hora'] = df.loc[missing_hour,'HumTechRoom']
</code>```

Body:
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)

Then I tried:

df_74034.at[0, 'data/hora'] = 0

And I got:

A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value

Thanks for any help!

Body:
Try:

missing_hour = df['data/hora'].isna()

df.loc[missing_hour, 'data/hora'] = df.loc[missing_hour,'HumTechRoom']


问:
Return type is () -> MultipartBody.Part! instead of MultipartBody.Part
I am relatively new to lambda expressions and would love it if somebody could explain why the return type is different from I am expecting. What is () -> MultipartBody.Part! anyways?

```<code>Single.just{
    val file = bitmapToFile(context, fileName, image)
    // create RequestBody instance from file
    val requestFile = RequestBody.create(
        MediaType.parse("multipart/form-data")
        , file
    )

    // MultipartBody.Part is used to send also the actual file name
    return@just MultipartBody.Part.createFormData("picture", file.name, requestFile)
}
</code>```

答:
() -> MultipartBody.Part describes a functional type.
It describes a function, that takes in no arguments and returns a MultipartBody.Part.
So the compiler is complaining, that you are returning a function, rather than the MultipartBody.Part, that it expects.

My guess is, that Single.just() does not return MultipartBody.Part but rather a function returning that? I am not familiar with the RX framework, so I can not be to sure here.

Body:
I am relatively new to lambda expressions and would love it if somebody could explain why the return type is different from I am expecting. What is () -> MultipartBody.Part! anyways?

Single.just{
    val file = bitmapToFile(context, fileName, image)
    // create RequestBody instance from file
    val requestFile = RequestBody.create(
        MediaType.parse("multipart/form-data")
        , file
    )

    // MultipartBody.Part is used to send also the actual file name
    return@just MultipartBody.Part.createFormData("picture", file.name, requestFile)
}


问:
Spacing between groups of bars in histogram
When I produce histograms in ggplot2 where the bar positions are dodge, I expect something like this where there is space between the groups of bars (i.e. notice the white space between each groups of red/green pairs):

I'm having a hard time producing the same effect when I build a histogram with continuous data. I can't seem to add space between the groups of bars, and instead, everything gets squashed together. As you can see, it makes it visually difficult to compare the red/green pairs:

To reproduce my problem, I created a sample data set here: https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=0

Code to reproduce:

```<code>data <- read.csv("https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=1")

ggplot(data, aes(x = soldPrice, fill = month)) +
    geom_histogram(binwidth=1e5, position=position_dodge()) +
    labs(x="Sold Price", y="Sales", fill="") +
    scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
    theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
</code>```

How can I add white space between the groups of red/green pairs?

答:
Alternative 1: overlapping bars with geom_histogram()

From ?position_dodge():

Dodging preserves the vertical position of an geom while adjusting the horizontal position

This function accepts a width argument that determines the space to be created.

To get what I think you want, you need to supply a suitable value to position_dodge(). In your case, where binwidth=1e5, you might play with e.g. 20% of that value: position=position_dodge(1e5-20*(1e3)).
(I left the rest of your code untouched.)

You could use the following code:

```<code>ggplot(data, aes(x = soldPrice, fill = month)) +
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3))) + ### <-----
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
</code>```

yielding this plot:

Alternative 2: use ggplot-object and render with geom_bar

geom_histogram() was not designed to produce what you want. geom_bar() on the other hand provides the flexibility you need.

You can generate the histogram with geom_histogram and save it in an ggplot-object. Then, you generate the plotting information with ggplot_build(). Now,
you may use the histogram plotting information in the object to generate a bar plot with geom_bar()

```<code>## save ggplot object to h
h <- ggplot(data, aes(x = soldPrice, fill = month)) +
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3)))

## get plotting information as data.frame
h_plotdata <- ggplot_build(h)$data[[1]]
h_plotdata$group <- as.factor(h_plotdata$group)
levels(h_plotdata$group) <- c("May 2018", "May 2019")

## plot with geom_bar
ggplot(h_plotdata, aes(x=x, y=y, fill = group)) +
  geom_bar(stat = "identity") +
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
</code>```

yielding this graph:

Please, let me know whether this is what you want.

Body:
When I produce histograms in ggplot2 where the bar positions are dodge, I expect something like this where there is space between the groups of bars (i.e. notice the white space between each groups of red/green pairs):

I'm having a hard time producing the same effect when I build a histogram with continuous data. I can't seem to add space between the groups of bars, and instead, everything gets squashed together. As you can see, it makes it visually difficult to compare the red/green pairs:

To reproduce my problem, I created a sample data set here: https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=0

Code to reproduce:

data <- read.csv("https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=1")

ggplot(data, aes(x = soldPrice, fill = month)) +
    geom_histogram(binwidth=1e5, position=position_dodge()) +
    labs(x="Sold Price", y="Sales", fill="") +
    scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
    theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

How can I add white space between the groups of red/green pairs?

Body:
Alternative 1: overlapping bars with geom_histogram()

From ?position_dodge():

Dodging preserves the vertical position of an geom while adjusting the horizontal position

This function accepts a width argument that determines the space to be created.

To get what I think you want, you need to supply a suitable value to position_dodge(). In your case, where binwidth=1e5, you might play with e.g. 20% of that value: position=position_dodge(1e5-20*(1e3)).
(I left the rest of your code untouched.)

You could use the following code:

ggplot(data, aes(x = soldPrice, fill = month)) +
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3))) + ### <-----
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

yielding this plot:

Alternative 2: use ggplot-object and render with geom_bar

geom_histogram() was not designed to produce what you want. geom_bar() on the other hand provides the flexibility you need.

You can generate the histogram with geom_histogram and save it in an ggplot-object. Then, you generate the plotting information with ggplot_build(). Now,
you may use the histogram plotting information in the object to generate a bar plot with geom_bar()

## save ggplot object to h
h <- ggplot(data, aes(x = soldPrice, fill = month)) +
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3)))

## get plotting information as data.frame
h_plotdata <- ggplot_build(h)$data[[1]]
h_plotdata$group <- as.factor(h_plotdata$group)
levels(h_plotdata$group) <- c("May 2018", "May 2019")

## plot with geom_bar
ggplot(h_plotdata, aes(x=x, y=y, fill = group)) +
  geom_bar(stat = "identity") +
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

yielding this graph:

Please, let me know whether this is what you want.


问:
combine files with similar substring in filename
I would like to combine files that have similar ID before the FIRST underscore "_". Below is an example of two such files. I think cat is the tool to use.

in:

```<code>EIV105_S21_R1.fastq.gz
EIV105_2_S117_R1.fastq.gz
EIV10_S13_R1.fastq.gz
EIV10_2_S109_R1.fastq.gz
</code>```

out:

```<code>EIV105_R1.fastq.gz
EIV10_R1.fastq.gz
</code>```

答:
```<code>#!/bin/sh

suffix=R1.fastq.gz

find *_?*_$suffix | sed 's/_.*//' | sort -u |\
while read id; do
    cat "$id"_?*_$suffix > "$id"_$suffix
    # gzip -cd "$id"_?*_$suffix | gzip > "$id"_$suffix
done
</code>```

find lists the input filenames

sed extracts the ids

sort outputs only unique ids

while loops over the unique ids (assuming they don't contain unusual characters like backslash or newline)

cat creates outputs

gzip may give better compression than cat

Body:
I would like to combine files that have similar ID before the FIRST underscore "_". Below is an example of two such files. I think cat is the tool to use.

in:

EIV105_S21_R1.fastq.gz
EIV105_2_S117_R1.fastq.gz
EIV10_S13_R1.fastq.gz
EIV10_2_S109_R1.fastq.gz

out:

EIV105_R1.fastq.gz
EIV10_R1.fastq.gz

Body:
#!/bin/sh

suffix=R1.fastq.gz

find *_?*_$suffix | sed 's/_.*//' | sort -u |\
while read id; do
    cat "$id"_?*_$suffix > "$id"_$suffix
    # gzip -cd "$id"_?*_$suffix | gzip > "$id"_$suffix
done

find lists the input filenames

sed extracts the ids

sort outputs only unique ids

while loops over the unique ids (assuming they don't contain unusual characters like backslash or newline)

cat creates outputs

gzip may give better compression than cat


问:
Bootstrap col is adding extra height instead of wrapping img tightly
I have an img nested in a col. However, the col is larger than the image. It's as if there is padding at the bottom, but I don't see any. Here is a screenshot: https://imgur.com/a/K8iRWLf

There is another img nested within a separate col in the same row, but that img is the exact same size.

EDIT* I tried two fixes per a suggestion: display: block and vertical-align: bottom (separately), neither of which worked.

```<code> .img-shrink {
    max-width: 80%;
    max-height: 80%;
  }
</code>```

```<code> <div class="row justify-content-center">
                <div class="col-3 body-padding text-center">
                    <img class="img-fluid img-shrink" src="img/dog-beer.jpg" alt="beer">
                </div>
                <div class="col-3 body-padding text-center">
                    <img class="img-fluid img-shrink" src="img/dog-treats.jpg" alt="treats">
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-2 align-text-top">
                    <h4 class="product-header">Lorem Ipsum</h4>
                </div>
                <div class="col-2 align-text-top">
                    <h4 class="product-header">Lorem Ipsum</h4>
                </div>
            </div>
</code>```

答: After playing around, I figured it out. The col is sized to the actual size of my image, not the max-width/height: 80% image that the browser renders. If anyone knows a way around this without resizing the original image, please enlighten me.</p>

Body:
I have an img nested in a col. However, the col is larger than the image. It's as if there is padding at the bottom, but I don't see any. Here is a screenshot: https://imgur.com/a/K8iRWLf

There is another img nested within a separate col in the same row, but that img is the exact same size.

EDIT* I tried two fixes per a suggestion: display: block and vertical-align: bottom (separately), neither of which worked.

 .img-shrink {
    max-width: 80%;
    max-height: 80%;
  }

Lorem Ipsum

Lorem Ipsum


问:
How to do a search for PID? (bash)
assuming that I know the PID of a process and want to do a search in ps -A, how do I do it? I tried doing this:

```<code>echo "Enter PID to search: "
read PID
search=$(ps -A | grep -v PID | awk '{print $1}')
</code>```

This returns me with a long list of PIDs. So how can I get use each individual value of the output and do:

```<code>if [ "$PID" = "*each_value_in_search_list*" ]; then
........
</code>```

In this case i'm trying to compare what the user enters with the output of my command, so how do I do it? Am I doing the correct way in the first place? Or is there any other way to do this?

Thanks for your help, everyone who answered this question. (:

答:
```<code><?php
echo shell_exec("ps -Ao cmd,pid|grep -P ' {$pid}$'");
?>
</code>```

Title: How to do a search for PID? (bash)

Body:
assuming that I know the PID of a process and want to do a search in ps -A, how do I do it? I tried doing this:

echo "Enter PID to search: "
read PID
search=$(ps -A | grep -v PID | awk '{print $1}')

This returns me with a long list of PIDs. So how can I get use each individual value of the output and do:

if [ "$PID" = "*each_value_in_search_list*" ]; then
........

In this case i'm trying to compare what the user enters with the output of my command, so how do I do it? Am I doing the correct way in the first place? Or is there any other way to do this?

Thanks for your help, everyone who answered this question. (:


问:
MS Access Automatically Generate Random Number
I want to generate a 6-digit random number in a table row in MS Access, is it possible?

I've tried to make a random number for a user's unique ID in a table, but sometimes it generates a negative number like -43543435.

答:
You can create random numbers between limits with this:

```<code>Int((maxlimit - minlimit + 1) * Rnd + minlimit)
</code>```

In your case, you want a 6 digit number, so:

```<code>minlimit = 100000
</code>```

and

```<code>maxlimit = 999999
</code>```

So:

```<code>Int(900000 * Rnd + 100000)
</code>```

You can find more about the function Rnd here:

https://support.office.com/en-us/article/rnd-function-503cd2e4-3949-413f-980a-ed8fb35c1d80

Body:
You can create random numbers between limits with this:

Int((maxlimit - minlimit + 1) * Rnd + minlimit)

In your case, you want a 6 digit number, so:

minlimit = 100000

and

maxlimit = 999999

So:

Int(900000 * Rnd + 100000)

You can find more about the function Rnd here:

https://support.office.com/en-us/article/rnd-function-503cd2e4-3949-413f-980a-ed8fb35c1d80


问:
how to remove duplicate values from Array using reactjs?
hello im beginnger in javascript also in react. can somebody help me to solve this. i just try this project from reactjs blog but i just wanna try solve this with my way

todoList.js

```<code>const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

export default todoList
</code>```

FilterTableProdcTable.js

```<code>class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        todoList.forEach(elem=>{
            if(aw.indexOf(elem.category) === -1){
                aw.push(
                    <li key={elem.name}> {elem.category}</li>
                )
            }
        })

        return(
            <div>
                {aw}
            </div>
        )
    }
}
</code>```

the result still same, all duplicate values still show on my screen. can somebody help me?

im sorry about my broken english, but thank you all

答:
Your code would be fine, the only problem is that your aw array is getting filled with li attributes, they are not strings that contain the elem.category. Perhaps if you kept track of different arrays, you could check the indexOf that. There's also the innerHTML or textContent you could use on the li attributes. Maybe consider something like this:

```<code>const aw = [];
const categories = [];
todoList.forEach(elem=>{
    if(!~categories.indexOf(elem.category)) { // tilde changes the result of indexOf to a boolean
        aw.push(
            <li key={elem.name}> {elem.category}</li>
        )
        categories.push(elem.category)
    }
})
</code>```

Body:
hello im beginnger in javascript also in react. can somebody help me to solve this. i just try this project from reactjs blog but i just wanna try solve this with my way

todoList.js

const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

export default todoList

FilterTableProdcTable.js

class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        todoList.forEach(elem=>{
            if(aw.indexOf(elem.category) === -1){
                aw.push(

 {elem.category}

                )
            }
        })

        return(

                {aw}

        )
    }
}

the result still same, all duplicate values still show on my screen. can somebody help me?

im sorry about my broken english, but thank you all

Body:
Your code would be fine, the only problem is that your aw array is getting filled with li attributes, they are not strings that contain the elem.category. Perhaps if you kept track of different arrays, you could check the indexOf that. There's also the innerHTML or textContent you could use on the li attributes. Maybe consider something like this:

const aw = [];
const categories = [];
todoList.forEach(elem=>{
    if(!~categories.indexOf(elem.category)) { // tilde changes the result of indexOf to a boolean
        aw.push(
            <li key={elem.name}> {elem.category}</li>
        )
        categories.push(elem.category)
    }
})


问:
libcouchbase not instaling on Red Hat Enterprise Linux Server release 6.6
Following the documentation for RHEL/CentOS, this is how I try to install libcouchbase:

wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-6-x86_64.rpm
sudo rpm -iv couchbase-release-1.0-6-x86_64.rpm
sudo yum install libcouchbase-devel libcouchbase2-bin gcc gcc-c++
```

<p>However <code>libcouchbase-devel</code> and <code>libcouchbase2-bin</code> fail with:</p>

```Running rpm_check_debug
Running Transaction Test

Transaction Check Error:
  file /usr/lib64/libcouchbase.so.2.0.65 conflicts between attempted installs of libcouchbase-2.10.3-1.el6.remi.x86_64 and libcouchbase2-core-2.10.3-1.el6.x86_64

Error Summary
-------------
```

I tried installing those packages one at a time but, if I install libcouchbase-devel first it succeeds and libcouchbase2-bin fail. If I remove what I installed and do libcouchbase2-bin first it succeeds, but thenlibcouchbase-devel` fails.

This clearly points to a conflict somewhere, but I am unsure what this conflict is exactly

答:
I removed all packages that have couchbase in their name: yum remove packagename

Then, yum install libcouchbase libcouchbase-devel

Body:
Following the documentation for RHEL/CentOS, this is how I try to install libcouchbase:

wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-6-x86_64.rpm
sudo rpm -iv couchbase-release-1.0-6-x86_64.rpm
sudo yum install libcouchbase-devel libcouchbase2-bin gcc gcc-c++

However libcouchbase-devel and libcouchbase2-bin fail with:

Running rpm_check_debug
Running Transaction Test

Transaction Check Error:
  file /usr/lib64/libcouchbase.so.2.0.65 conflicts between attempted installs of libcouchbase-2.10.3-1.el6.remi.x86_64 and libcouchbase2-core-2.10.3-1.el6.x86_64

Error Summary
-------------

I tried installing those packages one at a time but, if I install libcouchbase-devel first it succeeds and libcouchbase2-bin fail. If I remove what I installed and do libcouchbase2-bin first it succeeds, but thenlibcouchbase-devel` fails.

This clearly points to a conflict somewhere, but I am unsure what this conflict is exactly


问:
Correct sed syntax for variables
I'm getting a syntax error when running sed in my bash script. Non of the similar issues on here have resolved my problem.

I need to update a line in a config for a VPN connection.

```<code>serverconfig='vpnsrv.tcp.ovpn'
auth='auth-user-pass'
update='../login.conf'

sed -i.bak "s/$auth/$update" $serverconfig

# I have also tried these:
#sed -i.bak 's/auth-user-pass/auth-user-pass "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass '"${update}"'' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "$update"' $serverconfig
#sed -i.bak 's/'"$auth"'/'"$auth $update"' $serverconfig
# sed: -e expression #1, char 32: unterminated `s' command
</code>```

Line in file "auth-user-pass" should found and replaced with "auth-user-pass ../login.conf". I'm unable to get passed the syntax error: sed: -e expression #1, char [#]: unterminated `s' command

答:
Sed can use almost any character as its 'delimiter'. You're having trouble because your chosen delimiter / appears in your variable.

```<code>sed -i.bak "s,$auth,$update" $serverconfig
</code>```

You can also perform this substitution as many times as possible with the global operation:

```<code>sed -i.back "s,$auth,$update,g" $serverconfig
</code>```

Title: Correct sed syntax for variables

Body:
I'm getting a syntax error when running sed in my bash script. Non of the similar issues on here have resolved my problem.

I need to update a line in a config for a VPN connection.

serverconfig='vpnsrv.tcp.ovpn'
auth='auth-user-pass'
update='../login.conf'

sed -i.bak "s/$auth/$update" $serverconfig

# I have also tried these:
#sed -i.bak 's/auth-user-pass/auth-user-pass "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass '"${update}"'' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "${update}"' $serverconfig
#sed -i.bak 's/auth-user-pass/auth-user-pass\ "$update"' $serverconfig
#sed -i.bak 's/'"$auth"'/'"$auth $update"' $serverconfig
# sed: -e expression #1, char 32: unterminated `s' command

Line in file "auth-user-pass" should found and replaced with "auth-user-pass ../login.conf". I'm unable to get passed the syntax error: sed: -e expression #1, char [#]: unterminated `s' command

Body:
Sed can use almost any character as its 'delimiter'. You're having trouble because your chosen delimiter / appears in your variable.

sed -i.bak "s,$auth,$update" $serverconfig

You can also perform this substitution as many times as possible with the global operation:

sed -i.back "s,$auth,$update,g" $serverconfig