问:
In JSX | React How can the prop be passed to the button state so the button state can load a new page?
Trying to go from the search using the react datepicker and then check available dates. Having some trouble passing the props to the btn so I can create the new page based on the date selected.

Everything is Imported correctly we can leave that out below is my Datapicker Component and the Btnsearch Component I need the pops to be used by.

I have tried to pass the prop in every element on the component, with the btn built in to the component. I have read its better to pass the props down the chain of elements. To children so I tried to do that lastly. Still can't seem to catch the Datepicked to even console.log it.Tried to build a alert as well.

```<code>
class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }
  state = {};
  render() {
    console.log(this.props.value);
    return (
      <>
        <FormGroup>
          <InputGroup className="input-group-alternative">
            <InputGroupAddon addonType="prepend">
              <InputGroupText
              >
                <i className="ni ni-calendar-grid-58" />
              </InputGroupText>
            </InputGroupAddon>
            <ReactDatetime
            value={this.state.value}
            onChange={this.handleChange}
            inputProps={{
              placeholder: "Date Picker Here"
            }}
            timeFormat={false}
            />
          </InputGroup>
        </FormGroup>
        <Btnsearch />
      </>
    );
  }
}

export default Datepicker;

</code>```

```<code>class Btnsearch extends React.Component {
    render() {
        return (
        <button value={this.props.value} className="btn btn-success search-card-btn">Search</button>
    );
    }
};

export default Btnsearch;

</code>```

I expect to console.log and alert the props been changed when the button is clicked in order to populate a new page. I get props undefined

答:
Just pass down the prop:

```<code> <Btnsearch value={this.state.value}/>
</code>```

Otherwise your component would never get it.

Edit: there was several issues in your code, I made a snippet for you to check.

https://stackblitz.com/edit/react-af37vl

Select a date, hit "search" and date will be logged in console.

Notice (from react-datetime docs):

Callback trigger when the date changes. The callback receives the
  selected moment object as only parameter, if the date in the input is
  valid. If the date in the input is not valid, the callback receives
  the value of the input (a string).

Body:
Trying to go from the search using the react datepicker and then check available dates. Having some trouble passing the props to the btn so I can create the new page based on the date selected.

Everything is Imported correctly we can leave that out below is my Datapicker Component and the Btnsearch Component I need the pops to be used by.

I have tried to pass the prop in every element on the component, with the btn built in to the component. I have read its better to pass the props down the chain of elements. To children so I tried to do that lastly. Still can't seem to catch the Datepicked to even console.log it.Tried to build a alert as well.

class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }
  state = {};
  render() {
    console.log(this.props.value);
    return (
      <>
        <FormGroup>
          <InputGroup className="input-group-alternative">
            <InputGroupAddon addonType="prepend">
              <InputGroupText
              >

              </InputGroupText>
            </InputGroupAddon>
            <ReactDatetime
            value={this.state.value}
            onChange={this.handleChange}
            inputProps={{
              placeholder: "Date Picker Here"
            }}
            timeFormat={false}
            />
          </InputGroup>
        </FormGroup>
        <Btnsearch />
      </>
    );
  }
}

export default Datepicker;

class Btnsearch extends React.Component {
    render() {
        return (
        <button value={this.props.value} className="btn btn-success search-card-btn">Search</button>
    );
    }
};

export default Btnsearch;

I expect to console.log and alert the props been changed when the button is clicked in order to populate a new page. I get props undefined

Body:
Just pass down the prop:

 <Btnsearch value={this.state.value}/>

Otherwise your component would never get it.

Edit: there was several issues in your code, I made a snippet for you to check.

https://stackblitz.com/edit/react-af37vl

Select a date, hit "search" and date will be logged in console.

Notice (from react-datetime docs):

Callback trigger when the date changes. The callback receives the
  selected moment object as only parameter, if the date in the input is
  valid. If the date in the input is not valid, the callback receives
  the value of the input (a string).


来源: stackexchange

问:
How to get known paths for linux
Windows has a concept of a Known Path with functions to retrieve them without hard-coding a path:

```<code>#include <filesystem>
#include <windows.h>
#include <ShlObj.h>
//...
std::filesystem::path GetAppDataPath() {
    namespace FS = std::filesystem;
    PWSTR ppszPath = nullptr;
    auto hr_path = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, nullptr, &ppszPath);
    bool success = SUCCEEDED(hr_path);
    if (success) {
        auto p = FS::path(ppszPath);
        ::CoTaskMemFree(ppszPath);
        p = FS::canonical(p);
        return p;
    }
    return {};
}
</code>```

Is there an equivalent for linux?

答:
Linux is an operating system kernel. It does not have a concept of user directories.

There are several Linux distributions. The filesystem structure is determined by the distro. Most distros conform to POSIX standard, and follow (to varying degree) the Filesystem Hierarchy Standard by Linux Foundation, which is similar to the directory structures of other UNIX like systems. That said, distributions generally allow the user to use the file system in unconventional configurations. For example, they don't typically force users home directory to be under /home.

POSIX specifies a few environment variables that are relevant to this context:

```<code>HOME
</code>```

The system shall initialize this variable at the time of login to be a pathname of the user's home directory.

```<code>TMPDIR
</code>```

This variable shall represent a pathname of a directory made available for programs that need a place to create temporary files.

Environment variables can be accessed using std::getenv in C++.

On desktop systems, the directory structure is also determined to some degree by the desktop environment, of which there are several available. freedesktop.org produces unofficial specifications for interoperability of different desktop environments. On DE's conforming to XDG Base Directory Specification should following environment variables be available:

$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.

$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.

$XDG_DATA_DIRS defines the preference-ordered set of base directories to search for data files in addition to the $XDG_DATA_HOME base directory. The directories in $XDG_DATA_DIRS should be seperated with a colon ':'.

If $XDG_DATA_DIRS is either not set or empty, a value equal to /usr/local/share/:/usr/share/ should be used.

freedesktop.org also provides a utility xdg-user-dirs:

xdg-user-dirs is a tool to help manage "well known" user directories like the desktop folder and the music folder. It also handles localization (i.e. translation) of the filenames.

$(XDG_CONFIG_HOME)/user-dirs.dirs specifies the current set of directories for the user. This file is in a shell format, so its easy to access from a shell script. This file can also be modified by users (manually or via applications) to change the directories used.

So, in case of FOLDERID_RoamingAppData, you should probably use one of $XDG_x depending on the use case, falling back to the appropriate default relative to $HOME as specified.

ContentLicense: CC BY-SA 4.0

Title: How to get known paths for linux

Body:
Windows has a concept of a Known Path with functions to retrieve them without hard-coding a path:

#include <filesystem>
#include <windows.h>
#include <ShlObj.h>
//...
std::filesystem::path GetAppDataPath() {
    namespace FS = std::filesystem;
    PWSTR ppszPath = nullptr;
    auto hr_path = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, nullptr, &ppszPath);
    bool success = SUCCEEDED(hr_path);
    if (success) {
        auto p = FS::path(ppszPath);
        ::CoTaskMemFree(ppszPath);
        p = FS::canonical(p);
        return p;
    }
    return {};
}

Is there an equivalent for linux?

Body:
Linux is an operating system kernel. It does not have a concept of user directories.

There are several Linux distributions. The filesystem structure is determined by the distro. Most distros conform to POSIX standard, and follow (to varying degree) the Filesystem Hierarchy Standard by Linux Foundation, which is similar to the directory structures of other UNIX like systems. That said, distributions generally allow the user to use the file system in unconventional configurations. For example, they don't typically force users home directory to be under /home.

POSIX specifies a few environment variables that are relevant to this context:

HOME

The system shall initialize this variable at the time of login to be a pathname of the user's home directory.

TMPDIR

This variable shall represent a pathname of a directory made available for programs that need a place to create temporary files.

Environment variables can be accessed using std::getenv in C++.

On desktop systems, the directory structure is also determined to some degree by the desktop environment, of which there are several available. freedesktop.org produces unofficial specifications for interoperability of different desktop environments. On DE's conforming to XDG Base Directory Specification should following environment variables be available:

$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.

$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.

$XDG_DATA_DIRS defines the preference-ordered set of base directories to search for data files in addition to the $XDG_DATA_HOME base directory. The directories in $XDG_DATA_DIRS should be seperated with a colon ':'.

If $XDG_DATA_DIRS is either not set or empty, a value equal to /usr/local/share/:/usr/share/ should be used.

freedesktop.org also provides a utility xdg-user-dirs:

xdg-user-dirs is a tool to help manage "well known" user directories like the desktop folder and the music folder. It also handles localization (i.e. translation) of the filenames.

$(XDG_CONFIG_HOME)/user-dirs.dirs specifies the current set of directories for the user. This file is in a shell format, so its easy to access from a shell script. This file can also be modified by users (manually or via applications) to change the directories used.

So, in case of FOLDERID_RoamingAppData, you should probably use one of $XDG_x depending on the use case, falling back to the appropriate default relative to $HOME as specified.


问:
How do you show underlying SQL query in EF Core?
At 3:15 from the end of this ".NET Core 2.0 Released!" video, Diego Vega shows a demo of new features in Entity Framework Core 2.0. As part of that, a dump of the underlying SQL is shown in the console app.

I have seen many answers on Stack Overflow suggesting that people use an SQL profiler to view the underlying queries. But now I'm curious: how can you do what Diego Vega did, and get the query to show right there in the application?

Update for .NET 6+: EF logging is enabled by default in development. See this GitHub issue

Update: Diego added "Microsoft.EntityFrameworkCore.Database.Command": "Information" to appsettings.Development.json. See How do you show underlying SQL query in EF Core? for more details.

答:
I'm sure the accepted answer works, but I wanted to know how to do this using DI so...</p>

```<code>private readonly ILoggerFactory loggerFactory;

public MyDataContext(DbContextOptions<MyDataContext> options, ILoggerFactory loggerFactory)
        : base(options)
{
    this.loggerFactory = loggerFactory;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // Allow null if you are using an IDesignTimeDbContextFactory
    if (loggerFactory != null)
    {
        if (Debugger.IsAttached)
        {
            // Probably shouldn't log sql statements in production
            optionsBuilder.UseLoggerFactory(this.loggerFactory);
        }
    }
}
</code>```

Body:
I'm sure the accepted answer works, but I wanted to know how to do this using DI so...

private readonly ILoggerFactory loggerFactory;

public MyDataContext(DbContextOptions<MyDataContext> options, ILoggerFactory loggerFactory)
        : base(options)
{
    this.loggerFactory = loggerFactory;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // Allow null if you are using an IDesignTimeDbContextFactory
    if (loggerFactory != null)
    {
        if (Debugger.IsAttached)
        {
            // Probably shouldn't log sql statements in production
            optionsBuilder.UseLoggerFactory(this.loggerFactory);
        }
    }
}


问:
Suppressing MSB3276: Found conflicts between different versions
Here is the scenario

A.dll references B.dll (2.0.0.0)

A.dll references C.dll and C.dll references B.dll (1.0.0.0)

Obviously, msbuild will invoke the warning below since B.dll versions conflict. Automatically it will pick the latest version since I denied creating app.config file automatically in csproj file.

Warning: MSB3276 - Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects"

And I do not want to redirect anything since neither one will work with each other versions.

Question:

How do I get rid of this warning or suppress it ?

Note: Both assemblies will be installed in GAC at the time of installation process so runtime references will resolve just fine. Sadly, there seems no way to indicate MSBuild to let go of this warning.

答:
As of Visual Studio 2017 / MSBuild 15, edit the project file and add the following to the Project\ProprtyGroup section:

```<code>  <PropertyGroup>
    <MSBuildWarningsAsMessages>MSB3276</MSBuildWarningsAsMessages>
  </PropertyGroup>
</code>```

Works on my instance of Visual Studio 15.9.11

Ritchie

ContentLicense: CC BY-SA 3.0

Body:
As of Visual Studio 2017 / MSBuild 15, edit the project file and add the following to the Project\ProprtyGroup section:

  <PropertyGroup>
    <MSBuildWarningsAsMessages>MSB3276</MSBuildWarningsAsMessages>
  </PropertyGroup>

Works on my instance of Visual Studio 15.9.11

Ritchie


问:
If I give row_cache_size_in_mb =5Gb in cassandra.yaml file, does cassandra reserves 5GB from Heap Memory?
I am running my cassandra cluster having memory  32 GB on each node,
And row cache capacity (row_cache_size_in_mb) 5GB,
Just want to know, does 5gb memory ram is reserved for row caching from my heap??</p>

答: It will let it grow to that size over time. Can use nodetool info to see the current size and limit and nodetool setcachecapacity to change it at runtime. Note that its kinda an estimate though and heap can grow a bit larger. I would be sure to test that the row_cache is actually improving things though since in a lot of cases having no row cache can be faster.


问:
Regex for patterns like [ABC], ABC and ABCxx where xx is a number
I have a text whose length can vary between 1 and 1000. I am looking to get the following sub strings extracted from the text.

Sub string of the form ABCxx/ABCx where ABC are always english alphabets and x/xx is a number which can vary from 0 to 99 (the numeric length is either 1 or 2). The following regex does the job for me to extract this sub string - [a-zA-Z]{3}[0-9]{1,2}

Sub string of the form <space>ABC<space>, ABC (last sub string/word in the text)and ABC (first sub string in the text). Basically here I am trying to find a 3 letter word delimited by spaces in the text.

For getting the above matches, I have the following regex's.

[ ][a-zA-Z]{3}[ ], [ ][a-zA-Z]{3} and [a-zA-Z]{3}[ ]
```

<ol start="3">
<li>Same as 2, but the three character string can also be in a box bracket like [ABC]. </li>
</ol>

<pre class="lang-rb prettyprint-override"><code>\[([a-zA-Z]{3})\]
</code>```

Since the patterns are more or less similar, is there anyway to combine all 5 of them ?

Eg: ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc

Here valid matches are ABC, rat, LAN45, eat, HGF1, abc.

答:
Thank you all for your answers. This regex did the trick for me. </p>

<p>(\b[a-zA-Z]{3}([0-9]{1,2})?\b)</p>

Body:
I have a text whose length can vary between 1 and 1000. I am looking to get the following sub strings extracted from the text.

Sub string of the form ABCxx/ABCx where ABC are always english alphabets and x/xx is a number which can vary from 0 to 99 (the numeric length is either 1 or 2). The following regex does the job for me to extract this sub string - [a-zA-Z]{3}[0-9]{1,2}

Sub string of the form <space>ABC<space>, ABC (last sub string/word in the text)and ABC (first sub string in the text). Basically here I am trying to find a 3 letter word delimited by spaces in the text.

For getting the above matches, I have the following regex's.

[ ][a-zA-Z]{3}[ ], [ ][a-zA-Z]{3} and [a-zA-Z]{3}[ ]

Same as 2, but the three character string can also be in a box bracket like [ABC].

\[([a-zA-Z]{3})\]

Since the patterns are more or less similar, is there anyway to combine all 5 of them ?

Eg: ABC catmat dogdog [rat] LAN45 eat HGF1 jkhgkj abc

Here valid matches are ABC, rat, LAN45, eat, HGF1, abc.

Body:
Thank you all for your answers. This regex did the trick for me.

(\b[a-zA-Z]{3}([0-9]{1,2})?\b)


问:
Jquery 1.5 breaks old 1.4 $.get calls
I recently upgraded to 1.5, and functions like:

```<code>function showData(id) {

 $.get("/url/getdata", {id : id}, function(data) {
 $("#dialogData").html(data);
 $("#dialogData").dialog({width: 500, modal: true, zIndex:22000});
 }, "json");
}
</code>```

no longer work with the addition of 1.5.

Looking at firebug, the correct data is returned, but the function breaks after entering the callback.
Everything simply stops.

How can I fix this? I read about the changes to Ajax call in 1.5, but I have over a thousand such calls through my project -> I cannot even begin to think about hunting them all down and changing them, let alone bug testing it all.

Edit: Oddly enough, if I put "text json" instead of "json" for dataType, it works. I don't think going through all my code and changing that is a viable option...

Edit 2: Instead of returning json_encode($string), I tried returning json_encode(array("string" => $string)), and then I did $(element).html(data.string).
This did not work either, and the JSON data I got with this call was valid on jsonlint.com

Edit 3: Tried setting headers prior to the json_encode output, didn't work. So far the only solution has been setting the datatype to text json.

答: You use the data in with the html() function, but expect JSON data. Have a look at the mime type that comes back and if you really expect the data to be parsable JSON.

Title: Jquery 1.5 breaks old 1.4 $.get calls

Body:
I recently upgraded to 1.5, and functions like:

function showData(id) {

 $.get("/url/getdata", {id : id}, function(data) {
 $("#dialogData").html(data);
 $("#dialogData").dialog({width: 500, modal: true, zIndex:22000});
 }, "json");
}

no longer work with the addition of 1.5.

Looking at firebug, the correct data is returned, but the function breaks after entering the callback.
Everything simply stops.

How can I fix this? I read about the changes to Ajax call in 1.5, but I have over a thousand such calls through my project -> I cannot even begin to think about hunting them all down and changing them, let alone bug testing it all.

Edit: Oddly enough, if I put "text json" instead of "json" for dataType, it works. I don't think going through all my code and changing that is a viable option...

Edit 2: Instead of returning json_encode($string), I tried returning json_encode(array("string" => $string)), and then I did $(element).html(data.string).
This did not work either, and the JSON data I got with this call was valid on jsonlint.com

Edit 3: Tried setting headers prior to the json_encode output, didn't work. So far the only solution has been setting the datatype to text json.


问:
Can someone give one exact example of webview implementation in android
Hi I am developing android application using WebView implementation.

I followed the official android tutorial.

I am not getting errors when building my project in eclipse, but when running the application :

the application has stopped working unexpectedly

答:
Android WebView Example

WebView used to show webpages in our app. Let's make a WebView and load any website

provide permission in AndroidManifest.XML

```<code><uses-permission android:name="android.permission.INTERNET"/>
</code>```

activity_main.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

MainActivity.Java

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity
{
private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

webview=(WebView)findViewById(R.id.webview);
//loads androidride homepage to webview
webview.loadUrl("https://www.androidride.com");
}
}
</code>```

Body:
Android WebView Example

WebView used to show webpages in our app. Let's make a WebView and load any website

provide permission in AndroidManifest.XML

<uses-permission android:name="android.permission.INTERNET"/>

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity.Java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity
{
private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

webview=(WebView)findViewById(R.id.webview);
//loads androidride homepage to webview
webview.loadUrl("https://www.androidride.com");
}
}


问:
Make Item go the bottom using Flexbox and Material UI
I am trying to add Unassigned Text to the bottom of my Container, as shown in this mockup:

Below is the code, that I have so far. I am struggling to get the border between the play button working too. I have tried the usual css: bottom:0 and position:relevant Along with Flexbox but it doesn't seem to want to go to the very bottom of the container.

```<code> const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
      "& .star-rating": {
        "& .fa-star": {
          "&:hover": {
            "&::before": {
              content: "\f005",
              color: "yellow"
            }
          }
        }
      },
    },
});

function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">
      <i class="far fa-play-circle fa-2x"></i>
    </Grid>
    <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>
      <div class="star-rating">
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
      </div>
    <div className="dropdown-menu">
  <h5>Unnassigned</h5>
</div>
  </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(Tasks);
</code>```

Any input would be great.

答:
You can try something like this, or give flex: 1 to anything in the column to make it stretch.

const styles = theme => ({
  playButton: {
    '& .dropdown-menu': {
      marginTop: "auto"
    }
  }
})```

Body:
I am trying to add Unassigned Text to the bottom of my Container, as shown in this mockup:

Below is the code, that I have so far. I am struggling to get the border between the play button working too. I have tried the usual css: bottom:0 and position:relevant Along with Flexbox but it doesn't seem to want to go to the very bottom of the container.

 const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
      "& .star-rating": {
        "& .fa-star": {
          "&:hover": {
            "&::before": {
              content: "\f005",
              color: "yellow"
            }
          }
        }
      },
    },
});

function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>

                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">

    </Grid>

      Workers Assigned

    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>

Unnassigned

  </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

export default withStyles(styles)(Tasks);

Any input would be great.


问:
The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly
Could someone please clarify something for me. In my ASP.NET MVC 2 app, I've got a BaseViewModel class which includes the following method:

```<code>public virtual IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
                        (Expression<Func<TModel, TProperty>> propertyExpression)
{
    return new Dictionary<string, object>();
}
</code>```

The idea being that each child viewmodel can override this method and provide a suitable set of html attributes, based on some logic, to be rendered in the view:

```<code><%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                                                 (model => model.MyProperty)) %>
</code>```

However when used as in the line above, I get a compilation error when I hit the view:

The type arguments for method '...BaseViewModel.GetHtmlAttributes<TModel,TProperty> Expression<System.Func<TModel,TProperty>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I have to do the following:

```<code><%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                             <ChildModel, string>(model => model.MyProperty)) %>
</code>```

I'm just looking for some clarity as to how it tries to infer the type, it has no problem doing so in the HtmlHelper/TextBoxFor extension method?

Is it because HtmlHelper in the view will automatically be for the same type as is specified in the ViewUserControl at the top of the page, whereas my code can be for any type inheriting from BaseViewModel? Is is possible to write this in such a way that it can infer my model/property types?

答:
C# compiler have only lambda

```<code>arg => arg.MyProperty
</code>```

for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.

Body:
Could someone please clarify something for me. In my ASP.NET MVC 2 app, I've got a BaseViewModel class which includes the following method:

public virtual IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
                        (Expression<Func<TModel, TProperty>> propertyExpression)
{
    return new Dictionary<string, object>();
}

The idea being that each child viewmodel can override this method and provide a suitable set of html attributes, based on some logic, to be rendered in the view:

<%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                                                 (model => model.MyProperty)) %>

However when used as in the line above, I get a compilation error when I hit the view:

The type arguments for method '...BaseViewModel.GetHtmlAttributes<TModel,TProperty> Expression<System.Func<TModel,TProperty>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I have to do the following:

<%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                             <ChildModel, string>(model => model.MyProperty)) %>

I'm just looking for some clarity as to how it tries to infer the type, it has no problem doing so in the HtmlHelper/TextBoxFor extension method?

Is it because HtmlHelper in the view will automatically be for the same type as is specified in the ViewUserControl at the top of the page, whereas my code can be for any type inheriting from BaseViewModel? Is is possible to write this in such a way that it can infer my model/property types?

Body:
C# compiler have only lambda

arg => arg.MyProperty

for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.


问:
Dash App: callback executes several times when returning html.Div
I have these input and button components in my Dash App:

```<code>html.Div(
     dcc.Input(
          id='id_selector',
          placeholder='',
          type='text',
          value=''
     )
),

html.Button(
      type = 'submit',
      id = 'submit-button',
      className = 'btn btn-info',
      children = [
            html.Span('Go!'),
      ]
)
</code>```

and these components:

```<code>html.Div(id='output'),
html.Div(
     dcc.Graph(id='heatmap_id')
)
</code>```

Then I add a callback like this:

```<code>app.callback(
    Output(component_id='output', component_property='children'),
    [Input('submit-button','n_clicks')],
    [State('id_selector', 'value')])

def update_output(n_clicks, input_ID):
    print(input_ID)

    return html.Div(
              "you have selected"+input_ID
           ,id='output')
</code>```

However, when I do this, the callback executes several times and not only if I click on the button.

If I made this change:

```<code>app.callback(
        Output('heatmap_id', 'figure'),
        [Input('submit-button','n_clicks')],
        [State('id_selector', 'value')])

def update_output(n_clicks, input_ID):
    print(input_ID)

    {HERE I CREATE A THE FIG}

    fig = go.Figure(data=data, layout=layout)

    return fig
</code>```

In this case everything works fine and the Callbacks is only executed if I click on the button.

Why is this difference?

The reason because I want to use the first option (return a html.Div instead of a figure) is because when I enter my app I have an empty plot in the second case and I would like to have an empty space at first.

答:
I have solved it,
The problem is the line

```<code>return html.Div(
          "you have selected"+input_ID
       ,id='output')
</code>```

It should be:

```<code>return html.Div(
          "you have selected"+input_ID
       )
</code>```

Body:
I have these input and button components in my Dash App:

html.Div(
     dcc.Input(
          id='id_selector',
          placeholder='',
          type='text',
          value=''
     )
),

html.Button(
      type = 'submit',
      id = 'submit-button',
      className = 'btn btn-info',
      children = [
            html.Span('Go!'),
      ]
)

and these components:

html.Div(id='output'),
html.Div(
     dcc.Graph(id='heatmap_id')
)

Then I add a callback like this:

app.callback(
    Output(component_id='output', component_property='children'),
    [Input('submit-button','n_clicks')],
    [State('id_selector', 'value')])

def update_output(n_clicks, input_ID):
    print(input_ID)

    return html.Div(
              "you have selected"+input_ID
           ,id='output')

However, when I do this, the callback executes several times and not only if I click on the button.

If I made this change:

app.callback(
        Output('heatmap_id', 'figure'),
        [Input('submit-button','n_clicks')],
        [State('id_selector', 'value')])

def update_output(n_clicks, input_ID):
    print(input_ID)

    {HERE I CREATE A THE FIG}

    fig = go.Figure(data=data, layout=layout)

    return fig

In this case everything works fine and the Callbacks is only executed if I click on the button.

Why is this difference?

The reason because I want to use the first option (return a html.Div instead of a figure) is because when I enter my app I have an empty plot in the second case and I would like to have an empty space at first.

Body:
I have solved it,
The problem is the line

return html.Div(
          "you have selected"+input_ID
       ,id='output')

It should be:

return html.Div(
          "you have selected"+input_ID
       )


问:
How can a lambda capture itself for an asynchronous call?
I have to make an asynchronous call inside a lambda, and once the asynchronous call is terminated I have to call the lambda itself.

I try to explain my problem with code:

typedef function<void(int id)> Callback;
```

<pre class="lang-cpp prettyprint-override"><code>AsyncWork1(Callback call, int id, string)
{
    //...
    call(id);
}

AsyncWork2(Callback call, int id, double, string)
{
    //...
    call(id);
}
</code>```

void AsyncWorks(Callback final_callback, int id)
{
    Callback lambda = [&lambda, final_callback, id](int next_work) -> void
        {
            if(next_work == 1)
            {
                //...
                AsyncWork1(lambda, 2, "bla bla");
            }
            else if(next_work == 2)
            {
                //...
                //the lambda variable no longer exists
                AsyncWork2(lambda, 3, 0.0, "bla bla");
            }
            else if(next_work == 3)
            {
                //...
                final_callback(id);
            }
        };

    lambda(1);
}
```

<pre class="lang-cpp prettyprint-override"><code>int main()
{
    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    return 0;
}
</code>```

The problem is that when the code exits from "AsyncWorks(...)" function, the local variable "lambda" no longer exists.

I've read several threads that talk about lambda recursive, but I haven't found any solution.

How can I solve this problem?

答:
Lambda can capture itself implicitly. To demo how? see below code it calculate factorial value.

```<code>#include <iostream>

int (* factorial)( const int) = []( const int number)
{
    if( number > 1)
    {
        return number* factorial( number - 1);
    }
    else
    {
        return 1;
    }
};

int main(int , char *[])
{
    int fact = factorial( 7);
    std::cout<< "7! = "<< fact<< std::endl;
}
</code>```

```<code>Output 7! = 5040
</code>```

If any variable is used inside lambda then lambda captures it implicitly, if it is not captured explicitly. Due to this inside lambda, name factorial referring itself, is available.

But if in place of
int (* factorial)( const int) = []( const int number){//implementation };

 if auto is used like as follows,

auto factorial = []( const int number){ //implementation };

then g++ compiler gives following error,
error: use of ‘factorial’ before deduction of ‘auto’
         return number* factorial( number - 1);

It is because type of factorial is not deduced, auto does not deduce for same control block. Name factorial will be available only below the declaration in case of auto.

Body:
I have to make an asynchronous call inside a lambda, and once the asynchronous call is terminated I have to call the lambda itself.

I try to explain my problem with code:

typedef function<void(int id)> Callback;

AsyncWork1(Callback call, int id, string)
{
    //...
    call(id);
}

AsyncWork2(Callback call, int id, double, string)
{
    //...
    call(id);
}

void AsyncWorks(Callback final_callback, int id)
{
    Callback lambda = [&lambda, final_callback, id](int next_work) -> void
        {
            if(next_work == 1)
            {
                //...
                AsyncWork1(lambda, 2, "bla bla");
            }
            else if(next_work == 2)
            {
                //...
                //the lambda variable no longer exists
                AsyncWork2(lambda, 3, 0.0, "bla bla");
            }
            else if(next_work == 3)
            {
                //...
                final_callback(id);
            }
        };

    lambda(1);
}

int main()
{
    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    return 0;
}

The problem is that when the code exits from "AsyncWorks(...)" function, the local variable "lambda" no longer exists.

I've read several threads that talk about lambda recursive, but I haven't found any solution.

How can I solve this problem?

Body:
Lambda can capture itself implicitly. To demo how? see below code it calculate factorial value.

#include <iostream>

int (* factorial)( const int) = []( const int number)
{
    if( number > 1)
    {
        return number* factorial( number - 1);
    }
    else
    {
        return 1;
    }
};

int main(int , char *[])
{
    int fact = factorial( 7);
    std::cout<< "7! = "<< fact<< std::endl;
}

Output 7! = 5040

If any variable is used inside lambda then lambda captures it implicitly, if it is not captured explicitly. Due to this inside lambda, name factorial referring itself, is available.

But if in place of
int (* factorial)( const int) = []( const int number){//implementation };

 if auto is used like as follows,

auto factorial = []( const int number){ //implementation };

then g++ compiler gives following error,
error: use of ‘factorial’ before deduction of ‘auto’
         return number* factorial( number - 1);

It is because type of factorial is not deduced, auto does not deduce for same control block. Name factorial will be available only below the declaration in case of auto.


问:
Token authentication for CURL in EXCEL VBA
A client requested that I put together a tool to take a company domain name and somehow come up with the account name. I found an API that I can work with, but I'm not as familiar with doing this in VBA.

Here is the CURL procedure that the site documentation gives to push through a Domain Name, and receive the company name as a response:

```<code>curl 'https://company.clearbit.com/v2/companies/find?domain=segment.com' \
        -u sk_b3b05a8924c4f3df86248b4e38421cfa:
</code>```

After several attempts of receiving the "Please authenticate your request", I've finally gotten to the point where I am receiving an error from the API, I think indicating that I am now correctly calling the API in some way.

Here is my current code. Any idea why I may be receiving this error?

```<code>{"error":{"type":"api_error","message":"Sorry, something went wrong. We have been notified."}}
</code>```

```<code>Public Function CallRestAPI2(strUrl1 As String)
    TargetURL = "https://company.clearbit.com/v2/companies/find?domain=toplinegroup.com"
    Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    'HTTPReq.Option(4) = 13056 '
    HTTPReq.Open "GET", TargetURL, False
    HTTPReq.SetRequestHeader "Content-Type", "application/json"
    HTTPReq.SetRequestHeader "Accept", "application/json"
    HTTPReq.Send "-u sk_b3b05a8924c4f3df86248b4e38421cfa"
    Debug.Print HTTPReq.responseText
End Function
</code>```

Any idea what I am doing wrong?

答:
Figured this out after more reading in the documentation and it was due to not passing the Authentication header the correct way. Here is my code:</p>

```<code>Public Function CallRestAPI3(strUrl1 As String)
    Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String
    myurl = "https://company.clearbit.com/v2/companies/find?domain=toplinegroup.com"
    xmlhttp.Open "GET", myurl, False
    xmlhttp.setRequestHeader "Authorization", "Bearer " + "sk_b3b05a8924c4f3df86248b4e38421cfa"
    xmlhttp.Send
    Debug.Print (xmlhttp.responseText)
End Function
</code>```

Body:
A client requested that I put together a tool to take a company domain name and somehow come up with the account name. I found an API that I can work with, but I'm not as familiar with doing this in VBA.

Here is the CURL procedure that the site documentation gives to push through a Domain Name, and receive the company name as a response:

curl 'https://company.clearbit.com/v2/companies/find?domain=segment.com' \
        -u sk_b3b05a8924c4f3df86248b4e38421cfa:

After several attempts of receiving the "Please authenticate your request", I've finally gotten to the point where I am receiving an error from the API, I think indicating that I am now correctly calling the API in some way.

Here is my current code. Any idea why I may be receiving this error?

{"error":{"type":"api_error","message":"Sorry, something went wrong. We have been notified."}}

Public Function CallRestAPI2(strUrl1 As String)
    TargetURL = "https://company.clearbit.com/v2/companies/find?domain=toplinegroup.com"
    Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    'HTTPReq.Option(4) = 13056 '
    HTTPReq.Open "GET", TargetURL, False
    HTTPReq.SetRequestHeader "Content-Type", "application/json"
    HTTPReq.SetRequestHeader "Accept", "application/json"
    HTTPReq.Send "-u sk_b3b05a8924c4f3df86248b4e38421cfa"
    Debug.Print HTTPReq.responseText
End Function

Any idea what I am doing wrong?

Body:
Figured this out after more reading in the documentation and it was due to not passing the Authentication header the correct way. Here is my code:

Public Function CallRestAPI3(strUrl1 As String)
    Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String
    myurl = "https://company.clearbit.com/v2/companies/find?domain=toplinegroup.com"
    xmlhttp.Open "GET", myurl, False
    xmlhttp.setRequestHeader "Authorization", "Bearer " + "sk_b3b05a8924c4f3df86248b4e38421cfa"
    xmlhttp.Send
    Debug.Print (xmlhttp.responseText)
End Function


问:
Why is verbose redirection creating a line between data in exported CSV file?
I have the following code that imports two csv files and merges them together. As part of the merge I remove the two files used and export one main CSV file.

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force
</code>```

The CSV generated looks like this with the 4>&1 verbose redirection:

Notice the extra empty in between row between server1 and server2.

The CSV I'm expecting should be like this (no in between extra row):

```
server  Database    role    members
server1 DB1 role1   memberx
server1 DB1 role2   membery
server2 DB1 role1   memberx
server2 DB1 role2   membery
```

Of course without this part

```<code>4>&1|tee .\log.txt -append
</code>```

the exported CSV looks good. However, I want the verbose messages printed to the console and file (with 4>&1 | tee .\log.txt -Append it only seems to print to file unfortunately).

VERBOSE: Performing remove...

and the only way it works is with 4>&1.

I tried redirecting to a variable. I tried many things but to no avail.

UPDATE: In regards to the second solution HAL offered below.

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}
</code>```

the output i'd normally see on the console with just -verbose looked like this:

```<code>VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server1.domain.com.c
sv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server2.domain.com.c
sv".
</code>```

however, HAL's code results in this verbose console output:

```<code>VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server1.domain.com.csv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server2.domain.com.csv".
</code>```

of course its insignificant but its worth noting the strange output style anyways

as far as the csv file generated, it STILL results in empty line, but even more:

答:
Well, you merge verbose records into the standard stream, none of which have server, Database, role or members properties, so each verbose message will result in an empty row after the records of each csv file.

Move the merge redirector to the outer pipeline instead - at that point Export-Csv will have written everything in the standard output stream to file, and you'll have only the verbose messages left:

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_"
    Remove-Item "$csvLocation\$_" -Verbose
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force 4>&1 |tee .\log.txt -Append
</code>```

Body:
I have the following code that imports two csv files and merges them together. As part of the merge I remove the two files used and export one main CSV file.

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force

The CSV generated looks like this with the 4>&1 verbose redirection:

Notice the extra empty in between row between server1 and server2.

The CSV I'm expecting should be like this (no in between extra row):

server  Database    role    members
server1 DB1 role1   memberx
server1 DB1 role2   membery
server2 DB1 role1   memberx
server2 DB1 role2   membery

Of course without this part

4>&1|tee .\log.txt -append

the exported CSV looks good. However, I want the verbose messages printed to the console and file (with 4>&1 | tee .\log.txt -Append it only seems to print to file unfortunately).

VERBOSE: Performing remove...

and the only way it works is with 4>&1.

I tried redirecting to a variable. I tried many things but to no avail.

UPDATE: In regards to the second solution HAL offered below.

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}

the output i'd normally see on the console with just -verbose looked like this:

VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server1.domain.com.c
sv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server2.domain.com.c
sv".

however, HAL's code results in this verbose console output:

VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server1.domain.com.csv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server2.domain.com.csv".

of course its insignificant but its worth noting the strange output style anyways

as far as the csv file generated, it STILL results in empty line, but even more:

Body:
Well, you merge verbose records into the standard stream, none of which have server, Database, role or members properties, so each verbose message will result in an empty row after the records of each csv file.

Move the merge redirector to the outer pipeline instead - at that point Export-Csv will have written everything in the standard output stream to file, and you'll have only the verbose messages left:

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_"
    Remove-Item "$csvLocation\$_" -Verbose
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force 4>&1 |tee .\log.txt -Append


问:
JCR user login failure
I'm using JCR and Jackrabbit Oak implementation. I want to get session with admin user with this code:

```<code>Credentials credentials = new SimpleCredentials("admin", "admin".toCharArray());
return repository.login(credentials);
</code>```

but in the return session the parameters have null, for example accessControlManager and userManager.

My JCR configuration:

```<code>jcr.with(securityProvider)
                .with(new LuceneIndexEditorProvider())
                .with((QueryIndexProvider) indexProvider)
                .with((Observer) indexProvider)
                .withAsyncIndexing("async", 5);
        repository = jcr.createRepository();
</code>```

Can I login with admin user? Otherwise can I create a new user?

答:
Please use below code:

Repository jcrRepository = (Repository) initCtx.lookup(jcrJndiResource);
return jcrRepository.login(new SimpleCredentials(userName,password.toCharArray()), "default");

Title: JCR user login failure

Body:
I'm using JCR and Jackrabbit Oak implementation. I want to get session with admin user with this code:

Credentials credentials = new SimpleCredentials("admin", "admin".toCharArray());
return repository.login(credentials);

but in the return session the parameters have null, for example accessControlManager and userManager.

My JCR configuration:

jcr.with(securityProvider)
                .with(new LuceneIndexEditorProvider())
                .with((QueryIndexProvider) indexProvider)
                .with((Observer) indexProvider)
                .withAsyncIndexing("async", 5);
        repository = jcr.createRepository();

Can I login with admin user? Otherwise can I create a new user?


问:
XCUIElement tap() not working
I have a very simple XCTestCase implementation that tests a tap on a button and expects an Alert controller to show up. The problem is that the tap() method doesn't work. Placing a breakpoint in the associated button's IBAction I realise the logic doesn't even get called.

```<code>class uitestsampleUITests: XCTestCase {

    var app: XCUIApplication!

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app = XCUIApplication()
        app.launch()
    }

    func testButton() {
        let button = app.buttons["Button"]
        button.tap()

        expectationForPredicate(NSPredicate(format: "exists == 1"), evaluatedWithObject: button, handler: nil)
        waitForExpectationsWithTimeout(5.0, handler: nil)
    }
}
</code>```

Also, duplicating the button.tap() instruction makes the test pass, like this:

```<code>    func testButton() {
        let button = app.buttons["Button"]
        button.tap()
        button.tap()

        expectationForPredicate(NSPredicate(format: "exists == 1"), evaluatedWithObject: button, handler: nil)
        waitForExpectationsWithTimeout(5.0, handler: nil)
    }
</code>```

I am facing this issue in Xcode 7.3.1 Am I missing something? Is it a bug?

答:
You can wait while the element load, I created this extension:

```<code>import XCTest

extension XCUIElement {
    func tap(wait: Int, test: XCTestCase) {
        if !isHittable {
            test.expectation(for: NSPredicate(format: "hittable == true"), evaluatedWith: self, handler: nil)
            test.waitForExpectations(timeout: TimeInterval(wait), handler: nil)
        }
        tap()
    }
}
</code>```

Use like this:

```<code>app.buttons["start"].tap(wait: 20, test: self)
</code>```

Title: XCUIElement tap() not working

Body:
I have a very simple XCTestCase implementation that tests a tap on a button and expects an Alert controller to show up. The problem is that the tap() method doesn't work. Placing a breakpoint in the associated button's IBAction I realise the logic doesn't even get called.

class uitestsampleUITests: XCTestCase {

    var app: XCUIApplication!

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app = XCUIApplication()
        app.launch()
    }

    func testButton() {
        let button = app.buttons["Button"]
        button.tap()

        expectationForPredicate(NSPredicate(format: "exists == 1"), evaluatedWithObject: button, handler: nil)
        waitForExpectationsWithTimeout(5.0, handler: nil)
    }
}

Also, duplicating the button.tap() instruction makes the test pass, like this:

    func testButton() {
        let button = app.buttons["Button"]
        button.tap()
        button.tap()

        expectationForPredicate(NSPredicate(format: "exists == 1"), evaluatedWithObject: button, handler: nil)
        waitForExpectationsWithTimeout(5.0, handler: nil)
    }

I am facing this issue in Xcode 7.3.1 Am I missing something? Is it a bug?

Body:
You can wait while the element load, I created this extension:

import XCTest

extension XCUIElement {
    func tap(wait: Int, test: XCTestCase) {
        if !isHittable {
            test.expectation(for: NSPredicate(format: "hittable == true"), evaluatedWith: self, handler: nil)
            test.waitForExpectations(timeout: TimeInterval(wait), handler: nil)
        }
        tap()
    }
}

Use like this:

app.buttons["start"].tap(wait: 20, test: self)


问:
Export Data into excel using SSIS 2008 with 5000 length column
I need to create a SSIS package in 2008 which will export a query result into excel sheet. Comment column has length 5000 and whenever I try to export the data I am getting following error message:

"Error 0xc0204016: SSIS.Pipeline: The output column Comments (255) has a length that is not valid. the length must be between 0 to 4000."

I need to apply some formating on the excel sheet like word wrap is it possible thourgh SSIS package. Any help would be highly appricaited.
Thanks, Yogi

答: Put a data conversion component in between your source and destination. You should be able to stipulate the data size.</p>


问:
File not there when container is run but is there when Docker image is built
If I use:

```<code>FROM jenkins/jenkins:lts
RUN ls -l /var/jenkins_home/; touch /var/jenkins_home/isthisworking; echo "================================"; ls -l /var/jenkins_home;
</code>```

I actually see isthisworking in my final ls -l command during the building of the image. It is upon running the container that this file gets removed. Why?

答:
I think I know what is going on. Here is the Dockerfile I was using to figure out what was going on (copied from above):

```<code>FROM jenkins/jenkins:lts
RUN ls -l /var/jenkins_home/; touch /var/jenkins_home/isthisworking; echo "================================"; ls -l /var/jenkins_home;
</code>```

As mentioned, with this file, at build time, I would see the file isthisworking but when I run the container, that file is no longer there.

So I went to jenkins/jenkins:lts github page and looked at their Dockerfile. I saw this on line 26:

```<code># Jenkins home directory is a volume, so configuration and build history
# can be persisted and survive image upgrades
VOLUME $JENKINS_HOME
</code>```

Here, $JENKINS_HOME is /var/jenkins_home/. So as a Docker noob, I asked myself what is VOLUME (I know what it is from the command line but not inside a Dockerfile)? With googling, I found this and this, which basically say:

The docker run command initializes the newly created volume with any
  data that exists at the specified location within the base image.

Since that location is a docker VOLUME at that point in the Dockerfile, no matter what and how files are copied into it, at container runtime that location will be reinitialized to how the base image has it "defined."

To have the file stay when the container is run, make the modification/addition to the directory prior to making it a VOLUME.

Body:
If I use:

FROM jenkins/jenkins:lts
RUN ls -l /var/jenkins_home/; touch /var/jenkins_home/isthisworking; echo "================================"; ls -l /var/jenkins_home;

I actually see isthisworking in my final ls -l command during the building of the image. It is upon running the container that this file gets removed. Why?

Body:
I think I know what is going on. Here is the Dockerfile I was using to figure out what was going on (copied from above):

FROM jenkins/jenkins:lts
RUN ls -l /var/jenkins_home/; touch /var/jenkins_home/isthisworking; echo "================================"; ls -l /var/jenkins_home;

As mentioned, with this file, at build time, I would see the file isthisworking but when I run the container, that file is no longer there.

So I went to jenkins/jenkins:lts github page and looked at their Dockerfile. I saw this on line 26:

# Jenkins home directory is a volume, so configuration and build history
# can be persisted and survive image upgrades
VOLUME $JENKINS_HOME

Here, $JENKINS_HOME is /var/jenkins_home/. So as a Docker noob, I asked myself what is VOLUME (I know what it is from the command line but not inside a Dockerfile)? With googling, I found this and this, which basically say:

The docker run command initializes the newly created volume with any
  data that exists at the specified location within the base image.

Since that location is a docker VOLUME at that point in the Dockerfile, no matter what and how files are copied into it, at container runtime that location will be reinitialized to how the base image has it "defined."

To have the file stay when the container is run, make the modification/addition to the directory prior to making it a VOLUME.


问:
CMD batch file to delete a file if not found in list from text txt file
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

```<code>C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png
</code>```

and the in the same folder have this files:

```<code>Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt
</code>```

So i need to delete the next files because not exist in list.txt

```<code>Carlos.jpg
Sapo.png
</code>```

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

```<code>@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"
</code>```

any one can help me with this.

Thanks

答:
Give this a shot.  It works for my testing.

I have placed echo statements instead of actually deleting anything.

```<code>@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=%folder%\list.txt"

:: Check that both the target folder and filter file exist before starting up.
if not exist "%folder%" echo %~nx0: The target folder doesn't exist.  Nothing to do.&& goto :EOF
if not exist "%excludeFile%" echo %~nx0: The list file doesn't exist at the location specified!&& goto :EOF

for /f "delims=" %%F in ('dir /b /a-d "%folder%"') do call :process_file "%%F" "%~0" "%excludeFile%"
goto :EOF

:: --------------------------------------------
:process_file
:: --------------------------------------------
set input_file=%~1
set this_batch=%~2
set list_file=%~nx3

:: Skip list file and this batch file too
if "%this_batch%"=="%input_file%" echo Skip this batch file&& goto :EOF
if "%list_file%"=="%input_file%" echo Skip list file&& goto :EOF

:: Grep for the include file in the list
findstr /C:"%input_file%" "%excludeFile%" 2>&1 1>NUL

:: Bail out if the input line was in the list file
if not errorlevel 1 echo Skip "%input_file%", it is in %list_file%&& goto :EOF

:: Delete anything left
echo delete file %input_file%&& goto :EOF
goto :EOF
</code>```

Body:
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png

and the in the same folder have this files:

Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt

So i need to delete the next files because not exist in list.txt

Carlos.jpg
Sapo.png

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"

any one can help me with this.

Thanks

Body:
Give this a shot.  It works for my testing.

I have placed echo statements instead of actually deleting anything.

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=%folder%\list.txt"

:: Check that both the target folder and filter file exist before starting up.
if not exist "%folder%" echo %~nx0: The target folder doesn't exist.  Nothing to do.&& goto :EOF
if not exist "%excludeFile%" echo %~nx0: The list file doesn't exist at the location specified!&& goto :EOF

for /f "delims=" %%F in ('dir /b /a-d "%folder%"') do call :process_file "%%F" "%~0" "%excludeFile%"
goto :EOF

:: --------------------------------------------
:process_file
:: --------------------------------------------
set input_file=%~1
set this_batch=%~2
set list_file=%~nx3

:: Skip list file and this batch file too
if "%this_batch%"=="%input_file%" echo Skip this batch file&& goto :EOF
if "%list_file%"=="%input_file%" echo Skip list file&& goto :EOF

:: Grep for the include file in the list
findstr /C:"%input_file%" "%excludeFile%" 2>&1 1>NUL

:: Bail out if the input line was in the list file
if not errorlevel 1 echo Skip "%input_file%", it is in %list_file%&& goto :EOF

:: Delete anything left
echo delete file %input_file%&& goto :EOF
goto :EOF


问:
How to use drawables in int array from resources
I have a piece of code with int array hard coded, this works correctly.
But now I want to move it to an external ressource file and take images from there.

I already used the same for string array, to move hard code  and  use ressources, it works (see commented lines), but for int I don't have any errors but also don't have any images in app (see commented lines).
Here is my int array format:

```<code><integer-array name="mImageIds1">
<item>@drawable/ic_android_black_24dp</item>
<item>@drawable/ic_android_black_24dp</item>
<item>@drawable/ic_android_black_24dp</item>
</code>```

What's wrong?

```<code> public class MainActivity extends ListActivity {

    private String[] mText = {"First", "Second", "Third", "Fourth", "Fifth", "Sixth",
            "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"};

    int[] mImageIds = {R.drawable.ic_android_black_24dp, R.drawable.ic_android_blue_24dp,
            R.drawable.ic_android_black_24dp, R.drawable.ic_android_blue_24dp...
            };

    private myAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new myAdapter(this);
        setListAdapter(mAdapter);
    }

    private class myAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;

        myAdapter(Context context) {
            mLayoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mText.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = mLayoutInflater.inflate(R.layout.activity_main, null);

            int[] mArrayImageIds=getResources().getIntArray(R.array.mImageIds1);

            ImageView image = (ImageView) convertView.findViewById(R.id.imageViewIcon);
            if (1==1)
                image.setImageResource( mArrayImageIds[position]);
               // image.setImageResource( mImageIds[position]);

            TextView signTextView = (TextView) convertView.findViewById(R.id.textViewSign);
            signTextView.setText(mText[position]);

            String[] zooString=getResources().getStringArray(R.array.text1);

            TextView dateTextView = (TextView) convertView.findViewById(R.id.textViewDate);
            //dateTextView.setText(mSignatures[position]);
            dateTextView.setText(zooString[position]);

            return convertView;
        }

        String getString(int position) {
            return mText[position] + " (" + mSignatures[position] + ")";
        }
    }
}
</code>```

答:
I think TypedArray is what you are looking for. I have samples using it. If you are interested, take a look at codes below:

```<code>TypedArray tArray = getResources().obtainTypedArray(R.array.frag_home_ids);
int count = tArray.length();
int[] mArrayImageIds = new int[count];
for (int i = 0; i < mArrayImageIds .length; i++) {
    mArrayImageIds[i] = tArray.getResourceId(i, 0);
}

//Recycles the TypedArray, to be re-used by a later caller.
//After calling this function you must not ever touch the typed array again.
tArray.recycle();
</code>```

Body:
I have a piece of code with int array hard coded, this works correctly.
But now I want to move it to an external ressource file and take images from there.

I already used the same for string array, to move hard code  and  use ressources, it works (see commented lines), but for int I don't have any errors but also don't have any images in app (see commented lines).
Here is my int array format:

<integer-array name="mImageIds1">
<item>@drawable/ic_android_black_24dp</item>
<item>@drawable/ic_android_black_24dp</item>
<item>@drawable/ic_android_black_24dp</item>

What's wrong?

 public class MainActivity extends ListActivity {

    private String[] mText = {"First", "Second", "Third", "Fourth", "Fifth", "Sixth",
            "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"};

    int[] mImageIds = {R.drawable.ic_android_black_24dp, R.drawable.ic_android_blue_24dp,
            R.drawable.ic_android_black_24dp, R.drawable.ic_android_blue_24dp...
            };

    private myAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new myAdapter(this);
        setListAdapter(mAdapter);
    }

    private class myAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;

        myAdapter(Context context) {
            mLayoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mText.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = mLayoutInflater.inflate(R.layout.activity_main, null);

            int[] mArrayImageIds=getResources().getIntArray(R.array.mImageIds1);

            ImageView image = (ImageView) convertView.findViewById(R.id.imageViewIcon);
            if (1==1)
                image.setImageResource( mArrayImageIds[position]);
               // image.setImageResource( mImageIds[position]);

            TextView signTextView = (TextView) convertView.findViewById(R.id.textViewSign);
            signTextView.setText(mText[position]);

            String[] zooString=getResources().getStringArray(R.array.text1);

            TextView dateTextView = (TextView) convertView.findViewById(R.id.textViewDate);
            //dateTextView.setText(mSignatures[position]);
            dateTextView.setText(zooString[position]);

            return convertView;
        }

        String getString(int position) {
            return mText[position] + " (" + mSignatures[position] + ")";
        }
    }
}

Body:
I think TypedArray is what you are looking for. I have samples using it. If you are interested, take a look at codes below:

TypedArray tArray = getResources().obtainTypedArray(R.array.frag_home_ids);
int count = tArray.length();
int[] mArrayImageIds = new int[count];
for (int i = 0; i < mArrayImageIds .length; i++) {
    mArrayImageIds[i] = tArray.getResourceId(i, 0);
}

//Recycles the TypedArray, to be re-used by a later caller.
//After calling this function you must not ever touch the typed array again.
tArray.recycle();


问:
Dynamically putting functions into an object without losing type information
In my functions.ts, I define 2 functions, both take an api object, and returns a function with different arg types, arg numbers and return types.

```<code>export function f1 (api: Api) {
  return function (a: number): number[] {/* not important */}
};
export function f2 (api: Api) {
  return function (a: string, b: string): boolean {/* not important */}
};
</code>```

Now given an api: Api global object, I want to define an object, that has fields f1 and f2, and the value associated to each field is the inner function inside the above 2 functions.

Namely, manually, I would do:

```<code>const api: Api = ...;
const myObject = {
  f1: f1(api),
  f2: f2(api),
}
</code>```

And this works super well.

But the next step: I wish to do it dynamically, i.e. without manually typing f1 and f2.

Here's my start:

```<code>import * as functions from './functions';

const api: Api = ...;
const myObject = Object.keys(functions).reduce((accumulator, functionName) => {
  accumulator[functionName] = functions[functionName](api);
}, {} as ???);
</code>```

The code works, but the typings don't. I'm not sure what to put instead of ???. {[index: keyof typeof functions]: (...args: any[]) => any} would work, but I lose a lot of information on types.

I tried looking at TS's Parameters<T>, ReturnType<T> and I'm sure there's something to be done with infer, but can't seem to get hold of it.

答:
The code works, but the typings don't. I'm not sure what to put instead of ???.

Here is an approach that works. It creates a new type that maps each function name to its return type.

```<code>type ReturnTypes<T> = {
    [K in keyof T]: T[K] extends (...args: any) => any
    ? ReturnType<T[K]>
    : never;
};

const myObject = Object
    .keys(functions)
    .reduce(
        (accumulator, functionName) => {
            accumulator[functionName] = functions[functionName](api);
            return accumulator;
        },
        {} as ReturnTypes<typeof functions>
    );

const result1: number[] = myObject.f1(10);
const result2: boolean = myObject.f2('foo', 'bar');
</code>```

Here it is in the TypeScript playground.

Body:
In my functions.ts, I define 2 functions, both take an api object, and returns a function with different arg types, arg numbers and return types.

export function f1 (api: Api) {
  return function (a: number): number[] {/* not important */}
};
export function f2 (api: Api) {
  return function (a: string, b: string): boolean {/* not important */}
};

Now given an api: Api global object, I want to define an object, that has fields f1 and f2, and the value associated to each field is the inner function inside the above 2 functions.

Namely, manually, I would do:

const api: Api = ...;
const myObject = {
  f1: f1(api),
  f2: f2(api),
}

And this works super well.

But the next step: I wish to do it dynamically, i.e. without manually typing f1 and f2.

Here's my start:

import * as functions from './functions';

const api: Api = ...;
const myObject = Object.keys(functions).reduce((accumulator, functionName) => {
  accumulator[functionName] = functions[functionName](api);
}, {} as ???);

The code works, but the typings don't. I'm not sure what to put instead of ???. {[index: keyof typeof functions]: (...args: any[]) => any} would work, but I lose a lot of information on types.

I tried looking at TS's Parameters<T>, ReturnType<T> and I'm sure there's something to be done with infer, but can't seem to get hold of it.

Body:
The code works, but the typings don't. I'm not sure what to put instead of ???.

Here is an approach that works. It creates a new type that maps each function name to its return type.

type ReturnTypes<T> = {
    [K in keyof T]: T[K] extends (...args: any) => any
    ? ReturnType<T[K]>
    : never;
};

const myObject = Object
    .keys(functions)
    .reduce(
        (accumulator, functionName) => {
            accumulator[functionName] = functions[functionName](api);
            return accumulator;
        },
        {} as ReturnTypes<typeof functions>
    );

const result1: number[] = myObject.f1(10);
const result2: boolean = myObject.f2('foo', 'bar');

Here it is in the <a href="https://www.typescriptlang.org/play/#src=type%20Api%20%3D%20%7B%0D%0A%20%20%20%20prop1%3A%20string%3B%0D%0A%20%20%20%20prop2%3A%20string%3B%0D%0A%7D%3B%0D%0A%0D%0Afunction%20f1(api%3A%20Api)%20%7B%0D%0A%20%20%20%20return%20function%20(a%3A%20number)%3A%20number%5B%5D%20%7B%20return%20%5B%5D%3B%20%7D%0D%0A%7D%3B%0D%0A%0D%0Afunction%20f2(api%3A%20Api)%20%7B%0D%0A%20%20%20%20return%20function%20(a%3A%20string%2C%20b%3A%20string)%3A%20boolean%20%7B%20return%20true%3B%20%7D%0D%0A%7D%3B%0D%0A%0D%0A%2F%2F%20mimic%20the%20import%20of%20a%20module%20with%20two%20named%20exports%0D%0Aconst%20functions%20%3D%20%7B%20f1%2C%20f2%20%7D%3B%0D%0A%0D%0Atype%20ReturnTypes%3CT%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20T%5D%3A%20T%5BK%5D%20extends%20(...args%3A%20any)%20%3D%3E%20any%0D%0A%20%20%20%20%3F%20ReturnType%3CT%5BK%5D%3E%0D%0A%20%20%20%20%3A%20never%3B%0D%0A%7D%3B%0D%0A%0D%0Aconst%20api%20%3D%20%7B%0D%0A%20%20%20%20prop1%3A%20''%2C%0D%0A%20%20%20%20prop2%3A%20''%2C%0D%0A%7D%3B%0D%0A%0D%0Aconst%20myObject%20%3D%20Object%0D%0A%20%20%20%20.keys(functions)%0D%0A%20%20%20%20.reduce(%0D%0A%20%20%20%20%20%20%20%20(accumulator%2C%20functionName)%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20accumulator%5BfunctionName%5D%20%3D%20functions%5BfunctionName%5D(api)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20accumulator%3B%0D%0A%20%20%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%20%20%7B%7D%20as%20ReturnTypes%3Ctypeof%20functions%3E%0D%0A%20%20%20%20)%3B%0D%0A%0D%0Aconst%20result1%3A%20number%5B%5D%20%3D%20myObject.f1(10)%3B%0D%0Aconst%20result2%3A%20boolean%20%3D%20myObject.f2('foo'%2C%20'bar')%3B" rel="nofollow noreferrer">TypeScript playground.


问:
JNI system.loadlibrary problem - native C++ dll using C library
I have a pretty annoying compiling problem.

I am trying to do a System.loadlibrary on a C++ DLL in VS2010, which in turns uses a C DLL compiled in VS2008.

The error I am getting is:
java.lang.UnsatisfiedLinkError: The application has failed to start because
its side-by-side configuration is incorrect

This occurs whenever my C++ DLL tries to do a call to a function in the C DLL. Both compiles just fine, and both are in a folder accessible by Java Applet.

Is this possible to solve somehow? Do you need any more info?

答:
Have you installed the runtimes of VC2010 and VC2008?

Additionally you have to make sure the manifests of both DLLs are correctly configured so that the correct version of the used library can be loaded.

See also: http://msdn.microsoft.com/en-us/library/ms235342.aspx


问:
Ajax and Laravel 500 (Internal server error)
I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!

Here is my controller

```<code>public function store(Request $request)
{
    $response = array(
        'msg' => 'Thank you nephew'
    );

    $request->validate([
        'name' => 'required|min:3',
        'mobile' => 'required',
        'address' => 'nullable',
        'email' => 'nullable'
    ]);

    $values = $request->all();

    echo $values;

    return Response::json($response);
}
</code>```

Here is my Ajax script

```<code><script>
    $('#create-form').on('submit', function (event) {
        event.preventDefault();

        let name = $("input[name=name]").val();
        let mobile = $("input[name=mobile]").val();
        let email = $("input[name=email]").val();
        let address = $("input[name=address]").val();

        console.log(name);

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        $.ajax({
            type: 'POST',
            url: '{{ route('addresses.store') }}',
            data: {name: name, mobile: mobile, email: email, address: address, token: $('input[name="_token"]').val()},
            success: function (data) {
                console.log(data);
            }
        });
    });
</script>
</code>```

Here is the blade modal

```<code><div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Create address</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="result"></div>
                <form action="{{ route('addresses.store') }}" method="post" id="create-form">
                    @csrf

                    <div class="form-group">
                        <label for="">Name</label>
                        <input type="text" class="sequence-input" name="name"/>
                    </div>
                    <div class="form-group">
                        <label for="#">Mobile</label>
                        <input type="text" class="sequence-input" name="mobile"/>
                    </div>
                    <div class="form-group">
                        <label for="#">Address</label>
                        <textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="#">Email Address</label>
                        <input type="text" class="sequence-input" name="email"/>
                    </div>
                    <div class="form-group">
                        <button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

答:
Your 500 error is caused by attempting to echo the array $values:

```<code>$values = $request->all();

echo $values; // <-- Your error is here.
</code>```

Try using the dd helper method instead: dd($values)

Body:
I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!

Here is my controller

public function store(Request $request)
{
    $response = array(
        'msg' => 'Thank you nephew'
    );

    $request->validate([
        'name' => 'required|min:3',
        'mobile' => 'required',
        'address' => 'nullable',
        'email' => 'nullable'
    ]);

    $values = $request->all();

    echo $values;

    return Response::json($response);
}

Here is my Ajax script

Here is the blade modal

Create address

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <form action="{{ route('addresses.store') }}" method="post" id="create-form">
                    @csrf

                        Name
                        <input type="text" class="sequence-input" name="name"/>

                        Mobile
                        <input type="text" class="sequence-input" name="mobile"/>

                        Address
                        <textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>

                        Email Address
                        <input type="text" class="sequence-input" name="email"/>

                        <button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>

                </form>

                <button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>

Body:
Your 500 error is caused by attempting to echo the array $values:

$values = $request->all();

echo $values; // <-- Your error is here.

Try using the dd helper method instead: dd($values)


问:
Swift zoom with scrollview not centered
When setting (selected by taking a picture) the image of my imageview (which is inside a scrollview) is set but a little to the right and not centered as is supposed to be

Im not using storyboard, everything is made programmatically

//creating frames
    imgBorder.frame.size = CGSize(width: view.bounds.size.width * 0.7,     height: view.bounds.size.height * 0.7)
        imgBorder.center.x = self.view.bounds.width * 0.5
        imgBorder.center.y = self.view.bounds.height * 0.5
        imgBorder.image = UIImage(named: "imageBorder")
        self.view.addSubview(imgBorder)
        self.view.bringSubviewToFront(imgBorder)

```<code>    scrollImg.delegate = self
    scrollImg.frame = CGRect(x: view.bounds.size.width * 0.5 -     imgBorder.frame.size.width/2, y: view.bounds.size.height * 0.5 - imgBorder.frame.size.height/2, width: imgBorder.bounds.size.width, height: imgBorder.bounds.size.height)
    scrollImg.minimumZoomScale = 1.0
    scrollImg.maximumZoomScale = 6.0

    self.view.addSubview(scrollImg)

    imgPicture.frame.size = scrollImg.frame.size
    imgPicture.center.x = scrollImg.center.x
    imgPicture.center.y = scrollImg.center.y

    scrollImg.addSubview(imgPicture)
</code>```

First image shows when i take the picture (the problem in this post)
Second shows the picture im taking
Third shows that zoom is working fine with border limits

答:
I was able to fix the problem removing these lines of code:</p>

```<code>imgPicture.center.x = scrollImg.center.x
imgPicture.center.y = scrollImg.center.y
</code>```

Title: Swift zoom with scrollview not centered

Body:
When setting (selected by taking a picture) the image of my imageview (which is inside a scrollview) is set but a little to the right and not centered as is supposed to be

Im not using storyboard, everything is made programmatically

//creating frames
    imgBorder.frame.size = CGSize(width: view.bounds.size.width * 0.7,     height: view.bounds.size.height * 0.7)
        imgBorder.center.x = self.view.bounds.width * 0.5
        imgBorder.center.y = self.view.bounds.height * 0.5
        imgBorder.image = UIImage(named: "imageBorder")
        self.view.addSubview(imgBorder)
        self.view.bringSubviewToFront(imgBorder)

    scrollImg.delegate = self
    scrollImg.frame = CGRect(x: view.bounds.size.width * 0.5 -     imgBorder.frame.size.width/2, y: view.bounds.size.height * 0.5 - imgBorder.frame.size.height/2, width: imgBorder.bounds.size.width, height: imgBorder.bounds.size.height)
    scrollImg.minimumZoomScale = 1.0
    scrollImg.maximumZoomScale = 6.0

    self.view.addSubview(scrollImg)

    imgPicture.frame.size = scrollImg.frame.size
    imgPicture.center.x = scrollImg.center.x
    imgPicture.center.y = scrollImg.center.y

    scrollImg.addSubview(imgPicture)

First image shows when i take the picture (the problem in this post)
Second shows the picture im taking
Third shows that zoom is working fine with border limits

Body:
I was able to fix the problem removing these lines of code:

imgPicture.center.x = scrollImg.center.x
imgPicture.center.y = scrollImg.center.y


问:
How do I set a default value for a combo box that draws values from a table/query?
Since I'm new to Access but it is what I have available, I am customizing a database template to fit my needs.  The template came with a table called "Donations" that records all the received money from contributors.  I have added another table called "Descriptions" that has labels for the common types of contributions we receive (Donation, Participant, Sponsor, Anonymous, Memorial, Honorarium).

In the "Donation" table I have added a combo box called "Label" that imports the values from "Description" to populate the list.

```<code>SELECT Descriptions.ID, Descriptions.Label
FROM Descriptions ORDER BY Descriptions.[Label];
</code>```

This lookup is working correctly.

Since most of the contributions we receive fall under the Description/Label of Donation, in the name of efficiency, I would like to set this to be the default value.  However, I have no idea how to do this.

Failed Methods:

"Donation" - Error 'Type mismatch' in the default value.

[Donation] - Could not find field "Donation"

[Description].[Label] - Could not find field "Description].[Label".

答:
Since your lookup query SELECT Descriptions.ID, Descriptions.Label includes the ID, I assume the ID is what is internally stored.

Open your Descriptions table, find the ID of "Donation", and use that number as Default value in the main table.

Body:
Since I'm new to Access but it is what I have available, I am customizing a database template to fit my needs.  The template came with a table called "Donations" that records all the received money from contributors.  I have added another table called "Descriptions" that has labels for the common types of contributions we receive (Donation, Participant, Sponsor, Anonymous, Memorial, Honorarium).

In the "Donation" table I have added a combo box called "Label" that imports the values from "Description" to populate the list.

SELECT Descriptions.ID, Descriptions.Label
FROM Descriptions ORDER BY Descriptions.[Label];

This lookup is working correctly.

Since most of the contributions we receive fall under the Description/Label of Donation, in the name of efficiency, I would like to set this to be the default value.  However, I have no idea how to do this.

Failed Methods:

"Donation" - Error 'Type mismatch' in the default value.

[Donation] - Could not find field "Donation"

[Description].[Label] - Could not find field "Description].[Label".


问:
Separate columns by their strings if they are different
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))
</code>```

And, for example, I am trying with the first column this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")
</code>```

but is not working

I am having the next output:

```<code>TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>
</code>```

My expected output is:

```<code> TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2
</code>```

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

```<code> df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3
</code>```

答:
Here's a base solution. This goes through all possible factors in your column (i.e., TAP1, TAP2) and checks whereabouts they're present. For places where they are present, it returns the name of the level. For places where they're absent, it returns NA. Then, I repackage the resulting list into a data frame and rename the columns.

# Original data frame
df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))

# Repackage
df2 <- data.frame(lapply(levels(df$x), function(x)ifelse(df$x == x, x, NA)))

# Fix names
names(df2) <- levels(df$x)

# Check results
df2
#>   TAP1 TAP2
#> 1 <NA> <NA>
#> 2 TAP1 <NA>
#> 3 TAP1 <NA>
#> 4 <NA> TAP2
```

<p><sup>Created on 2019-05-29 by the reprex package (v0.3.0)</sup></p>

<hr>

<p>In light of your update:</p>

<pre class="lang-r prettyprint-override"><code># Original data frame
df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"),
                 y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

# Define splitter function
splitter <- function(foo){
  tmp <- data.frame(lapply(levels(foo), function(x)ifelse(foo == x, x, NA)))
  names(tmp) <- levels(foo)
  tmp
}

# Run over data frame and bind together
do.call(cbind, lapply(df, splitter))
#>   x.TAP1 x.TAP2 y.TAP1 y.TAP2 y.TAP3
#> 1   <NA>   <NA>   TAP1   <NA>   <NA>
#> 2   TAP1   <NA>   <NA>   TAP2   <NA>
#> 3   TAP1   <NA>   <NA>   TAP2   <NA>
#> 4   <NA>   TAP2   <NA>   <NA>   TAP3
</code>```

Created on 2019-05-29 by the reprex package (v0.3.0)

Same rationale as before, but I define a function that is applied to each column and the results are bound together using do.call and cbind.

Body:
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))

And, for example, I am trying with the first column this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")

but is not working

I am having the next output:

TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>

My expected output is:

 TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

 df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3

Body:
Here's a base solution. This goes through all possible factors in your column (i.e., TAP1, TAP2) and checks whereabouts they're present. For places where they are present, it returns the name of the level. For places where they're absent, it returns NA. Then, I repackage the resulting list into a data frame and rename the columns.

# Original data frame
df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))

# Repackage
df2 <- data.frame(lapply(levels(df$x), function(x)ifelse(df$x == x, x, NA)))

# Fix names
names(df2) <- levels(df$x)

# Check results
df2
#>   TAP1 TAP2
#> 1 <NA> <NA>
#> 2 TAP1 <NA>
#> 3 TAP1 <NA>
#> 4 <NA> TAP2

Created on 2019-05-29 by the reprex package (v0.3.0)

In light of your update:

# Original data frame
df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"),
                 y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

# Define splitter function
splitter <- function(foo){
  tmp <- data.frame(lapply(levels(foo), function(x)ifelse(foo == x, x, NA)))
  names(tmp) <- levels(foo)
  tmp
}

# Run over data frame and bind together
do.call(cbind, lapply(df, splitter))
#>   x.TAP1 x.TAP2 y.TAP1 y.TAP2 y.TAP3
#> 1   <NA>   <NA>   TAP1   <NA>   <NA>
#> 2   TAP1   <NA>   <NA>   TAP2   <NA>
#> 3   TAP1   <NA>   <NA>   TAP2   <NA>
#> 4   <NA>   TAP2   <NA>   <NA>   TAP3

Created on 2019-05-29 by the reprex package (v0.3.0)

Same rationale as before, but I define a function that is applied to each column and the results are bound together using do.call and cbind.