问:
UIActivityViewController time lag in appearance of sharing options
There is a time lag between tapping of an option (present in UIActivityViewController eg: Notes app , Mail app) and the appearance of the respective controllers (Notes sharing controller, MFMessageController).

I want to show a loader in this time frame, but there seems to be no delegate methods of UIActivityController for doing so.

Can anyone suggest the right way to do it?

答:
I ended up subclassing the UIActivityViewController with the only addition being sending a notification after viewDidLoad completed.

Thus, I spin an activity indicator which I stop when I receive said notification.


来源: stackexchange

问:
Material-UI with Next.js & express giving Warning: Prop `className` did not match for server & client
This happens when I reload directly the /login and /account page. Those two pages has Material-UI components.

Also here's how my express server looks like. Server.js

答:
Ok so here's what I did to temporarily fix this problem. I only showed the Material-UI component after firing the componentDidMount lifecycle method. I'm using component state for this. Here's how it works:

```<code>class AccountNav extends Component {
    constructor(props){
        super(props);
        this.state = {
            load: false
        }
    }

    componentDidMount(){
        this.setState({ load: true });
    }

    render(){
        const { activeItem } = this.props;
        const { load } = this.state;
        if(!load) return <div></div>;
        else{
            return(
                <List style={{width: 250}}>
                    <ListItem button divider="true" style={activeItem == 'profile' ? styles.listHoverStyle : {}}>
                        <Link prefetch as="/account/profile" href="/account?page_slug=profile">
                            <ListItemText primary='Your Profile' />
                        </Link>
                    </ListItem>
                    <ListItem button style={activeItem == 'edit' ? styles.listHoverStyle : {}}>
                        <Link prefetch as="/account/edit" href="/account?page_slug=edit">
                            <ListItemText primary="Edit Profile" />
                        </Link>
                    </ListItem>
                </List>
            );
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok so here's what I did to temporarily fix this problem. I only showed the Material-UI component after firing the componentDidMount lifecycle method. I'm using component state for this. Here's how it works:

class AccountNav extends Component {
    constructor(props){
        super(props);
        this.state = {
            load: false
        }
    }

    componentDidMount(){
        this.setState({ load: true });
    }

    render(){
        const { activeItem } = this.props;
        const { load } = this.state;
        if(!load) return <div></div>;
        else{
            return(
                <List style={{width: 250}}>
                    <ListItem button divider="true" style={activeItem == 'profile' ? styles.listHoverStyle : {}}>
                        <Link prefetch as="/account/profile" href="/account?page_slug=profile">
                            <ListItemText primary='Your Profile' />
                        </Link>
                    </ListItem>
                    <ListItem button style={activeItem == 'edit' ? styles.listHoverStyle : {}}>
                        <Link prefetch as="/account/edit" href="/account?page_slug=edit">
                            <ListItemText primary="Edit Profile" />
                        </Link>
                    </ListItem>
                </List>
            );
        }
    }
}


问:
Django ignoring DEBUG value when I use os.environ, why?
In my Django settings I have the following:

DEBUG = os.environ['DEBUG_VALUE']

Where DEBUG_VALUE = False

However, Django continues to show full error messages when I do this. If I manual add DEBUG = False it works and shows 500 error.

For some reason Django is ignoring it when I use the os.environ value.

I have confirmed DEBUG_VALUE is False but outputting to a file.

I have even tried:

DEBUG = bool(os.environ['DEBUG_VALUE'])

and still shows full errors.

答:
The django-environ package has a simple way of managing this that is more robust and elegant, I think, than having to manually parse the string value (which will always evaluate to true) - you can import your environment as an object.

Export the environment variable and install the package:

```<code>export MY_DEBUG_ENV_VAR=False
pip install django-environ
</code>```

Then in django, import the environment as an Env() object and use the bool() method to parse a boolean and provide an optional default value:

```<code>import environ
env = environ.Env()
MY_DEBUG_ENV_VAR = env.bool('MY_DEBUG_ENV_VAR', default=False)
</code>```

Tada! The Env() object also has a bunch of other methods (e.g. for parsing integers, floats, strings etc etc).

NB I found this though the django-cookiecutter application, which has a bunch of equally useful things preinstalled and is a great starting point for projects whether you're new or experienced with django.

Body:
The django-environ package has a simple way of managing this that is more robust and elegant, I think, than having to manually parse the string value (which will always evaluate to true) - you can import your environment as an object.

Export the environment variable and install the package:

export MY_DEBUG_ENV_VAR=False
pip install django-environ

Then in django, import the environment as an Env() object and use the bool() method to parse a boolean and provide an optional default value:

import environ
env = environ.Env()
MY_DEBUG_ENV_VAR = env.bool('MY_DEBUG_ENV_VAR', default=False)

Tada! The Env() object also has a bunch of other methods (e.g. for parsing integers, floats, strings etc etc).

NB I found this though the django-cookiecutter application, which has a bunch of equally useful things preinstalled and is a great starting point for projects whether you're new or experienced with django.


问:
How to check if a popup window is open or not using Selenium WebDriver in Java
I'm trying to check whether the popup window I want to open is opened or not.

I have checked some question answers like

How would you check if a popup window exists using selenium webdriver?

But, nothings helped to solve the problem.

Here, first I open the login window by clicking the login button.

```<code>driver.findElement(By.xpath("//a[@id='login_btn']")).click(); // Click Login Button
</code>```

I even tried getPageSource() but, it seems not working.

Any kind of help would be appreciated.

Thanks in advance. :)

答:
If it's a native, browser alert (= a popup) you can do the following:

```<code>try{
    driver.switchTo().alert();
    // If it reaches here, it found a popup
} catch(NoALertPresentException e){}
</code>```

What it looks like you're actually dealing with is an iframe which you can do the following after getting the attribute value of the "iframe" attribute:

```<code>driver.switchTo.frame("ValueOfIframe");
// Treat as normal webpage. Now in iframe scope
driver.switchTo.defaultContent(); // To return back to normal page scope
</code>```

Body:
I'm trying to check whether the popup window I want to open is opened or not.

I have checked some question answers like

How would you check if a popup window exists using selenium webdriver?

But, nothings helped to solve the problem.

Here, first I open the login window by clicking the login button.

driver.findElement(By.xpath("//a[@id='login_btn']")).click(); // Click Login Button

I even tried getPageSource() but, it seems not working.

Any kind of help would be appreciated.

Thanks in advance. :)

Body:
If it's a native, browser alert (= a popup) you can do the following:

try{
    driver.switchTo().alert();
    // If it reaches here, it found a popup
} catch(NoALertPresentException e){}

What it looks like you're actually dealing with is an iframe which you can do the following after getting the attribute value of the "iframe" attribute:

driver.switchTo.frame("ValueOfIframe");
// Treat as normal webpage. Now in iframe scope
driver.switchTo.defaultContent(); // To return back to normal page scope


问:
Angular service instantiated twice?
somehow I've got a service that seems to be instantiated twice (its properties are not in sync), by doing the following:

```<code>@Component
export class MyComponent extends someOtherComponent {
  constructor(service: Service, service2: Service2) {
    super(service, service2);
  }

  isStateEqual() {
    return this.service.serviceState === this.service2.service.serviceState;
  }
}

@Injectable
export class Service {
  serviceState = {}
}

@Injectable
export class Service2 {
  constructor(service: Service) {}
}
</code>```

This is just a very basic example, but that's what it comes down to. To be more precise: We're building our own datepicker and extending NgbDatepicker component which has KeyMapService (this uses NgbDatepickerService) and a local NgbDatepickerService.
Here is a link to the component: https://ng-bootstrap.github.io/#/components/datepicker/examples

In our app isStateEqual will always return false (even right after initialising the component) while in the demo you can find in the link above it will always return true (which is how it should be).

Anyone knows why it could be like that?

Thanks in advance.

Regards
Dennis

答:
"service" must be a public propertie of Service2. </p>

```<code>@Injectable
export class Service2 {
  service:Service
  constructor(service: Service)
  {
      this.service=service;
  }
}
</code>```

Title: Angular service instantiated twice?

Body:
somehow I've got a service that seems to be instantiated twice (its properties are not in sync), by doing the following:

@Component
export class MyComponent extends someOtherComponent {
  constructor(service: Service, service2: Service2) {
    super(service, service2);
  }

  isStateEqual() {
    return this.service.serviceState === this.service2.service.serviceState;
  }
}

@Injectable
export class Service {
  serviceState = {}
}

@Injectable
export class Service2 {
  constructor(service: Service) {}
}

This is just a very basic example, but that's what it comes down to. To be more precise: We're building our own datepicker and extending NgbDatepicker component which has KeyMapService (this uses NgbDatepickerService) and a local NgbDatepickerService.
Here is a link to the component: https://ng-bootstrap.github.io/#/components/datepicker/examples

In our app isStateEqual will always return false (even right after initialising the component) while in the demo you can find in the link above it will always return true (which is how it should be).

Anyone knows why it could be like that?

Thanks in advance.

Regards
Dennis

Body:
"service" must be a public propertie of Service2.

@Injectable
export class Service2 {
  service:Service
  constructor(service: Service)
  {
      this.service=service;
  }
}


问:
PDF::Create incorrectly converts french accented characters
My Perl program can successfully convert english text to pdf using the PDF::Create module.  However, french accented characters do not display correctly in the PDF file.

Here is a line from the plain text file containing french characters:

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

Here is what the same line looks like in the PDF file:

VÃ‰RIFIER DÃ‰CLARATION DE DROITS-FORMALITÃ‰S

Here is the relevant code:

```<code>$page = $pdf->new_page('MediaBox' => [0,0,$pdfWidth,$pdfHeight]);
$font1 = $pdf->font('Subtype'=>'Type1',Encoding'=>'WinAnsiEncoding','BaseFont'=>'Courier');
$page->string($font1, $fontSize, $leftMarg, $yCoord, $pdfLine);
</code>```

where $pdfLine contains the plain text.

The program reads in a file with this content:

azAZàâäçèéê

ÉTAT DES DEMANDES INACTIVES - OPÉRATION DES BREVETS

TÂCHE

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

VÉRIFIER LISTAGE DES SÉQUENCE-FORMALITÉS

答: I fixed the problem by installing an old version of PDF::Create.  I was running version 1.42 and I installed version 1.31.  French accented characters display fine using version 1.31.  So, somewhere between 1.31 and 1.42 the conversion of accented characters was broken.</p>

Body:
My Perl program can successfully convert english text to pdf using the PDF::Create module.  However, french accented characters do not display correctly in the PDF file.

Here is a line from the plain text file containing french characters:

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

Here is what the same line looks like in the PDF file:

VÃ‰RIFIER DÃ‰CLARATION DE DROITS-FORMALITÃ‰S

Here is the relevant code:

$page = $pdf->new_page('MediaBox' => [0,0,$pdfWidth,$pdfHeight]);
$font1 = $pdf->font('Subtype'=>'Type1',Encoding'=>'WinAnsiEncoding','BaseFont'=>'Courier');
$page->string($font1, $fontSize, $leftMarg, $yCoord, $pdfLine);

where $pdfLine contains the plain text.

The program reads in a file with this content:

azAZàâäçèéê

ÉTAT DES DEMANDES INACTIVES - OPÉRATION DES BREVETS

TÂCHE

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

VÉRIFIER LISTAGE DES SÉQUENCE-FORMALITÉS


问:
npm is not recognized as an internal or external command in windows
When I try to run npm install on windows, I get the following error. How can get rid of it?

```<code>D:\Xampp\htdocs\laravelchat>npm install
'CALL "C:\Program Files\nodejs\\node.exe" "C:\Program Files\nodejs\\node_modules\npm\bin\npm-cli.js" prefix -g' is not recognized as an internal or external command,
operable program or batch file.
</code>```

答:
As you can see C:\Program Files\nodejs\\node.exe has two slashes \. You need to remove \ from the end of C:\Program Files\nodejs\ which is defined in environment variable. Follow following steps to set up path for nodejs and npm

Open the system properties (enter sysdm.cpl in command prompt), and click Advanced tab.

Click Environmental Variables. A pop-up window will open displaying Path under System Variables. Check whether the Path is determined as C:\Program Files\nodejs or C:\Program Files (*86)\nodejs. Remember not to include \ at the end. If Path is not determined, append the path manually by clicking Edit.

Body:
When I try to run npm install on windows, I get the following error. How can get rid of it?

D:\Xampp\htdocs\laravelchat>npm install
'CALL "C:\Program Files\nodejs\\node.exe" "C:\Program Files\nodejs\\node_modules\npm\bin\npm-cli.js" prefix -g' is not recognized as an internal or external command,
operable program or batch file.


问:
Postgres SQL Query about database and table space
What is the hierarchy of Database related objects in postgres SQL?
Should it be like, table space must be created at instance level unlike other RDBMS(where we have table space under database).
If so we create the table space at instance level, what is the purpose of database? and what is difference between table space and database on postgres server?</p>

答:
An instance (in PostgreSQL called cluster) is a data directory initialized with initdb with a PostgreSQL server process.

A tablespace is a directory outside the data directory where objects can also be stored. Tablespaces are useful for certain corner cases like distributing I/O or limiting space for a subset of the data.

A database is a container for objects with permissions, organized in schemas.

The difference is that tablespaces are a physical concept, it defines a space where the data are stored, while databases are a logical concept about how data are organized, what they mean, how they are related, who is allowed to access them and so on.

The two concepts are orthogonal.

A database can have tables in several tablespaces, and a tablespace can contain data from several databases.


问:
Why would file checksums inconsistently fail?
I created a ~2MiB file.

```<code>dd if=/dev/urandom of=file.bin bs=2M count=1
</code>```

Then I copied that file a large number of times and generated a checksum for each (identical) copy.

```<code>for i in `seq 50000`;
do
  name="file.${i}.bin"
  cp file.bin "${name}"
  sha512sum "${name}" > "${name}.sha512"
done
</code>```

I then verified all of those checksummed files with a validation script to run sha512sum against each file.

```<code>for file in `find . -regex ".*\.sha512"`
do
    sha512sum --check --quiet "${file}" || (
      cat "${file}" && sha512sum "${file%.sha512}"
    )
done
</code>```

I just created these files, and when I validate them moments later, I see intermittent failures and inconsistencies in the data (console text truncated for readability)

```<code>will:/mnt/usb $ for file in `find ...
file.5602.bin: FAILED
sha512sum: WARNING: 1 computed checksum did NOT match
91fc201a3812e93ef3d4890 ... file.5602.bin
b176e8e3ea63a223130f3a0 ... ./file.5602.bin
</code>```

The checksum files are all identical since the source files are all identical

The problem seems to be that my computer is, seemingly at random, generating the wrong checksum for some of my files when I go to validate. A different file fails the checksum every time, and files that previously failed will pass.

```<code>will:/mnt/usb $ for file in `find ...
sha512sum: WARNING: 1 computed checksum did NOT match
91fc201a3812e93ef3d4890 ... file.3248.bin
442a1d8805ed134c9ab5252 ... ./file.3248.bin
</code>```

Keep in mind that all of these files are identical.

I see the same behavior with SATA SSD and HDD, and USB devices, with md5 and sha512, with xfs, btrfs, ext4, and vfat. I tried live booting to another OS. I see this same stranger behavior regardless. I also see rsync --checksum for these files thinks checksums are wrong and re-copies these files even though they have not changed.

What could explain this behavior? Since it's happening on multiple devices with all the scenarios I described, I doubt this is bit rot. My kernel logs show no obvious errors. I would assume this is a hardware issue based on my troubleshooting, but how can this be diagnosed? Is it the CPU, the motherboard, the RAM?

答:
What could explain this behavior? How can this be diagnosed?

From what I've read, a number of issues could explain this behavior. Bad disk(s), bad PSU (power supply), bad RAM, filesystem issues.

I tried the following to determine what was happening. I repeated the experiment with different...

Disks

Types of disks (SDD vs HDD)

External drives (3.5 and 2.5 enclosures)

Flash drives (USB 2 and 3 on various ports)

Filesystems (ext4, vfat (fat32), xfs, btrfs)

Different PSU

Different OS (live boot)

Nothing seemed to resolve this.

Finally, I gave memtest86+ v5.0.1 a try via an Ubuntu live USB.

voila. It found bad memory. Through process of elimination I determined one of my memory sticks was bad, and then tested the other over night to ensure it was in good shape. I re-ran my experiment again and I am seeing consistent checksums on all my files.

What a subtle bug. I only noticed this bad behavior by accident. If I hadn't been messing around with file checksums, I do not think I would have found this bad RAM.

This makes me want to regularly schedule a routine in which I verify and test my RAM. A consequence of this bad memory stick is that some of my test data did end up corrupt, but more often than not, the checksum verifications were just interimmitent failures.

In one sample data pool, all the checksums start with cb2848ca0e1ff27202a309408ec76..., because all ~50,000 files are identical.

Though, there are two files that are corrupt, but this is not bit rot or file integrity damage.

What seems most likely is that these files were created with corruption because cp encountered bad RAM when I created these files. Those files consistently return bad checksums of 58fe24f0e00229e8399dc6668b9... and bd85b51065ce5ec31ad7ebf3..., while the other 49,998 files return the same checksum.

This has been a fun extremely frustrating experiment in debugging.

Body:
I created a ~2MiB file.

dd if=/dev/urandom of=file.bin bs=2M count=1

Then I copied that file a large number of times and generated a checksum for each (identical) copy.

for i in `seq 50000`;
do
  name="file.${i}.bin"
  cp file.bin "${name}"
  sha512sum "${name}" > "${name}.sha512"
done

I then verified all of those checksummed files with a validation script to run sha512sum against each file.

for file in `find . -regex ".*\.sha512"`
do
    sha512sum --check --quiet "${file}" || (
      cat "${file}" && sha512sum "${file%.sha512}"
    )
done

I just created these files, and when I validate them moments later, I see intermittent failures and inconsistencies in the data (console text truncated for readability)

will:/mnt/usb $ for file in `find ...
file.5602.bin: FAILED
sha512sum: WARNING: 1 computed checksum did NOT match
91fc201a3812e93ef3d4890 ... file.5602.bin
b176e8e3ea63a223130f3a0 ... ./file.5602.bin

The checksum files are all identical since the source files are all identical

The problem seems to be that my computer is, seemingly at random, generating the wrong checksum for some of my files when I go to validate. A different file fails the checksum every time, and files that previously failed will pass.

will:/mnt/usb $ for file in `find ...
sha512sum: WARNING: 1 computed checksum did NOT match
91fc201a3812e93ef3d4890 ... file.3248.bin
442a1d8805ed134c9ab5252 ... ./file.3248.bin

Keep in mind that all of these files are identical.

I see the same behavior with SATA SSD and HDD, and USB devices, with md5 and sha512, with xfs, btrfs, ext4, and vfat. I tried live booting to another OS. I see this same stranger behavior regardless. I also see rsync --checksum for these files thinks checksums are wrong and re-copies these files even though they have not changed.

What could explain this behavior? Since it's happening on multiple devices with all the scenarios I described, I doubt this is bit rot. My kernel logs show no obvious errors. I would assume this is a hardware issue based on my troubleshooting, but how can this be diagnosed? Is it the CPU, the motherboard, the RAM?


问:
Optimizing mysql update statement on table with duplicate records
I have two tables in the same schema which are payments & tt_emails which look like below:

payments table: Contains ~27 million payment records with repeating customer_id's across months for which payments were made.

```<code>+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| report_cust  | varchar(100)     | YES  |     | NULL    |                |
| payment_type | varchar(100)     | YES  |     | NULL    |                |
| month        | varchar(1000)    | YES  |     | NULL    |                |
| year         | varchar(1000)    | YES  |     | NULL    |                |
| amount       | varchar(1000)    | YES  |     | NULL    |                |
| pmnt_date    | varchar(1000)    | YES  |     | NULL    |                |
| mapping      | varchar(100)     | YES  |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+
</code>```

tt_emails table: Contains ~916k records.

```<code>+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| cnc_id      | varchar(100)     | YES  |     | NULL    |                |
| customer_id | varchar(100)     | YES  |     | NULL    |                |
| email       | varchar(1000)    | YES  |     | NULL    |                |
| email_type  | varchar(1000)    | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+
</code>```

What am trying to achieve is, to update the mapping column in the payments table with the value in email_type from tt_emails table. I am using the below update statement which I have tested and seems to update 10 records (id <=10) in ~6 secs.

```<code>Update payments p
  join tt_emails tmp
    on p.report_cust=tmp.customer_id
  set p.mapping = tmp.email_type
  where p.report_cust is not null;
</code>```

I have left the update query to run for almost 12 hours but it seems to be still running and I suspect this could be due to the join condition in the update statement given that report_cust is not unique and repeats itself given its the payment history.

Is there a better way to handle this and get the update to run faster? I initial tried a sub-query but I read that its way slower than joins.

答:
No indexes!  (Except the PK)

```<code>on p.report_cust=tmp.customer_id
</code>```

needs either

```<code>p:  INDEX(report_cust)
tmp:  INDEX(customer_id)
</code>```

And

```<code>where p.report_cust is not null
</code>```

would probably benefit from

```<code>INDEX(report_cust)
</code>```

Even better would be this "covering" (and "composite") index:

```<code>tmp:  INDEX(customer_id, email_type)
</code>```

And get real with the datatypes.  If year is really a "year", does it take 1000 characters to spell it out?  4 would do.  INT would be better.  Even better is the datatyps YEAR.

Consider ENUM for "types".

It is rare (but not impossible) to need VARCHAR for ids (cnc_id and customer_id).

Without indexes, it has to scan the entire tables.  Think of looking through a list of 916K names that are not sorted in any way.  Furthermore, doing that 27 million times!

Body:
I have two tables in the same schema which are payments & tt_emails which look like below:

payments table: Contains ~27 million payment records with repeating customer_id's across months for which payments were made.

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| report_cust  | varchar(100)     | YES  |     | NULL    |                |
| payment_type | varchar(100)     | YES  |     | NULL    |                |
| month        | varchar(1000)    | YES  |     | NULL    |                |
| year         | varchar(1000)    | YES  |     | NULL    |                |
| amount       | varchar(1000)    | YES  |     | NULL    |                |
| pmnt_date    | varchar(1000)    | YES  |     | NULL    |                |
| mapping      | varchar(100)     | YES  |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+

tt_emails table: Contains ~916k records.

+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| cnc_id      | varchar(100)     | YES  |     | NULL    |                |
| customer_id | varchar(100)     | YES  |     | NULL    |                |
| email       | varchar(1000)    | YES  |     | NULL    |                |
| email_type  | varchar(1000)    | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

What am trying to achieve is, to update the mapping column in the payments table with the value in email_type from tt_emails table. I am using the below update statement which I have tested and seems to update 10 records (id <=10) in ~6 secs.

Update payments p
  join tt_emails tmp
    on p.report_cust=tmp.customer_id
  set p.mapping = tmp.email_type
  where p.report_cust is not null;

I have left the update query to run for almost 12 hours but it seems to be still running and I suspect this could be due to the join condition in the update statement given that report_cust is not unique and repeats itself given its the payment history.

Is there a better way to handle this and get the update to run faster? I initial tried a sub-query but I read that its way slower than joins.

Body:
No indexes!  (Except the PK)

on p.report_cust=tmp.customer_id

needs either

p:  INDEX(report_cust)
tmp:  INDEX(customer_id)

And

where p.report_cust is not null

would probably benefit from

INDEX(report_cust)

Even better would be this "covering" (and "composite") index:

tmp:  INDEX(customer_id, email_type)

And get real with the datatypes.  If year is really a "year", does it take 1000 characters to spell it out?  4 would do.  INT would be better.  Even better is the datatyps YEAR.

Consider ENUM for "types".

It is rare (but not impossible) to need VARCHAR for ids (cnc_id and customer_id).

Without indexes, it has to scan the entire tables.  Think of looking through a list of 916K names that are not sorted in any way.  Furthermore, doing that 27 million times!


问:
how to use image in ios with Xamarin forms
I use Xamrin forms for an app on IOs and Android.

in my Android project and IOS project, i have a folder "drawable" (with my image) in the "resources" folder.

In my XAML i call like this :
<Image Source="@drawable/clockCircular.png"/>

When attempting to view the image on Android, no problem I see my image.
When attempting to view the image on iOS, the image doesn't appear.

I would like to keep this file structure (resources > drawable).
I have followed many tutorials on the web as images but I'm still blocked here.

答:
IOS => You need put the images on "Resources"  (note: no more routes)
ANDROID => you need put the images on "Resources/drawable" .

On Diferents platforms the images have diferents routes.

Then on the xaml files you can put <Image Source="imageName.jpg" />


问:
Copying raw data into specific cells of a target sheet
I am trying to write the Output of my Script to the second worksheet of an Excel workbook. Now when I use the following code I always get the error

Microsoft VBScript Compilation error : Expected end of statement.

Can you let me know where I may be going wrong? If you want to look at the entire code feel free to let me know.

The code snippet to write the output is as follows:

```<code>Set targetsheet.Cells(1,1).Value = objOutput.Write objUser.samaccountname & ";" _
    & objUser.GivenName & ";" & objUser.sn & ";" & objUser.DisplayName & ";" _
    & ObjMail & ";" & InfosysSite & ";=IFERROR(IF(VLOOKUP(E" & count _
    & ",'Infosys employees'!C:C,1,FALSE)=E" & count & ",""Yes""),""No"")" _
    & ";=IF(G" & count & "=""Yes"",VLOOKUP(E" & count _
    & ",'Infosys employees'!C:D,2,FALSE),""Missing"")" & ";" & ObjUser.Title _
    & ";" & ObjUser.Co & ";" & Manager & ";" & objUser.employeeID & ";" _
    & Account_locked & ";" & last_Login & ";" & last_Logon_timestamp & ";" _
    & pwd_never_expire & ";" & Last_pwd_Changed & ";" & User_must_change_pwd _
    & ";" & objUser.whenCreated & ";" & objUser.whenChanged & ";" _
    & objUser.description & ";" & objUser.distinguishedName & ";" & vbCrLf
</code>```

答:
You get a 1025 error, when you try to call a sub/submethod in an assigment:

```<code>>> v = SubOrSubMethod "very long string"
>>
Error Number:       1025
Error Description:  Anweisungsende erwartet
</code>```

So assign your (horrible) string expression to a variable:

```<code>s = objUser.samaccountname &";" & ... &";" & vbcrlf
</code>```

and use that to fill the cell's value:

```<code>targetsheet.Cells(1,1).Value = s
</code>```

Mark the deleted Set! You want to assign a string, not an object. Whether a dignostic output:

```<code>objOutput.Write s
</code>```

makes sense in your context, is for you to decide.

Body:
I am trying to write the Output of my Script to the second worksheet of an Excel workbook. Now when I use the following code I always get the error

Microsoft VBScript Compilation error : Expected end of statement.

Can you let me know where I may be going wrong? If you want to look at the entire code feel free to let me know.

The code snippet to write the output is as follows:

Set targetsheet.Cells(1,1).Value = objOutput.Write objUser.samaccountname & ";" _
    & objUser.GivenName & ";" & objUser.sn & ";" & objUser.DisplayName & ";" _
    & ObjMail & ";" & InfosysSite & ";=IFERROR(IF(VLOOKUP(E" & count _
    & ",'Infosys employees'!C:C,1,FALSE)=E" & count & ",""Yes""),""No"")" _
    & ";=IF(G" & count & "=""Yes"",VLOOKUP(E" & count _
    & ",'Infosys employees'!C:D,2,FALSE),""Missing"")" & ";" & ObjUser.Title _
    & ";" & ObjUser.Co & ";" & Manager & ";" & objUser.employeeID & ";" _
    & Account_locked & ";" & last_Login & ";" & last_Logon_timestamp & ";" _
    & pwd_never_expire & ";" & Last_pwd_Changed & ";" & User_must_change_pwd _
    & ";" & objUser.whenCreated & ";" & objUser.whenChanged & ";" _
    & objUser.description & ";" & objUser.distinguishedName & ";" & vbCrLf

Body:
You get a 1025 error, when you try to call a sub/submethod in an assigment:

>> v = SubOrSubMethod "very long string"
>>
Error Number:       1025
Error Description:  Anweisungsende erwartet

So assign your (horrible) string expression to a variable:

s = objUser.samaccountname &";" & ... &";" & vbcrlf

and use that to fill the cell's value:

targetsheet.Cells(1,1).Value = s

Mark the deleted Set! You want to assign a string, not an object. Whether a dignostic output:

objOutput.Write s

makes sense in your context, is for you to decide.


问:
Sum values from a text file and printing them
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

```<code>System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}
</code>```

Here is my text file:

```<code>The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
</code>```

Here is what is being displayed by my java program:

```<code>Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:
</code>```

答:
It looks like the variable BookPrice2 is an array that holds doubles inside of it. In this case, you don't want to call a method directly on BookPrice2, you want to iterate over the array and add each value to another variable.

Something like this should set you on the correct path.

```<code>double sum = 0;
for (int i = 0; i < BookPrice2.length; i++) {
    sum += BookPrice2[i];
}
System.out.println(sum);
</code>```

Body:
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}

Here is my text file:

The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625

Here is what is being displayed by my java program:

Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:

Body:
It looks like the variable BookPrice2 is an array that holds doubles inside of it. In this case, you don't want to call a method directly on BookPrice2, you want to iterate over the array and add each value to another variable.

Something like this should set you on the correct path.

double sum = 0;
for (int i = 0; i < BookPrice2.length; i++) {
    sum += BookPrice2[i];
}
System.out.println(sum);


问:
Modify style of a html tag inside of a id-element
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}
```

<p>and html:</p>

```

    test
    test
    test
    test

```

<p>I want to change the style of all the <code><a></code> tags in the <code><div></code> with the id <code>titlebar</code>. <code>display</code> should be changed from <code>inline-block</code> to <code>block</code>. Is this possible with JavaScript or do I have to search a different way to do this?</p>

<p>https://jsfiddle.net/Ln0a235v/2/</p>

<p><strong>Complete Context:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}</code>```

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="titlebar">
  <nav>
    ToggleMenu
    test
    test
    test
  </nav>
</div>

<div class="main">
  <div class="content">
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
    <hr/>
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
  </div>
</div></code>```

答:
Plain JS approach

```<code>document.querySelectorAll( "#titlebar a" ).forEach( function(el){
   el.style.display = "block";
});
</code>```

Demo

document.querySelectorAll("#titlebar a").forEach(function(el) {
  el.style.display = "block";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#titlebar a {
  display: inline-block;
}</code>```

    test
    test
    test
    test

```

Body:
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}

and html:

    test
    test
    test
    test

I want to change the style of all the  tags in the
 with the id titlebar. display should be changed from inline-block to block. Is this possible with JavaScript or do I have to search a different way to do this?

https://jsfiddle.net/Ln0a235v/2/

Complete Context:

// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}

    ToggleMenu
    test
    test
    test

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Body:
Plain JS approach

document.querySelectorAll( "#titlebar a" ).forEach( function(el){
   el.style.display = "block";
});

Demo

document.querySelectorAll("#titlebar a").forEach(function(el) {
  el.style.display = "block";
});

#titlebar a {
  display: inline-block;
}

<div id="titlebar">
  <nav>
    <a href="#">test</a>
    <a href="#">test</a>
    <a href="#">test</a>
    <a href="#">test</a>
  </nav>
</div>


问:
How to replace data in a specific row jQuery
Hi everyone I want to replace data inside the row depending upon the row number. The code I have posted traverses through the rows in the table, counts the row-indexes and matches them with the required row. If condition gets true the data should be replaced in that row. I have edited the question

I don't know what should I use to replace the data?

I have tried .innerHTML, .replaceWith() but they do not give me the required thing.

```<code>$('table#table-mytable tr').each(function(){
  var row_required = tag[tag.length-2];
  console.log('this is row_required: '+row_required);
  var row = $(this).index()+1;
  console.log('this is row: '+row);
  if(row==row_required) {
     (What should I enter here)
  }
});
</code>```

I want replace with something like:
      replaceWith('td colspan="2" input type="text" name="input_" class="input_" id="input_" value="' + input_tag + '" placeholder="Enter Label" /td>')?

答:
You can use html() (amongst other methods) to replace the contents of the tr. Also note that you don't need to loop at all. If you know the index you can select it directly using eq():

var row_required = 1;
$('#table-mytable tr').eq(row_required).html('Bar	');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table id="table-mytable">
  <tbody>
    <tr><td>Foo</td></tr>
    <tr><td>Foo</td></tr>
    <tr><td>Foo</td></tr>
  </tbody>
</table></code>```

Body:
Hi everyone I want to replace data inside the row depending upon the row number. The code I have posted traverses through the rows in the table, counts the row-indexes and matches them with the required row. If condition gets true the data should be replaced in that row. I have edited the question

I don't know what should I use to replace the data?

I have tried .innerHTML, .replaceWith() but they do not give me the required thing.

$('table#table-mytable tr').each(function(){
  var row_required = tag[tag.length-2];
  console.log('this is row_required: '+row_required);
  var row = $(this).index()+1;
  console.log('this is row: '+row);
  if(row==row_required) {
     (What should I enter here)
  }
});

I want replace with something like:
      replaceWith('td colspan="2" input type="text" name="input_" class="input_" id="input_" value="' + input_tag + '" placeholder="Enter Label" /td>')?

Body:
You can use html() (amongst other methods) to replace the contents of the tr. Also note that you don't need to loop at all. If you know the index you can select it directly using eq():

var row_required = 1;
$('#table-mytable tr').eq(row_required).html('<td>Bar</td>');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table id="table-mytable">
  <tbody>
    <tr><td>Foo</td></tr>
    <tr><td>Foo</td></tr>
    <tr><td>Foo</td></tr>
  </tbody>
</table>


问:
How to set currentTime in video.js in Safari for iOS
Other is ok, but the setting of currentTime:

I tried some ways like:

```<code>videojs("example_video_1", {}, function() {
    this.currentTime(200);
    this.play();
});
</code>```

And this is not working.

```<code>videojs("example_video_1").ready(function(){
    this.currentTime(200);
});
</code>```

This also doesn't work.

```<code>var dom = document.getElementById('example_video_1');
dom.addEventListener("loadedmetadata", function() {
    dom.currentTime = 100;
}, false);    // ok for no video.js
videojs(dom);
</code>```

Not working. Even reverse the line of addEventListener and init videojs.

And I tried the videojs event.

```<code>var player = videojs("example_video_1");
alert(player.addEvent);
alert(player.addEventListener);
</code>```

these API all not exists, so how do I bind Event in videojs?

答:
This is how I got the video playback on a defined position at startup (it removes the problem that the video first started and only afterwards jumped to a video position): </p>

```<code>$(document).ready(function()
{
    var timecode = 120;
    var initdone = false;

    // wait for video metadata to load, then set time
    video.on("loadedmetadata", function(){
        video.currentTime(timecode);
    });

    // iPhone/iPad need to play first, then set the time
    // events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents
    video.on("canplaythrough", function(){
        if(!initdone)
        {
            video.currentTime(timecode);
            initdone = true;
        }
    });

}); // END ready
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Other is ok, but the setting of currentTime:

I tried some ways like:

videojs("example_video_1", {}, function() {
    this.currentTime(200);
    this.play();
});

And this is not working.

videojs("example_video_1").ready(function(){
    this.currentTime(200);
});

This also doesn't work.

var dom = document.getElementById('example_video_1');
dom.addEventListener("loadedmetadata", function() {
    dom.currentTime = 100;
}, false);    // ok for no video.js
videojs(dom);

Not working. Even reverse the line of addEventListener and init videojs.

And I tried the videojs event.

var player = videojs("example_video_1");
alert(player.addEvent);
alert(player.addEventListener);

these API all not exists, so how do I bind Event in videojs?

Body:
This is how I got the video playback on a defined position at startup (it removes the problem that the video first started and only afterwards jumped to a video position):

$(document).ready(function()
{
    var timecode = 120;
    var initdone = false;

    // wait for video metadata to load, then set time
    video.on("loadedmetadata", function(){
        video.currentTime(timecode);
    });

    // iPhone/iPad need to play first, then set the time
    // events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents
    video.on("canplaythrough", function(){
        if(!initdone)
        {
            video.currentTime(timecode);
            initdone = true;
        }
    });

}); // END ready


问:
XSD choice inside sequence
I understand and use xs:choice and xs:sequence separately but I do not understand what xs:choice inside xs:sequence mean?

```<code><xs:element name="sports-content">
  <xs:complexType>
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="sports-metadata" />
        <xs:element name="sports-event" />
        <xs:element name="tournament" />
        <xs:element name="schedule" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

Ok. This XML will be valid.

```<code><sports-content>
  <sports-metadata />
  <tournament />
</sports-content>
</code>```

Will this XML be valid or not?

```<code><sports-content>
  <sports-metadata />
  <tournament />
  <sports-metadata />
</sports-content>
</code>```

答:
The xs:sequence element in your XSD is superfluous; it can be removed without affecting validity of any XML document.  An xs:sequence around an xs:choice would be useful, for example, if you wanted the choice to always be preceded or followed by one or more elements in sequence.

Yes, both of the XML documents in your question are valid against your XSD (and will continue to be if you remove the xs:sequence wrapper around xs:choice.

Title: XSD choice inside sequence

Body:
I understand and use xs:choice and xs:sequence separately but I do not understand what xs:choice inside xs:sequence mean?

<xs:element name="sports-content">
  <xs:complexType>
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="sports-metadata" />
        <xs:element name="sports-event" />
        <xs:element name="tournament" />
        <xs:element name="schedule" />
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Ok. This XML will be valid.

<sports-content>
  <sports-metadata />
  <tournament />
</sports-content>

Will this XML be valid or not?

<sports-content>
  <sports-metadata />
  <tournament />
  <sports-metadata />
</sports-content>


问:
How to show hide a class?
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

```<code>$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });
</code>```

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

答:
Just put the hide and show commands in the success function:</p>

```
....
success:function(data) {
  $(".foo").hide();
  $(".bar").show();
}

```

ContentLicense: CC BY-SA 2.5

Title: How to show hide a class?

Body:
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

Body:
Just put the hide and show commands in the success function:

....
success:function(data) {
  $(".foo").hide();
  $(".bar").show();
}


问:
New Google Cloud Module not present in Android Studio 3.0
When I try to create new google cloud module via android studio it is not visible in new module panel as given in the step 1 of the instruction in the following link :-https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints.

I have tried all the solutions given online but they don't seem to work.
Please help

答:
Google Cloud Module was previously available through Cloud Tools for Android Studio plugin.

Unfortunately, this plugin doesn't have Google Cloud Module for Android Studio version 3.0. Please see this link:

https://cloud.google.com/tools/android-studio/docs/

Note: Creating App Engine-based cloud backends is not supported in
  Android Studio 3.0; however, your existing projects with cloud
  backends will continue to work in Android Studio.

We have to wait and see if the Android Studio team has plans on their roadmap to fix this.


问:
Check if functions have been called in unit test
Hi I'm trying to write some unit tests in Jest for a module I write, but kind of stuck currently and need some advice how to continue.

```<code>export const submitOrder = async (body, key) => {
  const clientRepo = new ClientRepository(db)
  const companyRepo = new CompanyRepository(db)

  const company = await getCompanyByKey(
    companyRepo,
    key
  );

  const client = await createClient(
    clientRepo,
    body
  );

  await addClientToCompany(
    companyRepo,
    client.id,
    company.id
  );

  .. More things
}
</code>```

I can easily test each function(getCompanyByKey, createClient & addClientToCompany) by passing down a mocked repository.

But I would also like to test my "flow" of the submitOrder function, by checking if my repository functions have been called. But I would then need the instance of each repository, which I don't instantiate until my submitOrder function.

Something like this, which is similar how I unit test my functions.

```<code>jest.mock('../repositories/ClientRepository');
jest.mock('../repositories/CompanyRepository');

test('should be able to submit an order', async () => {
  const apiKey = 'mocked-super-key';
  const body = getMockData();

  const result = await submitOrder(body, apiKey);
  expect(result).toMatchSnapshot();
  expect(CompanyRepository.findByKey).toHaveBeenCalled();
  expect(ClientRepository.create).toHaveBeenCalled();
  expect(CompanyRepository.addClient).toHaveBeenCalled();
});
</code>```

Do you have any tips of how I can test if my repositories have been called?

答:
The problem you describe is one of the motivating factors behind dependency injection.

As a single example: your submitOrder() code uses new to directly instantiate a client repository of the specific implementation ClientRepository.  Instead, it could declare that it has a dependency - it needs an object that implements the interface of a client repository.  It could then allow for such an object to be supplied by the surrounding environment (a "dependency injection container" in buzzword-ese).  Then during testing you would create and provide ("inject") a mock implementation instead of the real implementation.

This has the added benefit that if you ever have to be able to select between multiple "real" implementations, you're already set up to do that too.

There are many ways to achieve this.  It can be as simple as a design pattern, or for a more complete solution you could use a dependency injection framework.

If you absolutely cannot refactor your code for this practice, then JavaScript is dynamic enough that you can probably cobble together a way to intercept the invocation of new and thereby simulate dependency injection.

Body:
Hi I'm trying to write some unit tests in Jest for a module I write, but kind of stuck currently and need some advice how to continue.

export const submitOrder = async (body, key) => {
  const clientRepo = new ClientRepository(db)
  const companyRepo = new CompanyRepository(db)

  const company = await getCompanyByKey(
    companyRepo,
    key
  );

  const client = await createClient(
    clientRepo,
    body
  );

  await addClientToCompany(
    companyRepo,
    client.id,
    company.id
  );

  .. More things
}

I can easily test each function(getCompanyByKey, createClient & addClientToCompany) by passing down a mocked repository.

But I would also like to test my "flow" of the submitOrder function, by checking if my repository functions have been called. But I would then need the instance of each repository, which I don't instantiate until my submitOrder function.

Something like this, which is similar how I unit test my functions.

jest.mock('../repositories/ClientRepository');
jest.mock('../repositories/CompanyRepository');

test('should be able to submit an order', async () => {
  const apiKey = 'mocked-super-key';
  const body = getMockData();

  const result = await submitOrder(body, apiKey);
  expect(result).toMatchSnapshot();
  expect(CompanyRepository.findByKey).toHaveBeenCalled();
  expect(ClientRepository.create).toHaveBeenCalled();
  expect(CompanyRepository.addClient).toHaveBeenCalled();
});

Do you have any tips of how I can test if my repositories have been called?


问:
Why am I not able to return a fragment?
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

```<code>import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
The first line in your FragmentPagerAdapter is incorrect.

private List<Fragment> MyFragment = new ArrayList<>();

The Fragment in your List<Fragment> is of type android.app.Fragment, it should be of type android.support.v4.app.Fragment.

just remove this import statement in your file, ot should be at the top:

import android.app.Fragment;

Title: Why am I not able to return a fragment?

Body:
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


答:
You can pass a mock implementation factory as a second parameter to jest.mock, as described in the docs.

You can use this to mock out the methods that you want to check to have been called.

Try this:

```<code>jest.mock('../repositories/CompanyRepository', () => {
    findByKey: jest.fn(),
    addClient: jest.jn()
});

const mockCreate = jest.fn();

jest.mock('../repositories/CompanyRepository', () => class {
    create(...args) {
        mockCreate(...args);
    }
});

test('should be able to submit an order', async () => {
    const apiKey = 'mocked-super-key';
    const body = getMockData();

    const result = await submitOrder(body, apiKey);
    expect(result).toMatchSnapshot();
    expect(CompanyRepository.findByKey).toHaveBeenCalled();
    expect(ClientRepository.create).toHaveBeenCalled();
    expect(CompanyRepository.addClient).toHaveBeenCalled();
});
</code>```

Since CompanyRepository is created with “new”, we use a class definition in this case and pass in a mock function that is called when the “create” method is invoked.

Title: Check if functions have been called in unit test

Body:
You can pass a mock implementation factory as a second parameter to jest.mock, as described in the docs.

You can use this to mock out the methods that you want to check to have been called.

Try this:

jest.mock('../repositories/CompanyRepository', () => {
    findByKey: jest.fn(),
    addClient: jest.jn()
});

const mockCreate = jest.fn();

jest.mock('../repositories/CompanyRepository', () => class {
    create(...args) {
        mockCreate(...args);
    }
});

test('should be able to submit an order', async () => {
    const apiKey = 'mocked-super-key';
    const body = getMockData();

    const result = await submitOrder(body, apiKey);
    expect(result).toMatchSnapshot();
    expect(CompanyRepository.findByKey).toHaveBeenCalled();
    expect(ClientRepository.create).toHaveBeenCalled();
    expect(CompanyRepository.addClient).toHaveBeenCalled();
});

Since CompanyRepository is created with “new”, we use a class definition in this case and pass in a mock function that is called when the “create” method is invoked.


问:
Open wizard on a specific step
Is it possible to open the wizard component on a specific step?

I want to open the wizard with a commandbutton.

What I have tried, it using the PrimeFaces function loadStep() to change step right after the wizard is opened, but with no luck.

For example:

```<code>oncomplete="PF('wizard').show();" onsuccess="PF('wiz').loadStep('step-two', true)";
</code>```

And the other way around.

Any suggestions?

答:
If you use primefaces 5 or later</p>

```<code>PF('wiz').loadStep(PF('wiz').cfg.steps[0], false);
</code>```

Title: Open wizard on a specific step

Body:
Is it possible to open the wizard component on a specific step?

I want to open the wizard with a commandbutton.

What I have tried, it using the PrimeFaces function loadStep() to change step right after the wizard is opened, but with no luck.

For example:

oncomplete="PF('wizard').show();" onsuccess="PF('wiz').loadStep('step-two', true)";

And the other way around.

Any suggestions?

Body:
If you use primefaces 5 or later

PF('wiz').loadStep(PF('wiz').cfg.steps[0], false);


问:
Exploit a backup program using C
I'm doing an assignment of a security course that asks me to find 4 vulnerabilities of a backup program (setuid) and use each of them to gain root access (on a virtual linux machine with old version of gcc etc.).
There should be one of buffer overflow and one of format string.

Could anyone help me to point out where the 4 vulnerabilities are?
I think the buffer overflow can happened in copyFile().

The following is the code for backup.c: (which can be invoked in "backup backup foo" or "backup restore foo")

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define CMD_BACKUP 0
#define CMD_RESTORE 1

#define BACKUP_DIRECTORY "/usr/share/backup"
#define FORBIDDEN_DIRECTORY "/etc"

static
int copyFile(char* src, char* dst)
{
  char buffer[3072]; /* 3K ought to be enough for anyone*/
  unsigned int i, len;
  FILE *source, *dest;
  int c;

  source = fopen(src, "r");
  if (source == NULL) {
    fprintf(stderr, "Failed to open source file\n");
    return -1;
  }

  i = 0;
  c = fgetc(source);
  while (c != EOF) {
    buffer[i]  = (unsigned char) c;
    c = fgetc(source);
    i++;
  }

  len = i;
  fclose(source);

  dest = fopen(dst, "w");
  if (dest == NULL) {
    fprintf(stderr, "Failed to open destination file\n");
    return -1;
  }

  for(i = 0; i < len; i++)
    fputc(buffer[i], dest);

  fclose(dest);

  return 0;
}

static
int restorePermissions(char* target)
{
  pid_t pid;
  int status;
  char *user, *userid, *ptr;
  FILE *file;
  char buffer[64];
  mode_t mode;

  // execute "chown" to assign file ownership to user
  pid = fork();

  // error
  if (pid < 0) {
    fprintf(stderr, "Fork failed\n");
    return -1;
  }

  // parent
  if (pid > 0) {
    waitpid(pid, &status, 0);
    if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
      return -1;
  }
  else {

    // child
    // retrieve username
    user = getenv("USER");
    // retrieve corresponding userid
    file = fopen("/etc/passwd", "r");
    if (file == NULL) {
      fprintf(stderr, "Failed to open password file\n");
      return -1;
    }
    userid = NULL;
    while (!feof(file)) {
      if (fgets(buffer, sizeof(buffer), file) != NULL) {
    ptr = strtok(buffer, ":");
    if (strcmp(ptr, user) == 0) {
      strtok(NULL, ":"); // password
      userid = strtok(NULL, ":"); // userid
      ptr = strtok(NULL, ":"); // group
      *ptr = '\0';
      break;
    }
      }
    }

    if (userid != NULL)
      execlp("/bin/chown", "/bin/chown", userid, target, NULL);

    // reached only in case of error
    return -1;
  }

  mode = S_IRUSR | S_IWUSR | S_IEXEC;
  chmod(target, mode);

  return 0;
}

static
void usage(char* parameter)
{
  char newline = '\n';
  char output[96];
  char buffer[96];

  snprintf(buffer, sizeof(buffer),
        "Usage: %.60s backup|restore pathname%c", parameter, newline);

  sprintf(output, buffer);
  printf(output);
}

int main(int argc, char* argv[])
{
  int cmd;
  char *path, *ptr;
  char *forbidden = FORBIDDEN_DIRECTORY;
  char *src, *dst, *buffer;
  struct stat buf;

  if (argc != 3) {
    usage(argv[0]);
    return 1;
  }

  if (strcmp("backup", argv[1]) == 0) {
    cmd = CMD_BACKUP;
  }
  else if (strcmp("restore", argv[1]) == 0) {
    cmd = CMD_RESTORE;
  } else {
    usage(argv[0]);
    return 1;
  }

  path = argv[2];

  // prevent access to forbidden directory
  ptr = realpath(path, NULL);
  if (ptr != NULL && strstr(ptr, forbidden) == ptr) {
    fprintf(stderr, "Not allowed to access target/source %s\n", path);
    return 1;
  }

  // set up paths for copy operation
  buffer = malloc(strlen(BACKUP_DIRECTORY) + 1 + strlen(path) + 1);
  if (buffer == NULL) {
    fprintf(stderr, "Failed to allocate memory\n");
    return 1;
  }

  if (cmd == CMD_BACKUP) {
    src = path;

    dst = buffer;
    strcpy(dst, BACKUP_DIRECTORY);
    strcat(dst, "/");
    strcat(dst, path);
  }
  else {
    src = buffer;
    strcpy(src, BACKUP_DIRECTORY);
    strcat(src, "/");
    strcat(src, path);

    dst = path;

    // don't overwrite existing file if we don't own it
    if (stat(dst, &buf) == 0 && buf.st_uid != getuid()) {
      fprintf(stderr, "Not your file: %s\n", dst);
      return 1;
    }
  }

  // perform actual backup/restore operation
  if (copyFile(src, dst) < 0)
    return 1;

  // grant user access to restored file
  if (cmd == CMD_RESTORE) {
    if (restorePermissions(path) < 0)
      return 1;
  }

  return 0;
}
</code>```

And something useful:

```<code>  // one way to invoke backup
  //system("/usr/local/bin/backup backup foo");

  // another way
  args[0] = TARGET; args[1] = "backup";
  args[2] = "foo"; args[3] = NULL;

  env[0] = NULL;
  if (execve(TARGET, args, env) < 0)
    fprintf(stderr, "execve failed.\n");
  exit(0);
</code>```

答:
I am not a security expert, but the comment here

```<code>char buffer[3072]; /* 3K ought to be enough for anyone*/
</code>```

is telling :-) So as you have guessed, there is a possibility for buffer overflow here. The buffer is in fact used to read the contents of the input file in. So try it with a file longer than 3K.

Now, since buffer is local, it is allocated on the stack. Thus by overflowing, you can overwrite the contents of the stack, including the return address and local variables within the caller stack frame. This is the theory as far as I know, I can't give you any more practical details though.

Title: Exploit a backup program using C

Body:
I'm doing an assignment of a security course that asks me to find 4 vulnerabilities of a backup program (setuid) and use each of them to gain root access (on a virtual linux machine with old version of gcc etc.).
There should be one of buffer overflow and one of format string.

Could anyone help me to point out where the 4 vulnerabilities are?
I think the buffer overflow can happened in copyFile().

The following is the code for backup.c: (which can be invoked in "backup backup foo" or "backup restore foo")

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define CMD_BACKUP 0
#define CMD_RESTORE 1

#define BACKUP_DIRECTORY "/usr/share/backup"
#define FORBIDDEN_DIRECTORY "/etc"

static
int copyFile(char* src, char* dst)
{
  char buffer[3072]; /* 3K ought to be enough for anyone*/
  unsigned int i, len;
  FILE *source, *dest;
  int c;

  source = fopen(src, "r");
  if (source == NULL) {
    fprintf(stderr, "Failed to open source file\n");
    return -1;
  }

  i = 0;
  c = fgetc(source);
  while (c != EOF) {
    buffer[i]  = (unsigned char) c;
    c = fgetc(source);
    i++;
  }

  len = i;
  fclose(source);

  dest = fopen(dst, "w");
  if (dest == NULL) {
    fprintf(stderr, "Failed to open destination file\n");
    return -1;
  }

  for(i = 0; i < len; i++)
    fputc(buffer[i], dest);

  fclose(dest);

  return 0;
}

static
int restorePermissions(char* target)
{
  pid_t pid;
  int status;
  char *user, *userid, *ptr;
  FILE *file;
  char buffer[64];
  mode_t mode;

  // execute "chown" to assign file ownership to user
  pid = fork();

  // error
  if (pid < 0) {
    fprintf(stderr, "Fork failed\n");
    return -1;
  }

  // parent
  if (pid > 0) {
    waitpid(pid, &status, 0);
    if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
      return -1;
  }
  else {

    // child
    // retrieve username
    user = getenv("USER");
    // retrieve corresponding userid
    file = fopen("/etc/passwd", "r");
    if (file == NULL) {
      fprintf(stderr, "Failed to open password file\n");
      return -1;
    }
    userid = NULL;
    while (!feof(file)) {
      if (fgets(buffer, sizeof(buffer), file) != NULL) {
    ptr = strtok(buffer, ":");
    if (strcmp(ptr, user) == 0) {
      strtok(NULL, ":"); // password
      userid = strtok(NULL, ":"); // userid
      ptr = strtok(NULL, ":"); // group
      *ptr = '\0';
      break;
    }
      }
    }

    if (userid != NULL)
      execlp("/bin/chown", "/bin/chown", userid, target, NULL);

    // reached only in case of error
    return -1;
  }

  mode = S_IRUSR | S_IWUSR | S_IEXEC;
  chmod(target, mode);

  return 0;
}

static
void usage(char* parameter)
{
  char newline = '\n';
  char output[96];
  char buffer[96];

  snprintf(buffer, sizeof(buffer),
        "Usage: %.60s backup|restore pathname%c", parameter, newline);

  sprintf(output, buffer);
  printf(output);
}

int main(int argc, char* argv[])
{
  int cmd;
  char *path, *ptr;
  char *forbidden = FORBIDDEN_DIRECTORY;
  char *src, *dst, *buffer;
  struct stat buf;

  if (argc != 3) {
    usage(argv[0]);
    return 1;
  }

  if (strcmp("backup", argv[1]) == 0) {
    cmd = CMD_BACKUP;
  }
  else if (strcmp("restore", argv[1]) == 0) {
    cmd = CMD_RESTORE;
  } else {
    usage(argv[0]);
    return 1;
  }

  path = argv[2];

  // prevent access to forbidden directory
  ptr = realpath(path, NULL);
  if (ptr != NULL && strstr(ptr, forbidden) == ptr) {
    fprintf(stderr, "Not allowed to access target/source %s\n", path);
    return 1;
  }

  // set up paths for copy operation
  buffer = malloc(strlen(BACKUP_DIRECTORY) + 1 + strlen(path) + 1);
  if (buffer == NULL) {
    fprintf(stderr, "Failed to allocate memory\n");
    return 1;
  }

  if (cmd == CMD_BACKUP) {
    src = path;

    dst = buffer;
    strcpy(dst, BACKUP_DIRECTORY);
    strcat(dst, "/");
    strcat(dst, path);
  }
  else {
    src = buffer;
    strcpy(src, BACKUP_DIRECTORY);
    strcat(src, "/");
    strcat(src, path);

    dst = path;

    // don't overwrite existing file if we don't own it
    if (stat(dst, &buf) == 0 && buf.st_uid != getuid()) {
      fprintf(stderr, "Not your file: %s\n", dst);
      return 1;
    }
  }

  // perform actual backup/restore operation
  if (copyFile(src, dst) < 0)
    return 1;

  // grant user access to restored file
  if (cmd == CMD_RESTORE) {
    if (restorePermissions(path) < 0)
      return 1;
  }

  return 0;
}

And something useful:

  // one way to invoke backup
  //system("/usr/local/bin/backup backup foo");

  // another way
  args[0] = TARGET; args[1] = "backup";
  args[2] = "foo"; args[3] = NULL;

  env[0] = NULL;
  if (execve(TARGET, args, env) < 0)
    fprintf(stderr, "execve failed.\n");
  exit(0);

Body:
I am not a security expert, but the comment here

char buffer[3072]; /* 3K ought to be enough for anyone*/

is telling :-) So as you have guessed, there is a possibility for buffer overflow here. The buffer is in fact used to read the contents of the input file in. So try it with a file longer than 3K.

Now, since buffer is local, it is allocated on the stack. Thus by overflowing, you can overwrite the contents of the stack, including the return address and local variables within the caller stack frame. This is the theory as far as I know, I can't give you any more practical details though.


问:
Angular 4+ best practice HTTP service
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

```<code>export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}
</code>```

TaskService

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}
</code>```

TaskComponent

```<code>export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}
</code>```

template

```<code><input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

答:
I think you have forget .json() in your service:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res.json(); //<-- here
            });
    }
}
</code>```

If you don't do this, the result is an Response object with more information about the request (like statusCode, body, ...) https://developer.mozilla.org/en-US/docs/Web/API/Response

For futher

You use your result structure in your application, it's not very good. You couple your code to the API.

You have a good idea to have an interface to cast the result, like this you don't have any type in your code. This interface it's a DTO.

After this in your code you must have your own object than you control.

And in your service you can have a mapper:

```<code>@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http
            .get(serviceUrl)
            .map(res => this.mapper(res.json());
    }

    private mapper(res: TaskDTO): MyOwnTask {
       return MyOwnTask(res.Title, res.User, res.TaskStatus)
    }
}
</code>```

Title: Angular 4+ best practice HTTP service

Body:
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}

TaskService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}

TaskComponent

export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}

template

<input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

Body:
I think you have forget .json() in your service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res.json(); //<-- here
            });
    }
}

If you don't do this, the result is an Response object with more information about the request (like statusCode, body, ...) https://developer.mozilla.org/en-US/docs/Web/API/Response

For futher

You use your result structure in your application, it's not very good. You couple your code to the API.

You have a good idea to have an interface to cast the result, like this you don't have any type in your code. This interface it's a DTO.

After this in your code you must have your own object than you control.

And in your service you can have a mapper:

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http
            .get(serviceUrl)
            .map(res => this.mapper(res.json());
    }

    private mapper(res: TaskDTO): MyOwnTask {
       return MyOwnTask(res.Title, res.User, res.TaskStatus)
    }
}


答:
You can return android.app.Fragment:

```<code>@Override
public android.app.Fragment getItem(int position) {
      return MyFragment.get(position);
}
</code>```

Or MyFragment must extend android.support.v4.app.Fragment :

```<code>class MyFragment extends android.support.v4.app.Fragment {}
</code>```

Title: Why am I not able to return a fragment?

Body:
You can return android.app.Fragment:

@Override
public android.app.Fragment getItem(int position) {
      return MyFragment.get(position);
}

Or MyFragment must extend android.support.v4.app.Fragment :

class MyFragment extends android.support.v4.app.Fragment {}


问:
Get message id after using /sendMail API
I am using Microsoft Graph to authorize our app and send mail with authenticated details:

```<code>https://graph.microsoft.com/v1.0/me/sendMail
</code>```

Everything works well but it only returns HTTP Status Code 202 without the message's id.

Is there a way to get the id of the the sent message?

答:
After sending the message, you can find the message in the Send Items folder using /mailfolders/SentItems/messages. You can apply a $filter to limit the results to only the message in question.

There isn't however a way to get the id itself. To get around this you can use extensions to add your own unique id to the message.

Using your own ID allows you to instantly $filter out everything except the exact message you are looking for. To do this you first construct a draft message. You then add your custom data and send the draft message.

Body:
I am using Microsoft Graph to authorize our app and send mail with authenticated details:

https://graph.microsoft.com/v1.0/me/sendMail

Everything works well but it only returns HTTP Status Code 202 without the message's id.

Is there a way to get the id of the the sent message?