问:
How to make an PHP array of Multipart Post data?
I am working on paypal integration. and make a request to provide evidence in disputes action api.I couldn't make an array of request body which is given below:

```<code>curl -v -X POST https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-27803/provide-evidence \
-H "Content-Type: multipart/related; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" \
-H "Authorization: Bearer Access-Token" \
-F 'input={
    "evidences": [{
      "evidence_type": "PROOF_OF_FULFILLMENT",
      "evidence_info": {
      "tracking_info": [{
       "carrier_name": "FEDEX",
       "tracking_number": "122533485"
   }]
},
"notes": "Test"
}
]
};type=application/json' \
-F 'file1=@NewDoc.pdf'
</code>```

In this request after -F flag i could not make an array because new structure of this json. would u like to make php array of this request api body?.

This is an array that i try send in request:

```<code>[
  'input' => [
  'evidences' => [
      [
          'evidence_type' => 'PROOF_OF_FULFILLMENT',
          'evidence_info' => [
              'tracking_info' => [
                  [
                      'carrier_name' => 'FEDEX',
                      'tracking_number' => '122533485'
                  ]
              ]
          ],
         'notes' => 'Test'
       ],
     ]
   ]
 ]
</code>```

答:
In PHP code , as you are try to use curl

```<code>        $url = "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-27803/provide-evidence";
        $data = [
  'input' => [
  'evidences' => [
      [
          'evidence_type' => 'PROOF_OF_FULFILLMENT',
          'evidence_info' => [
              'tracking_info' => [
                  [
                      'carrier_name' => 'FEDEX',
                      'tracking_number' => '122533485'
                  ]
              ]
          ],
         'notes' => 'Test'
       ],
     ]
   ]
 ]

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $response = curl_exec($ch);
        curl_close($ch);
</code>```

It's a basic post request like form submit from html as you need to send.

for more info you can visit https://www.php.net/manual/en/book.curl.php or can google to use curl with php

Body:
I am working on paypal integration. and make a request to provide evidence in disputes action api.I couldn't make an array of request body which is given below:

curl -v -X POST https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-27803/provide-evidence \
-H "Content-Type: multipart/related; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" \
-H "Authorization: Bearer Access-Token" \
-F 'input={
    "evidences": [{
      "evidence_type": "PROOF_OF_FULFILLMENT",
      "evidence_info": {
      "tracking_info": [{
       "carrier_name": "FEDEX",
       "tracking_number": "122533485"
   }]
},
"notes": "Test"
}
]
};type=application/json' \
-F 'file1=@NewDoc.pdf'

In this request after -F flag i could not make an array because new structure of this json. would u like to make php array of this request api body?.

This is an array that i try send in request:

[
  'input' => [
  'evidences' => [
      [
          'evidence_type' => 'PROOF_OF_FULFILLMENT',
          'evidence_info' => [
              'tracking_info' => [
                  [
                      'carrier_name' => 'FEDEX',
                      'tracking_number' => '122533485'
                  ]
              ]
          ],
         'notes' => 'Test'
       ],
     ]
   ]
 ]

Body:
In PHP code , as you are try to use curl

        $url = "https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-27803/provide-evidence";
        $data = [
  'input' => [
  'evidences' => [
      [
          'evidence_type' => 'PROOF_OF_FULFILLMENT',
          'evidence_info' => [
              'tracking_info' => [
                  [
                      'carrier_name' => 'FEDEX',
                      'tracking_number' => '122533485'
                  ]
              ]
          ],
         'notes' => 'Test'
       ],
     ]
   ]
 ]

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $response = curl_exec($ch);
        curl_close($ch);

It's a basic post request like form submit from html as you need to send.

for more info you can visit https://www.php.net/manual/en/book.curl.php or can google to use curl with php


来源: stackexchange

问:
Find and Return found string in an array
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

```<code>$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);
</code>```

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

答:
I'm not sure I 100% understand the question, but based on what I gather you'd like to use the above array (keys) as the needle, and the $line as a haystack?

Could do it in multiple ways, but something such as:

```<code>// Regex Method
// this depends on how big this array is though, however, otherwise this
// regex pattern could potentially be HUGE.
$pattern = sprintf('/(%s)/g', implode('|', array_map('preg_quote',array_keys($userconfig))));
if (preg_match($pattern,$line,$matches)){
  // $matches has all names found in the line
  // $userconfig[$match[1]]
}
</code>```

Otherwise you could keep iterating over the keys:

```<code>// "brute fore"
// this keeps checking for $name int he $line over and over, but no real
// optimizations going on here.
foreach (array_keys($userconfig) as $name)
{
  if (strpos($line,$name) !== false)
  {
    // $name was found in $line
    // $userconfig[$name]
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

Body:
I'm not sure I 100% understand the question, but based on what I gather you'd like to use the above array (keys) as the needle, and the $line as a haystack?

Could do it in multiple ways, but something such as:

// Regex Method
// this depends on how big this array is though, however, otherwise this
// regex pattern could potentially be HUGE.
$pattern = sprintf('/(%s)/g', implode('|', array_map('preg_quote',array_keys($userconfig))));
if (preg_match($pattern,$line,$matches)){
  // $matches has all names found in the line
  // $userconfig[$match[1]]
}

Otherwise you could keep iterating over the keys:

// "brute fore"
// this keeps checking for $name int he $line over and over, but no real
// optimizations going on here.
foreach (array_keys($userconfig) as $name)
{
  if (strpos($line,$name) !== false)
  {
    // $name was found in $line
    // $userconfig[$name]
  }
}


问:
Angular 2 Animation - boolean trigger
I have a form with one field and if that field is incorrect I want to shake it using animations

```<code><form [formGroup]="subscribeFormGroup">
    <mat-form-field [@error]="isError" class="al-subscribe-form-field">
            <input formControlName="email" matInput type="email">
            <mat-icon class="al-subscribe-icon" svgIcon="mail" (click)="onSubscribeClick()"></mat-icon>
    </mat-form-field>
</form>

animations: [
    trigger('error', [
        transition('false <=> true', useAnimation(shake)),
    ]),
],

public onSubscribeClick(): void {
        if (this.subscribeFormGroup.invalid) {
            this.isError = true;
        }
    ...
}
</code>```

Now it triggers only at first time when I try to send incorrect data, if I click button the second time etc, the field is not shaking

答:
You need to set the isError to false after each animation cycle. If not the  transition false <=> true will never trigger since the isError is still true. Try the following

public onSubscribeClick(): void {
  if (this.subscribeFormGroup.invalid) {
    this.isError = true;
    setTimeout(() => { this.isError = false }, 1000);    // <-- set the duration to the animation duration
  }
  ...
}
```

ContentLicense: CC BY-SA 4.0

Title: Angular 2 Animation - boolean trigger

Body:
I have a form with one field and if that field is incorrect I want to shake it using animations

<form [formGroup]="subscribeFormGroup">
    <mat-form-field [@error]="isError" class="al-subscribe-form-field">
            <input formControlName="email" matInput type="email">
            <mat-icon class="al-subscribe-icon" svgIcon="mail" (click)="onSubscribeClick()"></mat-icon>
    </mat-form-field>
</form>

animations: [
    trigger('error', [
        transition('false <=> true', useAnimation(shake)),
    ]),
],

public onSubscribeClick(): void {
        if (this.subscribeFormGroup.invalid) {
            this.isError = true;
        }
    ...
}

Now it triggers only at first time when I try to send incorrect data, if I click button the second time etc, the field is not shaking


问:
How to display message on the unit test result window for successful unit tests? c#
I gave written a data-driven unit test in C# and the unit test uses MS Visual Studio unit test framework. For unsuccessful unit tests, exception would be thrown and a message would be shown in the unit test result windows. I hope to display some message for successful unit tests and the messages should be shown in the unit test output window. How to do it? I have tried Console.WriteLine("Message") but it doesn't work as I wish. Any suggestions?</p>

答:
In 2020, VS2019, one can output text to the test output window like this.

For this code, you'll need a dependency on Microsoft.VisualStudio.TestPlatform and works best in conjunction with Microsoft.VisualStudio.TestTools.

The test output is accessible from the Test Explorer side-bar, as a link, only after the test was executed. Clicking on that link will open the full test output window.

```<code>using Microsoft.VisualStudio.TestPlatform.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace YourNamespace.Tests
{
    [TestClass]
    public class SomeTestClassName
    {

        [TestMethod]
        public void Test1()
        {
            ConsoleOutput.Instance.WriteLine("+++ This test line ends up in the test output +++", OutputLevel.Information);
        }
    }
}
</code>```

Body:
In 2020, VS2019, one can output text to the test output window like this.

For this code, you'll need a dependency on Microsoft.VisualStudio.TestPlatform and works best in conjunction with Microsoft.VisualStudio.TestTools.

The test output is accessible from the Test Explorer side-bar, as a link, only after the test was executed. Clicking on that link will open the full test output window.

using Microsoft.VisualStudio.TestPlatform.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace YourNamespace.Tests
{
    [TestClass]
    public class SomeTestClassName
    {

        [TestMethod]
        public void Test1()
        {
            ConsoleOutput.Instance.WriteLine("+++ This test line ends up in the test output +++", OutputLevel.Information);
        }
    }
}


问:
Material UI sub drawer from main drawer
I am struggling to find an example of a "sub" drawer that extends a main drawer from Material UI. https://material-ui.com/components/drawers/#drawer

I found this example of placing the drawer in a div (not the page) which can be adapted I think: Is there a way to show a Material-UI Drawer nested inside a Grid component?.

The expected behaviour would be a button or event on the main drawer that can open the sub drawer. Here is a screenshot example:

答:
I have prepared an example for nested drawer in material ui. In this example, you can open a drawer on left. After opening it, you find a button Show Nested Drawer and if you click on that button you will have another drawer.

```<code>import React from 'react';
import clsx from 'clsx';
import {makeStyles, useTheme} from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import List from '@material-ui/core/List';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import Button from "@material-ui/core/Button";

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    root: {
        display: 'flex',
    },
    appBar: {
        transition: theme.transitions.create(['margin', 'width'], {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen,
        }),
    },
    appBarShift: {
        width: `calc(100% - ${drawerWidth}px)`,
        marginLeft: drawerWidth,
        transition: theme.transitions.create(['margin', 'width'], {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    hide: {
        display: 'none',
    },
    drawer: {
        width: drawerWidth,
        flexShrink: 0,
    },
    drawerPaper: {
        width: drawerWidth,
    },
    drawerHeader: {
        display: 'flex',
        alignItems: 'center',
        padding: theme.spacing(0, 1),
        // necessary for content to be below app bar
        ...theme.mixins.toolbar,
        justifyContent: 'flex-end',
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(3),
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen,
        }),
        marginLeft: -drawerWidth,
    },
    contentShift: {
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
        marginLeft: 0,
    },
}));

export default function NestedDrawerExample() {
    const classes = useStyles();
    const theme = useTheme();
    const [drawerOpen, setDrawerOpen] = React.useState(false);
    const [subDrawerOpen, setSubDrawerOpen] = React.useState(false);

    const handleDrawerOpen = () => {
        setDrawerOpen(true);
    };

    const handleDrawerClose = () => {
        setDrawerOpen(false);
    };

    return (
        <div className={classes.root}>
            <CssBaseline/>
            <AppBar
                position="fixed"
                className={clsx(classes.appBar, {
                    [classes.appBarShift]: drawerOpen,
                })}
            >
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="open drawer"
                        onClick={handleDrawerOpen}
                        edge="start"
                        className={clsx(classes.menuButton, drawerOpen && classes.hide)}
                    >
                        <MenuIcon/>
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Nested Drawer Example
                    </Typography>
                </Toolbar>
            </AppBar>
            <Drawer
                className={classes.drawer}
                variant="persistent"
                anchor="left"
                open={drawerOpen}
                classes={{
                    paper: classes.drawerPaper,
                }}
            >
                <div className={classes.drawerHeader}>
                    <IconButton onClick={handleDrawerClose}>
                        {theme.direction === 'ltr' ? <ChevronLeftIcon/> : <ChevronRightIcon/>}
                    </IconButton>
                </div>
                <Divider/>
                <List>
                    {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
                        <ListItem button key={text}>
                            <ListItemIcon>{index % 2 === 0 ? <InboxIcon/> : <MailIcon/>}</ListItemIcon>
                            <ListItemText primary={text}/>
                        </ListItem>
                    ))}
                </List>
                <Divider/>
                <Button onClick={() => {
                    setSubDrawerOpen(true)
                }}>Open Nested Drawer</Button>
                <Drawer
                    className={classes.drawer}
                    variant="persistent"
                    anchor="left"
                    open={subDrawerOpen}
                    classes={{
                        paper: classes.drawerPaper,
                    }}
                >
                    <div className={classes.drawerHeader}>
                        <IconButton onClick={()=>{setSubDrawerOpen(false) }}>
                            {theme.direction === 'ltr' ? <ChevronLeftIcon/> : <ChevronRightIcon/>}
                        </IconButton>
                    </div>
                    <Divider/>
                    <List>
                        {['All mail', 'Trash', 'Spam'].map((text, index) => (
                            <ListItem button key={text}>
                                <ListItemIcon>{index % 2 === 0 ? <InboxIcon/> : <MailIcon/>}</ListItemIcon>
                                <ListItemText primary={text}/>
                            </ListItem>
                        ))}
                    </List>
                </Drawer>
            </Drawer>
            <main
                className={clsx(classes.content, {
                    [classes.contentShift]: drawerOpen,
                })}
            >
                <div className={classes.drawerHeader}/>
                <Typography paragraph>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
                    ut labore et dolore magna aliqua.
                </Typography>
                <Typography paragraph>
                    Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla
                    facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac
                    tincidunt.
                </Typography>
            </main>
        </div>
    );
}
</code>```

Title: Material UI sub drawer from main drawer

Body:
I have prepared an example for nested drawer in material ui. In this example, you can open a drawer on left. After opening it, you find a button Show Nested Drawer and if you click on that button you will have another drawer.

import React from 'react';
import clsx from 'clsx';
import {makeStyles, useTheme} from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import List from '@material-ui/core/List';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import Button from "@material-ui/core/Button";

const drawerWidth = 240;

const useStyles = makeStyles((theme) => ({
    root: {
        display: 'flex',
    },
    appBar: {
        transition: theme.transitions.create(['margin', 'width'], {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen,
        }),
    },
    appBarShift: {
        width: `calc(100% - ${drawerWidth}px)`,
        marginLeft: drawerWidth,
        transition: theme.transitions.create(['margin', 'width'], {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    hide: {
        display: 'none',
    },
    drawer: {
        width: drawerWidth,
        flexShrink: 0,
    },
    drawerPaper: {
        width: drawerWidth,
    },
    drawerHeader: {
        display: 'flex',
        alignItems: 'center',
        padding: theme.spacing(0, 1),
        // necessary for content to be below app bar
        ...theme.mixins.toolbar,
        justifyContent: 'flex-end',
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(3),
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.leavingScreen,
        }),
        marginLeft: -drawerWidth,
    },
    contentShift: {
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
        marginLeft: 0,
    },
}));

export default function NestedDrawerExample() {
    const classes = useStyles();
    const theme = useTheme();
    const [drawerOpen, setDrawerOpen] = React.useState(false);
    const [subDrawerOpen, setSubDrawerOpen] = React.useState(false);

    const handleDrawerOpen = () => {
        setDrawerOpen(true);
    };

    const handleDrawerClose = () => {
        setDrawerOpen(false);
    };

    return (
        <div className={classes.root}>
            <CssBaseline/>
            <AppBar
                position="fixed"
                className={clsx(classes.appBar, {
                    [classes.appBarShift]: drawerOpen,
                })}
            >
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="open drawer"
                        onClick={handleDrawerOpen}
                        edge="start"
                        className={clsx(classes.menuButton, drawerOpen && classes.hide)}
                    >
                        <MenuIcon/>
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Nested Drawer Example
                    </Typography>
                </Toolbar>
            </AppBar>
            <Drawer
                className={classes.drawer}
                variant="persistent"
                anchor="left"
                open={drawerOpen}
                classes={{
                    paper: classes.drawerPaper,
                }}
            >
                <div className={classes.drawerHeader}>
                    <IconButton onClick={handleDrawerClose}>
                        {theme.direction === 'ltr' ? <ChevronLeftIcon/> : <ChevronRightIcon/>}
                    </IconButton>
                </div>
                <Divider/>
                <List>
                    {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
                        <ListItem button key={text}>
                            <ListItemIcon>{index % 2 === 0 ? <InboxIcon/> : <MailIcon/>}</ListItemIcon>
                            <ListItemText primary={text}/>
                        </ListItem>
                    ))}
                </List>
                <Divider/>
                <Button onClick={() => {
                    setSubDrawerOpen(true)
                }}>Open Nested Drawer</Button>
                <Drawer
                    className={classes.drawer}
                    variant="persistent"
                    anchor="left"
                    open={subDrawerOpen}
                    classes={{
                        paper: classes.drawerPaper,
                    }}
                >
                    <div className={classes.drawerHeader}>
                        <IconButton onClick={()=>{setSubDrawerOpen(false) }}>
                            {theme.direction === 'ltr' ? <ChevronLeftIcon/> : <ChevronRightIcon/>}
                        </IconButton>
                    </div>
                    <Divider/>
                    <List>
                        {['All mail', 'Trash', 'Spam'].map((text, index) => (
                            <ListItem button key={text}>
                                <ListItemIcon>{index % 2 === 0 ? <InboxIcon/> : <MailIcon/>}</ListItemIcon>
                                <ListItemText primary={text}/>
                            </ListItem>
                        ))}
                    </List>
                </Drawer>
            </Drawer>
            <main
                className={clsx(classes.content, {
                    [classes.contentShift]: drawerOpen,
                })}
            >
                <div className={classes.drawerHeader}/>
                <Typography paragraph>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
                    ut labore et dolore magna aliqua.
                </Typography>
                <Typography paragraph>
                    Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla
                    facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac
                    tincidunt.
                </Typography>
            </main>
        </div>
    );
}


问:
Convert basic array to PHP array
I have an array that I pull that looks like this:

[157966745,275000353,43192565,305328212]...

How do I go about taking that "string" and converting it to a PHP array which I can then manipulate.

答:
This looks like JSON, so you can use json_decode:

```<code>$str = "[157966745,275000353,43192565,305328212]";
$data = json_decode($str);
</code>```

Title: Convert basic array to PHP array

Body:
This looks like JSON, so you can use json_decode:

$str = "[157966745,275000353,43192565,305328212]";
$data = json_decode($str);


问:
Expand card view height to height of contained exoplayer, crop only left and right sides of expoplayer
I have an ex0player in a RecyclerView of CardViews. The height of the exoplayer needs to be changed programmatically based on the height of the video contained. This height value is passed returned from the API call in pixels. Here is the layout of the ViewHolder:

```<code><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:cardCornerRadius="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/communityPlayableCl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >

        <com.google.android.exoplayer2.ui.PlayerView
            android:id="@+id/toroPlayerView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@color/transparent"
            android:visibility="invisible"
            app:controller_layout_id="@layout/v_player_controls"
            app:keep_content_on_player_reset="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/communityPlayableIv"
            app:player_layout_id="@layout/toro_exo_player_view"
            app:resize_mode="zoom"
            app:show_buffering="when_playing"
            app:shutter_background_color="@android:color/transparent"
            app:surface_type="texture_view"
            app:use_controller="false" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/communityPlayableIv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:background="@color/black"
            android:scaleType="centerCrop"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteY="0dp"
            tools:src="@color/alpha_grey" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/volumeIv"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_gravity="bottom|end"
            android:padding="15dp"
            android:src="@drawable/ic_volume_off"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>
</code>```

Here is how I am adjusting the height and aspect ratio:

```<code>   if (model.mediaHeight != 0 && model.mediaHeight != null ) {
            communityPlayableCl.requestLayout()
            communityPlayableCl.layoutParams.height = model.mediaHeight

        }

    val constraintSet = ConstraintSet()
    constraintSet.clone(communityPlayableCl)
    constraintSet.setDimensionRatio(itemView.id,model.mediaAspectRatio)
    constraintSet.applyTo(communityPlayableCl)
</code>```

This crops the top and bottom of a 640x640 video

答: I ended up setting the dimensions of the view manually using the passed aspect ratio</p>

Body:
I have an ex0player in a RecyclerView of CardViews. The height of the exoplayer needs to be changed programmatically based on the height of the video contained. This height value is passed returned from the API call in pixels. Here is the layout of the ViewHolder:

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:cardCornerRadius="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/communityPlayableCl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >

        <com.google.android.exoplayer2.ui.PlayerView
            android:id="@+id/toroPlayerView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@color/transparent"
            android:visibility="invisible"
            app:controller_layout_id="@layout/v_player_controls"
            app:keep_content_on_player_reset="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/communityPlayableIv"
            app:player_layout_id="@layout/toro_exo_player_view"
            app:resize_mode="zoom"
            app:show_buffering="when_playing"
            app:shutter_background_color="@android:color/transparent"
            app:surface_type="texture_view"
            app:use_controller="false" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/communityPlayableIv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:background="@color/black"
            android:scaleType="centerCrop"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteY="0dp"
            tools:src="@color/alpha_grey" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/volumeIv"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_gravity="bottom|end"
            android:padding="15dp"
            android:src="@drawable/ic_volume_off"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

Here is how I am adjusting the height and aspect ratio:

   if (model.mediaHeight != 0 && model.mediaHeight != null ) {
            communityPlayableCl.requestLayout()
            communityPlayableCl.layoutParams.height = model.mediaHeight

        }

    val constraintSet = ConstraintSet()
    constraintSet.clone(communityPlayableCl)
    constraintSet.setDimensionRatio(itemView.id,model.mediaAspectRatio)
    constraintSet.applyTo(communityPlayableCl)

This crops the top and bottom of a 640x640 video


问:
How to check if string character is a space?
I've just started programming in C#. I'm trying to build a simple Vigenere text encryption tool as a personal project.

My problem should be very easy to fix, yet it's really stressing me out to find the error. In my code I'm trying to do a simple check to see whether or not the character in my string is a space; I have set up my if statement properly yet it is skipping the first test and moving to the else if, even when the first test is true. Id really like some help on this one.

My problem area is at the bottom.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class fun2013
{
public static void Main()
{
    Console.WriteLine("fun 2013");
    string UserName;
    do
    {
        Console.Write("LOGIN//: ");
        UserName = Console.ReadLine();
    }
    while(UserName != "Max");
    Console.WriteLine(("Hello ") + (UserName) + (", enter your key below."));

                //USER ENTERS TEXT AT THIS POINT

    string loweredPass = Console.ReadLine().ToLower();
        Console.WriteLine("Changing CASE...");
        Console.WriteLine(loweredPass);
    string Strippedpass = loweredPass.Replace(" ","");
        Console.WriteLine("STRIPPING SPACES...");
        Console.WriteLine(Strippedpass);
    int passLength = Strippedpass.Length;
        Console.WriteLine("Enter your message below.");
    string userMessage = Console.ReadLine();
    int MessageLength = userMessage.Length;

                //BEGIN PROCESSING STRINGS INTO ARRAYS

    string temp = "";
    StringBuilder bcon = new StringBuilder();
    char [] passArray = Strippedpass.ToCharArray();
    char [] messArray = userMessage.ToCharArray();
    string letterf = "";

    for(int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
        {
        >>> if (messArray[i].ToString() == " ")
            {
                letterf = " ";
            }
        else if (messArray[i].ToString() != " ")
            {
                letterf = passArray[i].ToString();
            }
            if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
                {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
        temp = letterf;
        bcon.Append(temp);
        }

    Console.WriteLine();
    Console.WriteLine(bcon);

    Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine(); //KILL APPLICATION
}
}
</code>```

Thanks for the help everyone, but after further inspection I noticed I made an error in my for loop. I was resetting the message array reader using the same interval as the key array (int i). I changed it to use the correct integer, "j". I also put the "temp" string updater and string builder into each if statement in the loop. It's now running correctly.

```<code>    for (int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
    {

    if (messArray[j].ToString() != " ")
        {
            letterf = passArray[i].ToString();
            temp = letterf;
            bcon.Append(temp);
        }

    else if (messArray[j].ToString() == " ")
        {
            letterf = " ";
            temp = letterf;
            bcon.Append(temp);
        }

    if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
        {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
    }
</code>```

答:
You should be able to do this:</p>

```<code>if (messArray[i] == ' ') // to check if the char is a single space
</code>```

Body:
I've just started programming in C#. I'm trying to build a simple Vigenere text encryption tool as a personal project.

My problem should be very easy to fix, yet it's really stressing me out to find the error. In my code I'm trying to do a simple check to see whether or not the character in my string is a space; I have set up my if statement properly yet it is skipping the first test and moving to the else if, even when the first test is true. Id really like some help on this one.

My problem area is at the bottom.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class fun2013
{
public static void Main()
{
    Console.WriteLine("fun 2013");
    string UserName;
    do
    {
        Console.Write("LOGIN//: ");
        UserName = Console.ReadLine();
    }
    while(UserName != "Max");
    Console.WriteLine(("Hello ") + (UserName) + (", enter your key below."));

                //USER ENTERS TEXT AT THIS POINT

    string loweredPass = Console.ReadLine().ToLower();
        Console.WriteLine("Changing CASE...");
        Console.WriteLine(loweredPass);
    string Strippedpass = loweredPass.Replace(" ","");
        Console.WriteLine("STRIPPING SPACES...");
        Console.WriteLine(Strippedpass);
    int passLength = Strippedpass.Length;
        Console.WriteLine("Enter your message below.");
    string userMessage = Console.ReadLine();
    int MessageLength = userMessage.Length;

                //BEGIN PROCESSING STRINGS INTO ARRAYS

    string temp = "";
    StringBuilder bcon = new StringBuilder();
    char [] passArray = Strippedpass.ToCharArray();
    char [] messArray = userMessage.ToCharArray();
    string letterf = "";

    for(int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
        {
        >>> if (messArray[i].ToString() == " ")
            {
                letterf = " ";
            }
        else if (messArray[i].ToString() != " ")
            {
                letterf = passArray[i].ToString();
            }
            if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
                {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
        temp = letterf;
        bcon.Append(temp);
        }

    Console.WriteLine();
    Console.WriteLine(bcon);

    Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine(); //KILL APPLICATION
}
}

Thanks for the help everyone, but after further inspection I noticed I made an error in my for loop. I was resetting the message array reader using the same interval as the key array (int i). I changed it to use the correct integer, "j". I also put the "temp" string updater and string builder into each if statement in the loop. It's now running correctly.

    for (int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
    {

    if (messArray[j].ToString() != " ")
        {
            letterf = passArray[i].ToString();
            temp = letterf;
            bcon.Append(temp);
        }

    else if (messArray[j].ToString() == " ")
        {
            letterf = " ";
            temp = letterf;
            bcon.Append(temp);
        }

    if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
        {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
    }

Body:
You should be able to do this:

if (messArray[i] == ' ') // to check if the char is a single space


问:
How to know the address of the webpage from which  was clicked?
I have a login.asp page. Whenever the session expires, the user is given a link to the login page to log in. After logging in, users need to go back to the original page from which the link was clicked. How do I get the address of that webpage?

答:
There is a property of the document object called referrer

For example link to your website was clicked from http://example.com, you can use document.referrer to get http://example.com

Ref - https://www.w3schools.com/jsref/prop_doc_referrer.asp

Title: How to know the address of the webpage from which <a href="present page"> was clicked?


问:
Correct Approach WP Custom Taxonomy and Categories
I have number of categories based on different basketball leagues League A, League B, League C and so on. What I'm trying to do is for each league to have a custom taxonomy for each season 2006-2007,2007-2008,2008-2009 so I can show the posts only for that season Category: League A -> Season: 2006-2007 -> Posts.

So far I've created the following taxonomy for post Post Type:

```<code>add_action( 'init', 'create_seasons' );

function create_seasons() {
    $labels = array(
        'name'                           => 'Seasons',
        'singular_name'                  => 'Season',
        'search_items'                   => 'Search Seasons',
        'all_items'                      => 'All Seasons',
        'edit_item'                      => 'Edit Season',
        'update_item'                    => 'Update Season',
        'add_new_item'                   => 'Add New Season',
        'new_item_name'                  => 'New Season Name',
        'menu_name'                      => 'Seasons',
        'view_item'                      => 'View Season',
        'popular_items'                  => 'Popular Season',
        'separate_items_with_commas'     => 'Separate Season with commas',
        'add_or_remove_items'            => 'Add or remove Season',
        'choose_from_most_used'          => 'Choose from the most used seasons',
        'not_found'                      => 'No seasons found'
    );

    register_taxonomy(
        'seasons',
        'post',
        array(
            'label' => __( 'Season' ),
            'hierarchical' => false,
            'labels' => $labels,
            'public' => true,
            'show_in_nav_menus' => false,
            'show_tagcloud' => false,
            'show_admin_column' => true,
            'rewrite' => array(
                'slug' => 'seasons'
            )
        )
    );
}
</code>```

Now if I want to show all posts from category League A during the season taxonomy 2008-2009 I can use the URL parameter ?seasons=2008-2009. Full URL http://localhost/site/category/league-a/?seasons=2008-2009

What bothers me is that I want to show as a default the posts from the current season 2019-2020 without using the URL parameter ?seasons=2019-2020 for each category.

Example:
http://localhost/site/category/league-a/ -> Show posts from seasons taxonomy 2019-2020 only.

Is there a way to make this work? Rewrite rule?

Also do you think my approach is correct with what I'm trying to do?

Thank you

答:
I think there are multiple ways to achive that. My suggestion would be to create a custom query on your term archive page.

Please have a look here first: https://developer.wordpress.org/themes/basics/template-hierarchy/

In Wordpress you can create your custom category-{term}.php page, which in your case would be called category-league-a.php. Make a copy of your category.php in your theme folder, or use an example out of wordpress themes (i.e. twentynineteen), and copy the code.

Inside of your new archive page (WP will recognize it automatically) remove the post loop. You now create your own post query with your taxonomy term.

Have a look at: https://developer.wordpress.org/reference/classes/wp_query/

You get all posts that have a certain category term and a seasons term.

```<code>$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'league-a',
        ),
        array(
            'taxonomy' => 'seasons',
            'field'    => 'slug',
            'terms'    => '2019-2020',
        ),
    ),
);
$current_season_query = new WP_Query( $args );
</code>```

You can now loop through your posts:

```<code><?php
// The Loop
if ( $current_season_query ->have_posts() ) {
    while ( $current_season_query ->have_posts() ) {
        $current_season_query ->the_post();
            // echo get_the_title().'<br>'; or whatever
    }
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}
?>
</code>```

It is important that you reset the post data to the orignal query, as it is done in the code above. Otherwise you could get in conflict with other queries on your page.

So you now have defined the page template for your category term. You created a custom query to only show the posts that additionally have the taxonomy term of the current season.

Hope this helps!

EDIT: Using only one category page template for all terms

You can also use variables in your tax_query 'category' and 'terms'.

```<code>        'taxonomy' => 'category',
        'field'    => 'slug',
        'terms'    => $current_category,
</code>```

and

```<code>        'taxonomy' => 'seasons',
        'field'    => 'slug',
        'terms'    => $current_season,
</code>```

In the $current_category you save the slug or your current viewing category term and in $current_season the slug of your taxonomy term.

Other solution: Check if there is a parameter in the url string

But it now comes to my mind that it would be another solution to look for the parameter in the url and only change the query if there is no parameter set. This way you just need one single category.php which you have to adjust a litte bit:

1. Get the parameter form the url

```<code>global $wp;
// Get current page url
$current_url = home_url( add_query_arg( array(), $wp->request ) );
// Parse the URL to get array which contains its components
$url_components = parse_url($current_url);
// parse_str() function to parse the string passed via URL
parse_str($url_components['query'], $params);
</code>```

2. Check if parameter is not set and use another WP_Query in this case

```<code>if(!isset($params['seasons'])) {
    $current_season_query = new WP_Query( $args );
    // your code
}
else {
    // unchanged WP_Query, standard post loop in archive file
}
</code>```

Before the if you define the new WP_query as described in the first code block of this answer. In the else you put your standard post loop.

This way you only have to make changes to your category.php and not have to make files for all the category terms.

Body:
I have number of categories based on different basketball leagues League A, League B, League C and so on. What I'm trying to do is for each league to have a custom taxonomy for each season 2006-2007,2007-2008,2008-2009 so I can show the posts only for that season Category: League A -> Season: 2006-2007 -> Posts.

So far I've created the following taxonomy for post Post Type:

add_action( 'init', 'create_seasons' );

function create_seasons() {
    $labels = array(
        'name'                           => 'Seasons',
        'singular_name'                  => 'Season',
        'search_items'                   => 'Search Seasons',
        'all_items'                      => 'All Seasons',
        'edit_item'                      => 'Edit Season',
        'update_item'                    => 'Update Season',
        'add_new_item'                   => 'Add New Season',
        'new_item_name'                  => 'New Season Name',
        'menu_name'                      => 'Seasons',
        'view_item'                      => 'View Season',
        'popular_items'                  => 'Popular Season',
        'separate_items_with_commas'     => 'Separate Season with commas',
        'add_or_remove_items'            => 'Add or remove Season',
        'choose_from_most_used'          => 'Choose from the most used seasons',
        'not_found'                      => 'No seasons found'
    );

    register_taxonomy(
        'seasons',
        'post',
        array(
            'label' => __( 'Season' ),
            'hierarchical' => false,
            'labels' => $labels,
            'public' => true,
            'show_in_nav_menus' => false,
            'show_tagcloud' => false,
            'show_admin_column' => true,
            'rewrite' => array(
                'slug' => 'seasons'
            )
        )
    );
}

Now if I want to show all posts from category League A during the season taxonomy 2008-2009 I can use the URL parameter ?seasons=2008-2009. Full URL http://localhost/site/category/league-a/?seasons=2008-2009

What bothers me is that I want to show as a default the posts from the current season 2019-2020 without using the URL parameter ?seasons=2019-2020 for each category.

Example:
http://localhost/site/category/league-a/ -> Show posts from seasons taxonomy 2019-2020 only.

Is there a way to make this work? Rewrite rule?

Also do you think my approach is correct with what I'm trying to do?

Thank you

Body:
I think there are multiple ways to achive that. My suggestion would be to create a custom query on your term archive page.

Please have a look here first: https://developer.wordpress.org/themes/basics/template-hierarchy/

In Wordpress you can create your custom category-{term}.php page, which in your case would be called category-league-a.php. Make a copy of your category.php in your theme folder, or use an example out of wordpress themes (i.e. twentynineteen), and copy the code.

Inside of your new archive page (WP will recognize it automatically) remove the post loop. You now create your own post query with your taxonomy term.

Have a look at: https://developer.wordpress.org/reference/classes/wp_query/

You get all posts that have a certain category term and a seasons term.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'league-a',
        ),
        array(
            'taxonomy' => 'seasons',
            'field'    => 'slug',
            'terms'    => '2019-2020',
        ),
    ),
);
$current_season_query = new WP_Query( $args );

You can now loop through your posts:

<?php
// The Loop
if ( $current_season_query ->have_posts() ) {
    while ( $current_season_query ->have_posts() ) {
        $current_season_query ->the_post();
            // echo get_the_title().'<br>'; or whatever
    }
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}
?>

It is important that you reset the post data to the orignal query, as it is done in the code above. Otherwise you could get in conflict with other queries on your page.

So you now have defined the page template for your category term. You created a custom query to only show the posts that additionally have the taxonomy term of the current season.

Hope this helps!

EDIT: Using only one category page template for all terms

You can also use variables in your tax_query 'category' and 'terms'.

        'taxonomy' => 'category',
        'field'    => 'slug',
        'terms'    => $current_category,

and

        'taxonomy' => 'seasons',
        'field'    => 'slug',
        'terms'    => $current_season,

In the $current_category you save the slug or your current viewing category term and in $current_season the slug of your taxonomy term.

Other solution: Check if there is a parameter in the url string

But it now comes to my mind that it would be another solution to look for the parameter in the url and only change the query if there is no parameter set. This way you just need one single category.php which you have to adjust a litte bit:

1. Get the parameter form the url

global $wp;
// Get current page url
$current_url = home_url( add_query_arg( array(), $wp->request ) );
// Parse the URL to get array which contains its components
$url_components = parse_url($current_url);
// parse_str() function to parse the string passed via URL
parse_str($url_components['query'], $params);

2. Check if parameter is not set and use another WP_Query in this case

if(!isset($params['seasons'])) {
    $current_season_query = new WP_Query( $args );
    // your code
}
else {
    // unchanged WP_Query, standard post loop in archive file
}

Before the if you define the new WP_query as described in the first code block of this answer. In the else you put your standard post loop.

This way you only have to make changes to your category.php and not have to make files for all the category terms.


问:
split a string without adjacent characters that matched regex in java
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

```<code>String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));
</code>```

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

答:
Try this,

Long code but Basic logic.

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class B {

    public static void main(final String[] args) {

        final String x = "conditional&&operator and ampersand&Symbol.";

        final String mydata = x;
        String delimString = "";
        final Pattern pattern = Pattern.compile("[^\\&]\\&[^\\&]");
        final Matcher m = pattern.matcher(mydata);
        while (m.find()){
            delimString = m.group(0);
        }

    final String[] result = x.split(delimString); // Split using 'd&S'
    final String[] conResult = delimString.split("&"); //Split d&S in d and s
    System.out.println(result[0]+""+conResult[0]); // append d at the end of string
    System.out.println(conResult[1]+""+result[1]); // append s at the start of string

    }
}
</code>```

Body:
i am first to this site.
I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."

My regex-expression for spit is : "[^\\&]\\&[^\\&]"

My expectation is : [conditional&&operator and ampersand, Symbol]

But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

Body:
Try this,

Long code but Basic logic.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class B {

    public static void main(final String[] args) {

        final String x = "conditional&&operator and ampersand&Symbol.";

        final String mydata = x;
        String delimString = "";
        final Pattern pattern = Pattern.compile("[^\\&]\\&[^\\&]");
        final Matcher m = pattern.matcher(mydata);
        while (m.find()){
            delimString = m.group(0);
        }

    final String[] result = x.split(delimString); // Split using 'd&S'
    final String[] conResult = delimString.split("&"); //Split d&S in d and s
    System.out.println(result[0]+""+conResult[0]); // append d at the end of string
    System.out.println(conResult[1]+""+result[1]); // append s at the start of string

    }
}


问:
Docker - unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx
I just downloaded Docker Toolbox for Windows 10 64-bit today.  I'm going through the tutorial.  I'm receiving the following error when trying to build an image using a Dockerfile.

Steps:

Launched Docker Quickstart terminal.

testdocker after creating it.

Prepare Dockerfile as documented in "Build your own image" web link

ran the below command

    docker build -t docker-whale .

Error: $ docker build -t docker-whale .

unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\Users\Villanueva\Test\testdocker\Dockerfile: The system cannot find the file specified.

BTW: I tried several options mentioned @ https://github.com/docker/docker/issues/14339

```<code>docker info
</code>```

Output:

```<code>Containers: 4
 Running: 0
 Paused: 0
 Stopped: 4
Images: 2
Server Version: 1.10.1
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 20
 Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
 Volume: local
 Network: bridge null host
Kernel Version: 4.1.17-boot2docker
Operating System: Boot2Docker 1.10.1 (TCL 6.4.1); master : b03e158 - Thu Feb 11 22:34:01 UTC 2016
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 996.2 MiB
Name: default
ID: C7DS:CIAJ:FTSN:PCGD:ZW25:MQNG:H3HK:KRJL:G6FC:VPRW:SEWW:KP7B
Debug mode (server): true
 File Descriptors: 32
 Goroutines: 44
 System Time: 2016-02-19T17:37:37.706076803Z
 EventsListeners: 0
 Init SHA1:
 Init Path: /usr/local/bin/docker
 Docker Root Dir: /mnt/sda1/var/lib/docker
Labels:
 provider=virtualbox
</code>```

答:
Execute docker build -t getting-started . in your project directory and make sure Dockerfile is present and having no .txt extension.
If you are on Windows, check the 'file name extension' in the under the view tab in the
File Explorer to show whether .txt is there or not and remove it if the former is true.
Good Luck.

Body:
I just downloaded Docker Toolbox for Windows 10 64-bit today.  I'm going through the tutorial.  I'm receiving the following error when trying to build an image using a Dockerfile.

Steps:

Launched Docker Quickstart terminal.

testdocker after creating it.

Prepare Dockerfile as documented in "Build your own image" web link

ran the below command

    docker build -t docker-whale .

Error: $ docker build -t docker-whale .

unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\Users\Villanueva\Test\testdocker\Dockerfile: The system cannot find the file specified.

BTW: I tried several options mentioned @ https://github.com/docker/docker/issues/14339

docker info

Output:

Containers: 4
 Running: 0
 Paused: 0
 Stopped: 4
Images: 2
Server Version: 1.10.1
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 20
 Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
 Volume: local
 Network: bridge null host
Kernel Version: 4.1.17-boot2docker
Operating System: Boot2Docker 1.10.1 (TCL 6.4.1); master : b03e158 - Thu Feb 11 22:34:01 UTC 2016
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 996.2 MiB
Name: default
ID: C7DS:CIAJ:FTSN:PCGD:ZW25:MQNG:H3HK:KRJL:G6FC:VPRW:SEWW:KP7B
Debug mode (server): true
 File Descriptors: 32
 Goroutines: 44
 System Time: 2016-02-19T17:37:37.706076803Z
 EventsListeners: 0
 Init SHA1:
 Init Path: /usr/local/bin/docker
 Docker Root Dir: /mnt/sda1/var/lib/docker
Labels:
 provider=virtualbox


问:
Using PyVimeo error 404 when create a live event
I am just starting the integration of vimeo on my web platform for lives (I have a premium account)

Currently, the client connects well with this code:

```<code>vimeo.VimeoClient(token=settings.VIMEO_ACCESS_TOKEN,key=settings.VIMEO_CLIENT_ID,secret=settings.VIMEO_CLIENT_SECRET)
</code>```

Until then, no worries.

Then I do a test to create a live with the following code:

```<code>uri = '/me/live_events'
response= client.post(uri, data={'title':'test from api'})
</code>```

And I have a 404 feedback, I also did the test directly from vimeo with message :

Note that the only two fields required are client_id and title.

And my scopes token :

I don't see where my mistake may be

Thanks for your help ! :)

答:
Live API access is only available to Vimeo Enterprise users. It is not open to Premium users:

https://vimeo.zendesk.com/hc/en-us/articles/360042881411-Live-API-access

Body:
I am just starting the integration of vimeo on my web platform for lives (I have a premium account)

Currently, the client connects well with this code:

vimeo.VimeoClient(token=settings.VIMEO_ACCESS_TOKEN,key=settings.VIMEO_CLIENT_ID,secret=settings.VIMEO_CLIENT_SECRET)

Until then, no worries.

Then I do a test to create a live with the following code:

uri = '/me/live_events'
response= client.post(uri, data={'title':'test from api'})

And I have a 404 feedback, I also did the test directly from vimeo with message :

Note that the only two fields required are client_id and title.

And my scopes token :

I don't see where my mistake may be

Thanks for your help ! :)


问:
Close subnav once a different subnav is open with jQuery
Currently I have this working almost perfectly, but the user has the ability to open multiple sub-nav's at once, and I need any open sub-nav's to close when another one is open.

Basically, the jQuery that's beloe, I need to classes to be removed if a new sub-nav is clicked on, currently it only removes them if the same one is clicked.

HTML

```<code><nav class="st-menu" id="menu-4a">
    <ul>
        <li>
            <a href="#">Guidance Manual</a>
        </li>
        <li>
            <a href="#">Resource Directory</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Stormwater Plan Review Resources</a></li>
                <li><a href="#">Pilot Projects</a></li>
                <li><a href="#">Proprietary Products</a></li>
                <li><a href="#">Additional Resources</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Stormwater 101</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">Regulations</a></li>
                <li><a href="#">Stormwater Management</a></li>
                <li><a href="#">Stormwater Billing & Retrofits</a></li>
                <li><a href="#">Green City, Clean Waters</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Contact Us</a><div class="toggle-arrow"><img src="/assets/images/chevron-up-solid.svg"/></div>
            <ul class="reg-subnav">
                <li><a href="#">About Us</a></li>
                <li><a href="#">Development Review Contacts</a></li>
            </ul>
        </li>
    </ul>
</nav>
</code>```

jQuery

```<code>$(".toggle-arrow").click(function(){
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});
</code>```

答:
How about this one? You should remove class 'open-sub' from all of lists.</p>

```<code>$(".toggle-arrow").click(function(){
    $("nav.st-menu").find(".reg-subnav").removeClass('open-sub');
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');

    $("nav.st-menu").find(".arrow-image").removeClass('flip');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});
</code>```

Body:
Currently I have this working almost perfectly, but the user has the ability to open multiple sub-nav's at once, and I need any open sub-nav's to close when another one is open.

Basically, the jQuery that's beloe, I need to classes to be removed if a new sub-nav is clicked on, currently it only removes them if the same one is clicked.

HTML

            Guidance Manual

            Resource Directory

Stormwater Plan Review Resources

Pilot Projects

Proprietary Products

Additional Resources

            Stormwater 101

Regulations

Stormwater Management

Stormwater Billing & Retrofits

Green City, Clean Waters

            Contact Us

About Us

Development Review Contacts

jQuery

$(".toggle-arrow").click(function(){
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});

Body:
How about this one? You should remove class 'open-sub' from all of lists.

$(".toggle-arrow").click(function(){
    $("nav.st-menu").find(".reg-subnav").removeClass('open-sub');
    $(this).closest('li').find(".reg-subnav").toggleClass('open-sub');

    $("nav.st-menu").find(".arrow-image").removeClass('flip');
    $(this).closest('li').find('.arrow-image').toggleClass("flip");
});


问:
React rendering a loop inside a loop
Trying to loop inside a loop and getting error: value.forEach is not a function.

Dont know how to write this code inside a render

```<code>render(){

    return(
        Object.entries(this.props.detailOras).map(([key, value])=>{

       return(
            <div className="flex-row">
            <div className="flex-cont">
                <div>Laikas</div>
                <div>Temperatūra </div>
                <div>Vėjas</div>
                <div>Krituliai</div>
            </div>

                {value.forEach(day => {
                    return(
                        <div className="flex-cont">
                            <div>{day.forecastTimeUtc.slice(11,16)}</div>
                                <div>{day.airTemperature} </div>
                                <div>{day.windSpeed}</div>
                                <div>{day.totalPrecipitation}</div>
                            </div>
                          )
                })}
                     </div>
        )
                }

        ))}
</code>```

答:
Below should work provided value is populated as an array in later stages.

```<code>render(){

    return(
        Object.entries(this.props.detailOras).map(([key, value])=>{

       return(
            <div className="flex-row">
            <div className="flex-cont">
                <div>Laikas</div>
                <div>Temperatūra </div>
                <div>Vėjas</div>
                <div>Krituliai</div>
            </div>
                {(value.forecast || []).map(day => {
                    return(
                        <div className="flex-cont">
                            <div>{day.forecastTimeUtc.slice(11,16)}</div>
                            <div>{day.airTemperature} </div>
                            <div>{day.windSpeed}</div>
                            <div>{day.totalPrecipitation}</div>
                        </div>
                    )
                })}
            </div>
        )
    }
))}
</code>```

Title: React rendering a loop inside a loop

Body:
Trying to loop inside a loop and getting error: value.forEach is not a function.

Dont know how to write this code inside a render

render(){

    return(
        Object.entries(this.props.detailOras).map(([key, value])=>{

       return(

Laikas

Temperatūra

Vėjas

Krituliai

                {value.forEach(day => {
                    return(

{day.forecastTimeUtc.slice(11,16)}

{day.airTemperature}

{day.windSpeed}

{day.totalPrecipitation}

                          )
                })}

        )
                }

        ))}

Body:
Below should work provided value is populated as an array in later stages.

render(){

    return(
        Object.entries(this.props.detailOras).map(([key, value])=>{

       return(
            <div className="flex-row">
            <div className="flex-cont">
                <div>Laikas</div>
                <div>Temperatūra </div>
                <div>Vėjas</div>
                <div>Krituliai</div>
            </div>
                {(value.forecast || []).map(day => {
                    return(
                        <div className="flex-cont">
                            <div>{day.forecastTimeUtc.slice(11,16)}</div>
                            <div>{day.airTemperature} </div>
                            <div>{day.windSpeed}</div>
                            <div>{day.totalPrecipitation}</div>
                        </div>
                    )
                })}
            </div>
        )
    }
))}


问:
I want to figure out the error - TypeError: 'builtin_function_or_method' object is not subscriptable
Good afternoon.

Announced the ADX indicator function
(link Python: Average Directional Index (ADX) 2 Directional Movement System Calculation - https://www.youtube.com/watch?v=joOWm-GcHTw).

An error occurs during operation - "TypeError: 'builtin_function_or_method' object is not subscriptable".

on this line -
    TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1])
TypeError: 'builtin_function_or_method' object is not subscriptable

I will be glad of any help.
Thank.
The code is below.

```<code>def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z
    return d, TR

def DM(d,o,h,l,c,yo,yh,yl,yc):
    moveUp = h-yh
    moveDown = yl-l

    if 0 < moveUp > moveDown:
        PDM = moveUp
    else:
        PDM = 0

    if 0 < moveDown > moveUp:
        NDM = moveDown
    else:
        NDM = 0
    return d,PDM,NDM

def calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf):
    x = 1
    TRDates = []
    TrueRanges = []
    PosDMs = []
    NegDMs = []

    while x < len(date):
        TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) << error
        TRDates.append(TRDate)
        TrueRanges.append(TrueRange)

        DMdate,PosDM,NegDM = DM(date[x],openp[x],highp[x],lowp[x],closep[x],openp[x-1],highp[x-1],lowp[-1],closep[x-1]) << I assume that there will be the same error
        PosDMs.append(PosDM)
        NegDMs.append(NegDM)

        x +=1

    expPosDM = ExpMovingAverage(PosDMs,14)
    expNegDM = ExpMovingAverage(NegDMs,14)
    ATR = ExpMovingAverage(TrueRanges,14)

    xx = 0
    PDIs = []
    NDIs = []

    while xx < len(ATR):
        PDI = 100*(expPosDM[xx]/ATR[xx])
        PDIs.append(PDI)

        NDI = 100*(expNegDM[xx]/ATR[xx])
        NDIs.append(NDI)

        xx +=1

    return PDIs,NDIs
</code>```

答:
I'm sorry, I did not insert the last part of the code.

```<code>def ADX(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf,tfy):
    PositiveDI,NegativeDI = calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf)

    xxx = 0
    DXs =[]

    while xxx < len(date[1:]):
        DX = 100*( (abs(PositiveDI[xxx]-NegativeDI[xxx])
                    /(PositiveDI[xxx]+NegativeDI[xxx])))

        DXs.append(DX)

        xxx += 1

    ADX = ExpMovingAverage(DXs,14)

    return PositiveDI, NegativeDI, ADX
</code>```

And accordingly the call:

```<code>PositiveDI, NegativeDI, ADX = ta.ADX(data,open,high,low,closes,open,high,low,closes,14,14)
</code>```

here data on candles received through API Binance - https://api.binance.com/api/v1/klines?symbol=LTCBTC&interval=5m

eg:
[
  [
    1499040000000,      // data
    "0.01634790",       // Open
    "0.80000000",       // High
    "0.01575800",       // Low
    "0.01577100",       // Close
    "148976.11427815",  // volume
    1499644799999,      // Closing time
    "2434.19055334",    // Quota currency
    308,                // Number of deals
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "17928899.62484339" // Ignore
  ]
]

Body:
Good afternoon.

Announced the ADX indicator function
(link Python: Average Directional Index (ADX) 2 Directional Movement System Calculation - https://www.youtube.com/watch?v=joOWm-GcHTw).

An error occurs during operation - "TypeError: 'builtin_function_or_method' object is not subscriptable".

on this line -
    TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1])
TypeError: 'builtin_function_or_method' object is not subscriptable

I will be glad of any help.
Thank.
The code is below.

def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z
    return d, TR

def DM(d,o,h,l,c,yo,yh,yl,yc):
    moveUp = h-yh
    moveDown = yl-l

    if 0 < moveUp > moveDown:
        PDM = moveUp
    else:
        PDM = 0

    if 0 < moveDown > moveUp:
        NDM = moveDown
    else:
        NDM = 0
    return d,PDM,NDM

def calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf):
    x = 1
    TRDates = []
    TrueRanges = []
    PosDMs = []
    NegDMs = []

    while x < len(date):
        TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) << error
        TRDates.append(TRDate)
        TrueRanges.append(TrueRange)

        DMdate,PosDM,NegDM = DM(date[x],openp[x],highp[x],lowp[x],closep[x],openp[x-1],highp[x-1],lowp[-1],closep[x-1]) << I assume that there will be the same error
        PosDMs.append(PosDM)
        NegDMs.append(NegDM)

        x +=1

    expPosDM = ExpMovingAverage(PosDMs,14)
    expNegDM = ExpMovingAverage(NegDMs,14)
    ATR = ExpMovingAverage(TrueRanges,14)

    xx = 0
    PDIs = []
    NDIs = []

    while xx < len(ATR):
        PDI = 100*(expPosDM[xx]/ATR[xx])
        PDIs.append(PDI)

        NDI = 100*(expNegDM[xx]/ATR[xx])
        NDIs.append(NDI)

        xx +=1

    return PDIs,NDIs

Body:
I'm sorry, I did not insert the last part of the code.

def ADX(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf,tfy):
    PositiveDI,NegativeDI = calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf)

    xxx = 0
    DXs =[]

    while xxx < len(date[1:]):
        DX = 100*( (abs(PositiveDI[xxx]-NegativeDI[xxx])
                    /(PositiveDI[xxx]+NegativeDI[xxx])))

        DXs.append(DX)

        xxx += 1

    ADX = ExpMovingAverage(DXs,14)

    return PositiveDI, NegativeDI, ADX

And accordingly the call:

PositiveDI, NegativeDI, ADX = ta.ADX(data,open,high,low,closes,open,high,low,closes,14,14)

here data on candles received through API Binance - https://api.binance.com/api/v1/klines?symbol=LTCBTC&interval=5m

eg:
[
  [
    1499040000000,      // data
    "0.01634790",       // Open
    "0.80000000",       // High
    "0.01575800",       // Low
    "0.01577100",       // Close
    "148976.11427815",  // volume
    1499644799999,      // Closing time
    "2434.19055334",    // Quota currency
    308,                // Number of deals
    "1756.87402397",    // Taker buy base asset volume
    "28.46694368",      // Taker buy quote asset volume
    "17928899.62484339" // Ignore
  ]
]


问:
ServiceHost Class constructor
I'm refering the book Microsoft Windows Communication Foundation Step By Step. It says that

If you omit the base address
  information in the ServiceHost
  constructor, like this:

ServiceHost productsServiceHost = new
       ServiceHost(typeof(ProductsServiceImpl));

the WCF runtime will just use the
  address information specified in the
  application configuration file, and
  automatically listen for requests on
  all configured endpoints.

But when I try to declare the ServiceHost class using VS 2010, it gives only 2 option for ServiceHost class. Both of which need base url. Is above constructor removed in VS 2010 or am  I missing something?

答: Figured it out. It was missing the baseAddress element.</p>

Title: ServiceHost Class constructor


问:
Set default value to an existing item in DataTable for ComboBox
I use ComboBox as the Dropdown, and I assign a DataTable as the DataSource. How to set default value to an existing item in DataTable (I don't want to create a new item) and show that in drawdown (ComboBox)?

Here is my C# code

```<code>ComboBox statusDDL = new ComboBox();
DataTable allStatus = dataLayer.getAllStatus();
statusDDL.DataSource = allStatus;
statusDDL.DisplayMember = "Status";
statusDDL.ValueMember = "TaskStatusID";
</code>```

My DataTable has 2 columns and 6 rows, which are "statusID" and "Status". I want to set the default value to statusID = 2 and Status = "In Progress".

答:
You can get the index of the statusID =2 in your allStatus datatable
and then set that index to the selected index property.</p>

```<code>statusDDL.SelectedIndex = <position of statusid 2>;
</code>```

Body:
I use ComboBox as the Dropdown, and I assign a DataTable as the DataSource. How to set default value to an existing item in DataTable (I don't want to create a new item) and show that in drawdown (ComboBox)?

Here is my C# code

ComboBox statusDDL = new ComboBox();
DataTable allStatus = dataLayer.getAllStatus();
statusDDL.DataSource = allStatus;
statusDDL.DisplayMember = "Status";
statusDDL.ValueMember = "TaskStatusID";

My DataTable has 2 columns and 6 rows, which are "statusID" and "Status". I want to set the default value to statusID = 2 and Status = "In Progress".

Body:
You can get the index of the statusID =2 in your allStatus datatable
and then set that index to the selected index property.

statusDDL.SelectedIndex = <position of statusid 2>;


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答:
It's not just constants, it is a much broader issue with PHP's parsing engine. (You ought to see warnings in your logs.)

In PHP, "bare words" that it doesn't recognize are generally treated as strings that happen to be missing their quotes, and strings with a non-zero length tend to evaluate to true.

Try this:

```<code>$x =  thisisatest ;
$y = "thisisatest";
if($x == $y){
    echo("They are the same");
}
</code>```

You should see "They are the same".

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)

Body:
It's not just constants, it is a much broader issue with PHP's parsing engine. (You ought to see warnings in your logs.)

In PHP, "bare words" that it doesn't recognize are generally treated as strings that happen to be missing their quotes, and strings with a non-zero length tend to evaluate to true.

Try this:

$x =  thisisatest ;
$y = "thisisatest";
if($x == $y){
    echo("They are the same");
}

You should see "They are the same".


问:
Find all the faces between a source and a target faces
I've used the CGAL::Surface_mesh_shortest_path before to find the exact shortest path in a topological manner. But now I want something simpler that seem to be missing from the library that is finding the logical path from one face to another, returning a list of the faces in between.

Is there any way to do it without having to implement a tree search from scratch?

答:
CGAL offers a class Dual as a wrapper around a mesh. As the name suggests you obtain a dual graph.  If your mesh has boundaries you have to filter them out with a boost::filtered_graph. Now you can run boost::dijkstra_shortest_paths. Now for any vertex the predecessor map will lead you to the source vertex.

You can find a self contained example here.

You probably can add a visitor so that you stops by throwing an exception as soon the shortest path algorithm reaches your target vertex.


问:
"plot.new has not been called yet" error when graphing ggplot
Why does this happen/How can I troubleshoot this? Iv read some of the other entries about this error but am still confused, especially because when I run the following code without the bolded part, it runs fine, but with the bolded section included, i get this error.

Code:

```<code>ggplot(diamonds, aes(x = price)) + geom_histogram(binwidth = 500) +
axis(side = 1, at = seq(0, 20000, by = 500))
</code>```

Error:

```<code>Error in axis(side = 1, at = seq(0, 20000, by = 500)) :
  plot.new has not been called yet
</code>```

答:
axis is part of the graphics package not ggplot. So axis is looking for a plot not a ggplot.

Try

```<code>ggplot(diamonds, aes(x = price)) +
  geom_histogram(binwidth = 500) +
  scale_x_continuous(breaks = seq(0,20000, by = 500))
</code>```

Or in base graphics

```<code>hist(diamonds$price)
axis(side = 1, at = seq(0, 20000, by = 500))
</code>```

Body:
Why does this happen/How can I troubleshoot this? Iv read some of the other entries about this error but am still confused, especially because when I run the following code without the bolded part, it runs fine, but with the bolded section included, i get this error.

Code:

ggplot(diamonds, aes(x = price)) + geom_histogram(binwidth = 500) +
axis(side = 1, at = seq(0, 20000, by = 500))

Error:

Error in axis(side = 1, at = seq(0, 20000, by = 500)) :
  plot.new has not been called yet

Body:
axis is part of the graphics package not ggplot. So axis is looking for a plot not a ggplot.

Try

ggplot(diamonds, aes(x = price)) +
  geom_histogram(binwidth = 500) +
  scale_x_continuous(breaks = seq(0,20000, by = 500))

Or in base graphics

hist(diamonds$price)
axis(side = 1, at = seq(0, 20000, by = 500))


问:
is it possible to get rid of the relative paths on imports?
in any project with node.js, react, i set up the env variable:

```<code>NODE_PATH=src/
</code>```

and then i can do imports like

```<code>import COLORS from 'Constants/Colors'
</code>```

instead of

```<code>import COLORS from '../../../Constants/Colors'
</code>```

I just started with react-native, with expo and am trying to find a solution for this.

I tried the same approach of adding the env variable and it doesn't work

答:
install babel-plugin-module-resolver by

```<code>yarn add babel-plugin-module-resolver
</code>```

then add relative path in babel.config.js file like this

```<code>module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset' ],
    plugins: [
            [
                'module-resolver',
                {
                    alias: {
                       '@company'     : './src/company.json',
                       '@components'     : './src/components'

                }
            }
            ]
        ]
  };
};
</code>```

then you can use an absolute path like this

```<code>import TextLabel from './src/components/textLabel/index.js'
</code>```

To

```<code>import TextLabel from '@components/textLabel/index.js'
</code>```

Body:
in any project with node.js, react, i set up the env variable:

NODE_PATH=src/

and then i can do imports like

import COLORS from 'Constants/Colors'

instead of

import COLORS from '../../../Constants/Colors'

I just started with react-native, with expo and am trying to find a solution for this.

I tried the same approach of adding the env variable and it doesn't work

Body:
install babel-plugin-module-resolver by

yarn add babel-plugin-module-resolver

then add relative path in babel.config.js file like this

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset' ],
    plugins: [
            [
                'module-resolver',
                {
                    alias: {
                       '@company'     : './src/company.json',
                       '@components'     : './src/components'

                }
            }
            ]
        ]
  };
};

then you can use an absolute path like this

import TextLabel from './src/components/textLabel/index.js'

To

import TextLabel from '@components/textLabel/index.js'


问:
Vuetify datatable how fit the table vertically along with pagination footer stick to the bottom
I am having a hard time making the vuetify datatable fit to the screen along with pagination footer sticking to the bottom of the screen regardless of number of rows in the data table.

I tried to set the footer to use following css to always stick to the bottom but it doesn't work as expected

```<code>  #table .v-data-footer {
  position: absolute;
  bottom: 0;
}

#table .v-data-table__wrapper {
  height: 400px;
  margin-bottom: 100px;
  overflow: auto scroll;
}
</code>```

When the data table has more number of rows, it simply pushes the pagination control to the bottom and it is not visible until I scroll it down to the very bottom.One thing I also tried to do is to set a fixed height for the data table but this is not ideal because of the device sizes, for larger screen size it behaves really weird.

I have a codepen with a simple data table, when we increase the number of rows from pagination control, it loads more number of rows and the footer simply hidden because of height.
I expect the data table to have a height for the content so that user can scroll through the rows and the pagination control should always stick to the bottom no matter what the device size is.

I would really appreciate if anyone can help or give me any pointers on this.

答:
If you want the v-data-table fit screen. you can use position: fixed to the footer, and set a margin to wrapper (same as footer height):

```<code>#table .v-data-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: white;
}

#table .v-data-table__wrapper {
  margin-bottom: 60px;
}
</code>```

https://codepen.io/hans-felix/pen/MWaMENQ

Body:
I am having a hard time making the vuetify datatable fit to the screen along with pagination footer sticking to the bottom of the screen regardless of number of rows in the data table.

I tried to set the footer to use following css to always stick to the bottom but it doesn't work as expected

  #table .v-data-footer {
  position: absolute;
  bottom: 0;
}

#table .v-data-table__wrapper {
  height: 400px;
  margin-bottom: 100px;
  overflow: auto scroll;
}

When the data table has more number of rows, it simply pushes the pagination control to the bottom and it is not visible until I scroll it down to the very bottom.One thing I also tried to do is to set a fixed height for the data table but this is not ideal because of the device sizes, for larger screen size it behaves really weird.

I have a codepen with a simple data table, when we increase the number of rows from pagination control, it loads more number of rows and the footer simply hidden because of height.
I expect the data table to have a height for the content so that user can scroll through the rows and the pagination control should always stick to the bottom no matter what the device size is.

I would really appreciate if anyone can help or give me any pointers on this.

Body:
If you want the v-data-table fit screen. you can use position: fixed to the footer, and set a margin to wrapper (same as footer height):

#table .v-data-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: white;
}

#table .v-data-table__wrapper {
  margin-bottom: 60px;
}

https://codepen.io/hans-felix/pen/MWaMENQ


问:
Python-poetry error: Setting settings.virtualenvs.in-project does not exist
I am setting poetry to create virtual environments in the project directory.
I entered:

poetry config settings.virtualenvs.in-project true

and received error

[ValueError]
  Setting settings.virtualenvs.in-project does not exist

Also there is the text

home/alex/.poetry/lib/poetry/_vendor/py2.7/subprocess32.py:149: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability may suffer if your program uses threads.
    "program uses threads.", RuntimeWarning)

How can I solve the error?

It seems that error deals with version of the python.

I am using Ubuntu 16.04 version

Poetry version 1.0.5

答:
The config has changed with the release of poetry 1.0. The prefix settings is no longer needed. So just type poetry config virtualenvs.in-project true.

Concerning the subprocess warning: This seems to be just a warning and has no influence on the correct working of poetry. Also have a look at my comment in poetry's issue tracker.

@ptd: poetry can work with python2 and python3.


问:
WPF Button location in ToolBar
I have a vertical ToolBarTray and a ToolBar with buttons.
While most of the buttons must be in the upper part, I need one (Exit button) to be on the bottom.
But they all come one after another downwards.
Can you give me an idea on what should I do to put the last button apart from the main group, please?

Thank you!

答:
You could achieve it with two ToolBarTrays like this:

```<code>    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ToolBarTray Grid.Row="0" Background="White" IsLocked="True" Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Left" >
            <ToolBar Band="1" BandIndex="1" >
                <Button Content="Cut"/>
                <Button Content="Copy"/>
                <Button Content="Paste"/>
            </ToolBar>
        </ToolBarTray>
        <ToolBarTray Grid.Row="1" Background="White" IsLocked="True" Orientation="Vertical" VerticalAlignment="Bottom" HorizontalAlignment="Left" >
            <ToolBar Band="1" BandIndex="1" >
                <Button Content="Exit" />
            </ToolBar>
        </ToolBarTray>
    </Grid>
</code>```

Then it would look like this:

Title: WPF Button location in ToolBar

Body:
You could achieve it with two ToolBarTrays like this:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ToolBarTray Grid.Row="0" Background="White" IsLocked="True" Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Left" >
            <ToolBar Band="1" BandIndex="1" >
                <Button Content="Cut"/>
                <Button Content="Copy"/>
                <Button Content="Paste"/>
            </ToolBar>
        </ToolBarTray>
        <ToolBarTray Grid.Row="1" Background="White" IsLocked="True" Orientation="Vertical" VerticalAlignment="Bottom" HorizontalAlignment="Left" >
            <ToolBar Band="1" BandIndex="1" >
                <Button Content="Exit" />
            </ToolBar>
        </ToolBarTray>
    </Grid>

Then it would look like this:


问:
Android Firebase crashes doesn't send crash report in third party libs (or *.aar)
I found that I didn't receive crash issues which was registered in a third party libs attached to project as dependency or like *.aar. I mean, for example, like this:

```<code>implementation 'xxxx:2.1.1'
</code>```

I developed some library in my project and attached it as dependency to an app. I simulated some crash in this lib, but I didn't receive any crash report in Firebase. Moreover, I created the same library which is using NDK. But I also haven't any crash reports.

It seems that Firebase sends crashes which were detected only in the app, but we didn't send it from libs.
It's not a good, because previously, in Fabric, we got it.

I had followed to the instructions which described here
I had used:

```<code>dependencies {
    // Recommended: Add the Firebase SDK for Google Analytics.
    implementation 'com.google.firebase:firebase-analytics:17.4.2'

    // Add the Firebase Crashlytics SDK.
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}
</code>```

Does anybody have the same situation?

答:
Firebaser here -

There are a couple things going on here. First, what we expect to work:

Receiving Java crashes from a library. If you're initializing Crashlytics as normal in your main app process, we would expect it to be able to pick up crashes from a library/AAR that you're pulling in. Once compiled into an APK, the library code is all just app code, and Crashlytics should be able to report on it.

For example, if you're including a math library, and the Crashlytics initialization is occurring before a method call like mathlibrary.add(number1, number2), that method call should get captured and symbolicated.

Crashlytics initializing before library method calls would be the expected behavior, because in Android, as long as Firebase is configured correctly Crashlytics should be starting up automatically at the start of your app process. If you're doing any work to change this behavior in your app, it could be causing this issue. I'd need to know more about how you're actually initializing Crashlytics, since if you're trying to initalize Crashlytics in the library itself, or the library code itself spins up a Service, that could cause issues with reporting.

What doesn't work:

NDK reporting from a library. AARs can contain native code and Java code, but the Java specifically should be getting captured even if it's in a library.

However if you're in a situation where you would need to upload native symbol files to Crashlytics in order to get sensible stacktraces from your AAR, Crashlytics doesn't support this particular path yet.

Overall, what you're trying to do should work with Java code, and to diagnose your issue we'd need to know more about how you're setting up Crashlytics in your app and how you're setting up the library itself. Feel free to submit a support case with Firebase support as well with all that information.

Body:
I found that I didn't receive crash issues which was registered in a third party libs attached to project as dependency or like *.aar. I mean, for example, like this:

implementation 'xxxx:2.1.1'

I developed some library in my project and attached it as dependency to an app. I simulated some crash in this lib, but I didn't receive any crash report in Firebase. Moreover, I created the same library which is using NDK. But I also haven't any crash reports.

It seems that Firebase sends crashes which were detected only in the app, but we didn't send it from libs.
It's not a good, because previously, in Fabric, we got it.

I had followed to the instructions which described here
I had used:

dependencies {
    // Recommended: Add the Firebase SDK for Google Analytics.
    implementation 'com.google.firebase:firebase-analytics:17.4.2'

    // Add the Firebase Crashlytics SDK.
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}

Does anybody have the same situation?