问:
How to achieve @args splatting in an advanced function in Powershell?
Consider the following simple function:

```<code>function Write-HostIfNotVerbose()
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @args
    }
}
</code>```

And it works fine:

Now I want to make it an advanced function, because I want it to inherit the verbosity preference:

```<code>function Write-HostIfNotVerbose([Parameter(ValueFromRemainingArguments)]$MyArgs)
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @MyArgs
    }
}
</code>```

But it does not work:

And what drives me nuts is that I am unable to identify how $args in the first example is different from $args in the second.

I know that the native @args splatting does not work for advanced functions by default - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.2#notes

But I hoped it could be simulated, yet it does not work either. My question is - what is wrong with the way I am trying to simulate it and whether it is possible to fix my code without surfacing all the Write-Host parameters at Write-HostIfNotVerbose

答:
Santiago Squarzon's helpful answer contains some excellent sleuthing that reveals the hidden magic behind @args, i.e. splatting using the automatic $args variable, which is available in simple (non-advanced) functions only.

The solution in Santiago's answer isn't just complex, it also isn't fully robust, as it wouldn't be able to distinguish -ForegroundColor (a parameter name) from '-ForegroundColor' a parameter value that happens to look like a parameter name, but is distinguished from it by quoting.

As an aside: even the built-in @args magic has a limitation: it doesn't correctly pass a [switch] parameter specified with an explicit value through, such as

-NoNewLine:$false[1]

A robust solution requires splatting via the automatic $PSBoundParameters variable, which in turn requires that the wrapping function itself also declare all potential pass-through parameters.

Such a wrapping function is called a proxy function, and the PowerShell SDK facilitates scaffolding such functions via the PowerShell SDK, as explained in this answer.

In your case, you'd have to define your function as follows:

```<code>function Write-HostIfNotVerbose {
  [CmdletBinding()]
  param(
    [Parameter(Position = 0, ValueFromPipeline, ValueFromRemainingArguments)]
    [Alias('Msg', 'Message')]
    $Object,
    [switch] $NoNewline,
    $Separator,
    [System.ConsoleColor] $ForegroundColor,
    [System.ConsoleColor] $BackgroundColor
  )

  begin {
    $scriptCmd =
      if ($VerbosePreference -eq 'SilentlyContinue') { { Write-Host @PSBoundParameters } }
      else                                           { { Out-Null } }
    $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
    $steppablePipeline.Begin($PSCmdlet)
  }

  process {
    $steppablePipeline.Process($_)
  }

  end {
    $steppablePipeline.End()
  }

}
</code>```

[1] Such an argument is invariably passed through as two arguments, namely as parameter name -NoNewLine by itself, followed by a separate argument, $false. The problem is that at the time the original arguments are parsed into $args, it isn't yet known what formally declared parameters they will bind to. The NoteProperty tagging applied to $args for marking elements as parameter names doesn't preserve the information as to whether the subsequent argument was separated from the parameter name with :, which for a [switch] parameter is necessary to identify that argument as belonging to the switch. In the absence of this information, two separate arguments are always passed during splatting.

Body:
Consider the following simple function:

function Write-HostIfNotVerbose()
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @args
    }
}

And it works fine:

Now I want to make it an advanced function, because I want it to inherit the verbosity preference:

function Write-HostIfNotVerbose([Parameter(ValueFromRemainingArguments)]$MyArgs)
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @MyArgs
    }
}

But it does not work:

And what drives me nuts is that I am unable to identify how $args in the first example is different from $args in the second.

I know that the native @args splatting does not work for advanced functions by default - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.2#notes

But I hoped it could be simulated, yet it does not work either. My question is - what is wrong with the way I am trying to simulate it and whether it is possible to fix my code without surfacing all the Write-Host parameters at Write-HostIfNotVerbose

Body:
Santiago Squarzon's helpful answer contains some excellent sleuthing that reveals the hidden magic behind @args, i.e. splatting using the automatic $args variable, which is available in simple (non-advanced) functions only.

The solution in Santiago's answer isn't just complex, it also isn't fully robust, as it wouldn't be able to distinguish -ForegroundColor (a parameter name) from '-ForegroundColor' a parameter value that happens to look like a parameter name, but is distinguished from it by quoting.

As an aside: even the built-in @args magic has a limitation: it doesn't correctly pass a [switch] parameter specified with an explicit value through, such as

-NoNewLine:$false[1]

A robust solution requires splatting via the automatic $PSBoundParameters variable, which in turn requires that the wrapping function itself also declare all potential pass-through parameters.

Such a wrapping function is called a proxy function, and the PowerShell SDK facilitates scaffolding such functions via the PowerShell SDK, as explained in this answer.

In your case, you'd have to define your function as follows:

function Write-HostIfNotVerbose {
  [CmdletBinding()]
  param(
    [Parameter(Position = 0, ValueFromPipeline, ValueFromRemainingArguments)]
    [Alias('Msg', 'Message')]
    $Object,
    [switch] $NoNewline,
    $Separator,
    [System.ConsoleColor] $ForegroundColor,
    [System.ConsoleColor] $BackgroundColor
  )

  begin {
    $scriptCmd =
      if ($VerbosePreference -eq 'SilentlyContinue') { { Write-Host @PSBoundParameters } }
      else                                           { { Out-Null } }
    $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
    $steppablePipeline.Begin($PSCmdlet)
  }

  process {
    $steppablePipeline.Process($_)
  }

  end {
    $steppablePipeline.End()
  }

}

[1] Such an argument is invariably passed through as two arguments, namely as parameter name -NoNewLine by itself, followed by a separate argument, $false. The problem is that at the time the original arguments are parsed into $args, it isn't yet known what formally declared parameters they will bind to. The NoteProperty tagging applied to $args for marking elements as parameter names doesn't preserve the information as to whether the subsequent argument was separated from the parameter name with :, which for a [switch] parameter is necessary to identify that argument as belonging to the switch. In the absence of this information, two separate arguments are always passed during splatting.


来源: stackexchange

问:
Spring boot - Not a managed type
I use Spring boot+JPA and having a problem while starting the service.

```<code>Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.nervytech.dialer.domain.PhoneSettings
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:177)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
</code>```

Here is the Application.java file,

```<code>@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@SpringBootApplication
public class DialerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DialerApplication.class, args);
    }
}
</code>```

I use UCp for connection pooling and the DataSource configuration is below,

```<code>@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervy.dialer.spring.jpa.repository" })
public class ApplicationDataSource {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ApplicationDataSource.class);

    /** The Constant TEST_SQL. */
    private static final String TEST_SQL = "select 1 from dual";

    /** The pooled data source. */
    private PoolDataSource pooledDataSource;
</code>```

UserDetailsService Implementation,

```<code>@Service("userDetailsService")
@SessionAttributes("user")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
</code>```

Service layer implementation,

```<code>@Service
public class PhoneSettingsServiceImpl implements PhoneSettingsService {

}
</code>```

The repository class,

```<code>@Repository
public interface PhoneSettingsRepository extends JpaRepository<PhoneSettings, Long> {

}
</code>```

Entity class,

```<code>@Entity
@Table(name = "phone_settings", catalog = "dialer")
public class PhoneSettings implements java.io.Serializable {
</code>```

WebSecurityConfig class,

```<code>@Configuration
@EnableWebMvcSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * Instantiates a new web security config.
     */
    public WebSecurityConfig() {

        super();
    }

    /**
     * {@inheritDoc}
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/login", "/logoffUser", "/sessionExpired", "/error", "/unauth", "/redirect", "*support*").permitAll()
            .anyRequest().authenticated().and().rememberMe().and().httpBasic()
            .and()
            .csrf()
            .disable().logout().deleteCookies("JSESSIONID").logoutSuccessUrl("/logoff").invalidateHttpSession(true);
    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

}
</code>```

The packages are as follows,

Application class is in - com.nervy.dialer

Datasource class is in - com.nervy.dialer.common

Entity classes are in - com.nervy.dialer.domain

Service classes are in - com.nervy.dialer.domain.service.impl

Controllers are in - com.nervy.dialer.spring.controller

Repository classes are in - com.nervy.dialer.spring.jpa.repository

WebSecurityConfig is in - com.nervy.dialer.spring.security

Thanks

答:
I've reproduced similar issue w/ Not a managed type.

More specifically:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockPriceRepository' defined in com.example.stockclient.repository.StockPriceRepository defined in @EnableJpaRepositories declared on StockUiApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.stockclient.StockPrice
</code>```

As I had multi-module project, I needed to enable auto configuration support for Spring Data JPA required to know the path of JPA repositories, because by default, it will scan only the main application package and its sub packages for detecting JPA repositories.

So in my specific use case I've already used @EnableJpaRepositories to enable the JPA repositories that contains in necessary packages, but without @EntityScan.

With @EntityScan was the same story as with @EnableJpaRepositories, because  entity classes weren't placed in the main application package because of multi-module project.

For more details you can refer, for instance, to this article.

ContentLicense: CC BY-SA 4.0

Title: Spring boot - Not a managed type

Body:
I use Spring boot+JPA and having a problem while starting the service.

Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.nervytech.dialer.domain.PhoneSettings
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:177)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)

Here is the Application.java file,

@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@SpringBootApplication
public class DialerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DialerApplication.class, args);
    }
}

I use UCp for connection pooling and the DataSource configuration is below,

@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervy.dialer.spring.jpa.repository" })
public class ApplicationDataSource {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ApplicationDataSource.class);

    /** The Constant TEST_SQL. */
    private static final String TEST_SQL = "select 1 from dual";

    /** The pooled data source. */
    private PoolDataSource pooledDataSource;

UserDetailsService Implementation,

@Service("userDetailsService")
@SessionAttributes("user")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

Service layer implementation,

@Service
public class PhoneSettingsServiceImpl implements PhoneSettingsService {

}

The repository class,

@Repository
public interface PhoneSettingsRepository extends JpaRepository<PhoneSettings, Long> {

}

Entity class,

@Entity
@Table(name = "phone_settings", catalog = "dialer")
public class PhoneSettings implements java.io.Serializable {

WebSecurityConfig class,

@Configuration
@EnableWebMvcSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * Instantiates a new web security config.
     */
    public WebSecurityConfig() {

        super();
    }

    /**
     * {@inheritDoc}
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/login", "/logoffUser", "/sessionExpired", "/error", "/unauth", "/redirect", "*support*").permitAll()
            .anyRequest().authenticated().and().rememberMe().and().httpBasic()
            .and()
            .csrf()
            .disable().logout().deleteCookies("JSESSIONID").logoutSuccessUrl("/logoff").invalidateHttpSession(true);
    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

}

The packages are as follows,

Application class is in - com.nervy.dialer

Datasource class is in - com.nervy.dialer.common

Entity classes are in - com.nervy.dialer.domain

Service classes are in - com.nervy.dialer.domain.service.impl

Controllers are in - com.nervy.dialer.spring.controller

Repository classes are in - com.nervy.dialer.spring.jpa.repository

WebSecurityConfig is in - com.nervy.dialer.spring.security

Thanks

Body:
I've reproduced similar issue w/ Not a managed type.

More specifically:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockPriceRepository' defined in com.example.stockclient.repository.StockPriceRepository defined in @EnableJpaRepositories declared on StockUiApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.stockclient.StockPrice

As I had multi-module project, I needed to enable auto configuration support for Spring Data JPA required to know the path of JPA repositories, because by default, it will scan only the main application package and its sub packages for detecting JPA repositories.

So in my specific use case I've already used @EnableJpaRepositories to enable the JPA repositories that contains in necessary packages, but without @EntityScan.

With @EntityScan was the same story as with @EnableJpaRepositories, because  entity classes weren't placed in the main application package because of multi-module project.

For more details you can refer, for instance, to this article.


问:
Is there a code that will use CSS to hide a class if within a certain window-type?
I'm currently trying to create an app from my WordPress site but when I do, I'm running into the issue of the header, right sidebar, and footer showing. I'd ultimately like to hide these if they appear within a window without a URL option. I'm not even sure that's viable.

What's happening is that the app maker is pulling in pages from my WordPress site and displaying like an app. Except for the header, sidebar, and footer unnecessarily being there. I can't hide these based on screen because I still want people with mobile devices to be able to see if they're looking on a browser window.

答:
CSS does not have the power to do this, it's something that needs to be done either with client-side (JS) or server-side. The latter would probably be a cleaner and easier option.

On the server side, with PHP you can do the following:

$hide_stuff = (isset($_GET['hide']) && trim($_GET['hide']) == '1');

if ($hide_stuff) {
    echo '<link rel="stylesheet" type="text/css" href="/path/to/file.css">';
}
```

So that when the page URL includes ?hide=1 the server will automatically add /path/to/file.css to the page. Then, in file.css you can simply do whatever you want, like hiding elements.

Body:
CSS does not have the power to do this, it's something that needs to be done either with client-side (JS) or server-side. The latter would probably be a cleaner and easier option.

On the server side, with PHP you can do the following:

$hide_stuff = (isset($_GET['hide']) && trim($_GET['hide']) == '1');

if ($hide_stuff) {
    echo '<link rel="stylesheet" type="text/css" href="/path/to/file.css">';
}

So that when the page URL includes ?hide=1 the server will automatically add /path/to/file.css to the page. Then, in file.css you can simply do whatever you want, like hiding elements.


问:
How to append different react components to a list on a click of a button?
I have two kinds of components, I want them to appear in the screen on the click of a button, but it is not like show and hide components, it is more like generate theme many times. like if I click the button, I can add more and more, so if i click on the first button it generates component 1 and when I click on the second button it appends the second component to the list and etc.

I have no idea how to achieve this, I thought of storing the components in a state and do a map loop, but i not sure if this possible (storing components in state) and if it's a good practice.

答:
I think I have had a similar situation while making a math solving website where I wanted to show the solution (JSX Element) when the user clicks on "solve" button. I don't know if this is the best practice but I just created a SolutionObject with the following typescript interface:

interface SolutionObject {
  isSolved: boolean;
  solutionElement: JSX.Element;
}
```
<p>I then initialised the solution object using the <code>useState()</code> hook:</p>
<pre class="lang-js prettyprint-override"><code>const [Solution, solved] = useState<SolutionObject>();
</code>```

Then I used it in my React component like this

```<code><div className="solution">
    {Solution?.solutionElement}
</div>
{Solution?.isSolved ? <button onClick={closeBtn}>Close</button> : null}
</code>```

To update the solution, I just updated the solution object with the JSX in solutionElement property in a solve function with the correct JSX for step-by-step solution. Here is an example:

```<code>solved({
      isSolved: true,
      solutionElement:
        // prettier-ignore
        <div className="card">
          <h2>Using Distance Formula</h2>
          <p>
            <Latex>{`$Distance\\ (D) = \\sqrt{(x_{2}-x_{1})^2 + (y_{2}-y_{1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{(${X2}-${X1})^2 + (${Y2}-${Y1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{(${X2 - X1})^2 + (${Y2 - Y1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{${(X2 - X1) ** 2} + ${(Y2 - Y1) ** 2}}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{${(X2 - X1) ** 2 + (Y2 - Y1) ** 2}}$`}</Latex>
            <br /><br />
            <Latex>{`$D = ${formatSquareRoot((X2 - X1) ** 2 + (Y2 - Y1) ** 2).outer}\\sqrt{${formatSquareRoot((X2 - X1) ** 2 + (Y2 - Y1) ** 2).inner}}$`}</Latex>
          </p>
        </div>,
    });
</code>```

I don't know if this is exactly what you are looking for, but your question sounds similar. I guess you can use this idea to store JSX elements in a state and render them in your component. If you have a list of JSX elements, you may use the JSX.Element[] type for them (if you use typescript) and map them

```<code>{items &&
    items.map((Item, i) => (
        <div key={i}>
            <Item />
        </div>
     ))}
</code>```

Again, I am not much experienced with this and don't know if it is the best practice but it sure works.

Body:
I think I have had a similar situation while making a math solving website where I wanted to show the solution (JSX Element) when the user clicks on "solve" button. I don't know if this is the best practice but I just created a SolutionObject with the following typescript interface:

interface SolutionObject {
  isSolved: boolean;
  solutionElement: JSX.Element;
}

I then initialised the solution object using the useState() hook:

const [Solution, solved] = useState<SolutionObject>();

Then I used it in my React component like this

<div className="solution">
    {Solution?.solutionElement}
</div>
{Solution?.isSolved ? <button onClick={closeBtn}>Close</button> : null}

To update the solution, I just updated the solution object with the JSX in solutionElement property in a solve function with the correct JSX for step-by-step solution. Here is an example:

solved({
      isSolved: true,
      solutionElement:
        // prettier-ignore
        <div className="card">
          <h2>Using Distance Formula</h2>
          <p>
            <Latex>{`$Distance\\ (D) = \\sqrt{(x_{2}-x_{1})^2 + (y_{2}-y_{1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{(${X2}-${X1})^2 + (${Y2}-${Y1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{(${X2 - X1})^2 + (${Y2 - Y1})^2}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{${(X2 - X1) ** 2} + ${(Y2 - Y1) ** 2}}$`}</Latex>
            <br /><br />
            <Latex>{`$D = \\sqrt{${(X2 - X1) ** 2 + (Y2 - Y1) ** 2}}$`}</Latex>
            <br /><br />
            <Latex>{`$D = ${formatSquareRoot((X2 - X1) ** 2 + (Y2 - Y1) ** 2).outer}\\sqrt{${formatSquareRoot((X2 - X1) ** 2 + (Y2 - Y1) ** 2).inner}}$`}</Latex>
          </p>
        </div>,
    });

I don't know if this is exactly what you are looking for, but your question sounds similar. I guess you can use this idea to store JSX elements in a state and render them in your component. If you have a list of JSX elements, you may use the JSX.Element[] type for them (if you use typescript) and map them

{items &&
    items.map((Item, i) => (
        <div key={i}>
            <Item />
        </div>
     ))}

Again, I am not much experienced with this and don't know if it is the best practice but it sure works.


问:
Reducing iterator based on value
I have an iterator as such:

```<code>Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))
</code>```

I'm trying to return an iterator, but with the values slightly changed. The values for all multiples of 5 must be added to the previous row. So the result would be:

```<code>Iterator(List(1, 2012), List(2, 4032), List(7, 2020))
</code>```

I've tried using the following method:

```<code>val a = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

val aTransformed = a.reduce((x,y) => if (y(0)%5 == 0) List(x(0),x(1)+y(1)) else x)
</code>```

but it gives me the final value val aTransformed: List[Int] = List(1, 4029)

What can I do to get an iterator in my desired format? Is there a method to just check the previous/next row without folding it all into one final value?

I know this is possible by converting the iterator to a List, traversing, mutating and converting back to an iterator, but is there a more elegant solution?

Edit for clarification:

Consecutive multiples of 5 will get collated into one sum

Ex:

```<code>Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))
</code>```

should become

```<code>Iterator(List(1, 2012), List(2, 6057))
</code>```

答:
Following is a possible way to get the expected result. I haven't checked all the possibilities..</p>
```<code>val interResult = itr.foldLeft((List.empty[List[Int]], List.empty[Int])) { (acc, curr) =>
    if(curr.size != 2)
      acc
    else if(acc._2.isEmpty)
      (acc._1, curr)
    else
      if(curr.headOption.exists(_ % 5 == 0))
        (acc._1, List(acc._2.head, acc._2.last + curr.last))
      else
        (acc._1 :+ acc._2, curr)
  }

interResult._1 :+ interResult._2
</code>```

Title: Reducing iterator based on value

Body:
I have an iterator as such:

Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

I'm trying to return an iterator, but with the values slightly changed. The values for all multiples of 5 must be added to the previous row. So the result would be:

Iterator(List(1, 2012), List(2, 4032), List(7, 2020))

I've tried using the following method:

val a = Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(7, 2020))

val aTransformed = a.reduce((x,y) => if (y(0)%5 == 0) List(x(0),x(1)+y(1)) else x)

but it gives me the final value val aTransformed: List[Int] = List(1, 4029)

What can I do to get an iterator in my desired format? Is there a method to just check the previous/next row without folding it all into one final value?

I know this is possible by converting the iterator to a List, traversing, mutating and converting back to an iterator, but is there a more elegant solution?

Edit for clarification:

Consecutive multiples of 5 will get collated into one sum

Ex:

Iterator(List(1, 2012), List(2, 2015), List(5, 2017), List(10, 2025))

should become

Iterator(List(1, 2012), List(2, 6057))

Body:
Following is a possible way to get the expected result. I haven't checked all the possibilities..

val interResult = itr.foldLeft((List.empty[List[Int]], List.empty[Int])) { (acc, curr) =>
    if(curr.size != 2)
      acc
    else if(acc._2.isEmpty)
      (acc._1, curr)
    else
      if(curr.headOption.exists(_ % 5 == 0))
        (acc._1, List(acc._2.head, acc._2.last + curr.last))
      else
        (acc._1 :+ acc._2, curr)
  }

interResult._1 :+ interResult._2


问:
P5.js make ellipses move so it looks like a splash
I'm trying to create a canvas that the user can interact with. I need help solving the following problems.

At the fountain at the front, ellipses should fly up into the air. All ellipses should move a little differently than the others. The ellipses should also come down to the water surface again and then disappear. It should simply look like a small splash. This should be done within a certain radius from the mouse click the user makes to activate the event.

Here is the part of the code that have with the problem to do. I am also sharing my canvas to hopefully make everything a bit clearer.

var Water;
var image;

function preload() {
  image = loadImage("Vy över Versailles.png");
  soundFormats('mp3', 'ogg');
  Water = loadSound('202915__tritus__fountain02.wav');
}

function setup() {
  let cnv = createCanvas(638, 413);
  cnv.mouseClicked(CanvasPressed);
  background(image);
}

function CanvasPressed() {
  if (mouseX > 0 && mouseX < 638 && mouseY > 170 && mouseY < 300) {
    Water.stop();
    Water.play();

    let blue = color(0, 0, 255);
    fill(blue);
    noStroke();
    let antal = random(5)

    if (mouseX > 130 && mouseX < 510 && mouseY > 275 && mouseY < 310) {
      for (var i = 0; i < antal; i++) {
        let musX = mouseX - random(i * 10);
        let musY = mouseY - random(i * 10);
        let xSize = random(20);
        ellipse(musX, musY, xSize);
      }
      ellipse(mouseX, mouseY, 50, 6);
    }
  }
}
```

答:
Use frameRate() (how many frames / s) in function preload():

```<code>var image;

function preload() {
  image = loadImage("Vy över Versailles.png");
  soundFormats('mp3', 'ogg');
  Water = loadSound('202915__tritus__fountain02.wav');
  // Here I will set the frameRate() to 24
  frameRate(24);
}

function setup() {
  let cnv = createCanvas(638, 413);
  cnv.mouseClicked(CanvasPressed);
  background(image);
}

function CanvasPressed() {
  if (mouseX > 0 && mouseX < 638 && mouseY > 170 && mouseY < 300) {
    Water.stop();
    Water.play();

    let blue = color(0, 0, 255);
    fill(blue);
    noStroke();
    let antal = random(5)

    if (mouseX > 130 && mouseX < 510 && mouseY > 275 && mouseY < 310) {
      for (var i = 0; i < antal; i++) {
        let musX = mouseX - random(i * 10);
        let musY = mouseY - random(i * 10);
        let xSize = random(20);
        ellipse(musX, musY, xSize);
      }
      ellipse(mouseX, mouseY, 50, 6);
    }
  }
}
</code>```

Body:
Use frameRate() (how many frames / s) in function preload():

var image;

function preload() {
  image = loadImage("Vy över Versailles.png");
  soundFormats('mp3', 'ogg');
  Water = loadSound('202915__tritus__fountain02.wav');
  // Here I will set the frameRate() to 24
  frameRate(24);
}

function setup() {
  let cnv = createCanvas(638, 413);
  cnv.mouseClicked(CanvasPressed);
  background(image);
}

function CanvasPressed() {
  if (mouseX > 0 && mouseX < 638 && mouseY > 170 && mouseY < 300) {
    Water.stop();
    Water.play();

    let blue = color(0, 0, 255);
    fill(blue);
    noStroke();
    let antal = random(5)

    if (mouseX > 130 && mouseX < 510 && mouseY > 275 && mouseY < 310) {
      for (var i = 0; i < antal; i++) {
        let musX = mouseX - random(i * 10);
        let musY = mouseY - random(i * 10);
        let xSize = random(20);
        ellipse(musX, musY, xSize);
      }
      ellipse(mouseX, mouseY, 50, 6);
    }
  }
}


问:
Text based game 'Exit Game' process
Good evening, I am working on a text-based game for my scripting class. This week we are incrementing the "move between rooms" process. My code is working smoothly except I cannot get the user to exit the game. When I type "Exit" It tells me "Ouch! I hit a wall." Not sure why it's going through the if statement and not the elif statement I have for exiting the game.</p>
```<code># Nick Thomas
# declaration
rooms = {
    'Ground Level': {'Right': 'Library', 'Up': 'Bedroom'},
    'Library': {'Left': 'Ground Level', 'Up': 'Enchanting Lab'},
    'Bedroom': {'Right': 'Enchanting Lab', 'Down': 'Ground Level'},
    'Enchanting Lab': {'Left': 'Bedroom', 'Down': 'Library'}
}
state = 'Ground Level'

# function
def get_new_state(state, direction):
    new_state = state  # declaration
    for i in rooms:  # loop
        if i == state:  # if statement
            if direction in rooms[i]:  # if statement
                new_state = rooms[i][direction]  # assigns new_state
    return new_state  # return

# FIXME: a function for getting items

# function
def instructions():
    # print a main menu and the commands
    print('Necromancer’s Lair Text Game')
    print('Move commands: go Up, go Down, go Left, go Right')
    print('To Exit: type Exit')
    # FIXME: add instructions for what do and how to get an item

instructions()
# FIXME: add empty inventory list
while 1:
    print('You are in the', state)  # prints state
    print('------------------------------')
    direction = input('Enter your move: ')  # asking user
    if direction == 'go Up' or 'go Down' or 'go Left' or 'go Right':
        direction = direction[3:]
        new_state = get_new_state(state, direction)  # calling function
        if new_state == state:  # if statement
            print('Ouch! You hit a wall.')
        else:
            state = new_state
    elif direction == 'Exit':
        print('Thanks for playing!')
        exit(0)
    else:
        print('Invalid Direction!!')
</code>```

答:
you need to change the if condition as below where direction is compared against each direction i.e. go Up, go Down, go Left and go Right</p>
```<code>if direction == 'go Up' or direction=='go Down' or direction=='go Left' or direction=='go Right':
</code>```

Title: Text based game 'Exit Game' process

Body:
Good evening, I am working on a text-based game for my scripting class. This week we are incrementing the "move between rooms" process. My code is working smoothly except I cannot get the user to exit the game. When I type "Exit" It tells me "Ouch! I hit a wall." Not sure why it's going through the if statement and not the elif statement I have for exiting the game.

# Nick Thomas
# declaration
rooms = {
    'Ground Level': {'Right': 'Library', 'Up': 'Bedroom'},
    'Library': {'Left': 'Ground Level', 'Up': 'Enchanting Lab'},
    'Bedroom': {'Right': 'Enchanting Lab', 'Down': 'Ground Level'},
    'Enchanting Lab': {'Left': 'Bedroom', 'Down': 'Library'}
}
state = 'Ground Level'

# function
def get_new_state(state, direction):
    new_state = state  # declaration
    for i in rooms:  # loop
        if i == state:  # if statement
            if direction in rooms[i]:  # if statement
                new_state = rooms[i][direction]  # assigns new_state
    return new_state  # return

# FIXME: a function for getting items

# function
def instructions():
    # print a main menu and the commands
    print('Necromancer’s Lair Text Game')
    print('Move commands: go Up, go Down, go Left, go Right')
    print('To Exit: type Exit')
    # FIXME: add instructions for what do and how to get an item

instructions()
# FIXME: add empty inventory list
while 1:
    print('You are in the', state)  # prints state
    print('------------------------------')
    direction = input('Enter your move: ')  # asking user
    if direction == 'go Up' or 'go Down' or 'go Left' or 'go Right':
        direction = direction[3:]
        new_state = get_new_state(state, direction)  # calling function
        if new_state == state:  # if statement
            print('Ouch! You hit a wall.')
        else:
            state = new_state
    elif direction == 'Exit':
        print('Thanks for playing!')
        exit(0)
    else:
        print('Invalid Direction!!')

Body:
you need to change the if condition as below where direction is compared against each direction i.e. go Up, go Down, go Left and go Right

if direction == 'go Up' or direction=='go Down' or direction=='go Left' or direction=='go Right':


问:
How to display images using props in react?
I'm new to React and I am following a tutorial. Right now I have the following code:

index.js:

```<code>import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(
    <App />,
    document.getElementById("root")
)
</code>```

App.js:

```<code>import Contact from "./components/Contact"
export default function App() {
    return (
        <div className="contacts">
            <Contact
                img="../images/mr-whiskerson.png"
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}
</code>```

Contact.js:

```<code>import React from "react"
import ReactDOM from "react-dom"

export default function Contact(props) {
return (
        < div className="contact-card" >
            <img src={props.img} />
            <h3>{props.name}</h3>
            <div className="info-group">
                <img src="../images/phone-icon.png" />
                <p>{props.phone}</p>
            </div>
            <div className="info-group">
                <img src="../images/mail-icon.png" />
                <p>{props.email}</p>
            </div>
        </div >
    )
}
</code>```

All the files above are structured like this:

My problem is that I can't seem to display the images:

This is exactly how the tutorial has it, and I know the image directory is correct since if I hard code the directory for 'mr-whiskerson.png' on Contact component like this

..the image is displayed

So my question is, is there something I am missing? Do I need to use special syntax to display images that is not used to display paragraphs? I am honestly confused and I would really appreciate those who could help me understand. Thank you.

答:
in your structur folder images and App.js file in one structur, you just need pass the image url in App.js with

./images/phone-icon.png

Body:
I'm new to React and I am following a tutorial. Right now I have the following code:

index.js:

import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(
    <App />,
    document.getElementById("root")
)

App.js:

import Contact from "./components/Contact"
export default function App() {
    return (

            <Contact
                img="../images/mr-whiskerson.png"
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}

Contact.js:

import React from "react"
import ReactDOM from "react-dom"

export default function Contact(props) {
return (

{props.name}

{props.phone}

{props.email}

    )
}

All the files above are structured like this:

My problem is that I can't seem to display the images:

This is exactly how the tutorial has it, and I know the image directory is correct since if I hard code the directory for 'mr-whiskerson.png' on Contact component like this

..the image is displayed

So my question is, is there something I am missing? Do I need to use special syntax to display images that is not used to display paragraphs? I am honestly confused and I would really appreciate those who could help me understand. Thank you.


问:
Combine SQL Select Lines into "Groups"
I have the following problem,

I have an audit system, which saves the ID of at most three companies for each Audit onde the database line, but it is possible to have up to 15 companies in an audit.

Criteria to determine if group audit
IF

A record has data in Audited_Company2 AND/OR Audited_Company3
THEN
Find additional records where:

Auditor_ID AND Audit_Type AND Audit_Date all match the record found above AND
IF
Records matching criteria are found:
1.Take Audited_Company1-3 from all other matching records and insert them into Audited_Company4-15

Do not show any audits that have had Audited_Company fields merged into another record in the view

However, I have no idea how to I merge 2 or more SQL Lines n a select result like they asked

答:
You can use UNPIVOT to normalize your data and then PIVOT to denormalize it again. Below is a sample query that combines the two. It uses ROW_NUMBER() with appropriate partitioning and ordering conditions to assign sequence numbers to the data for use in the final pivot.

```<code>DECLARE @Unnormalized TABLE (Id INT, Value1 VARCHAR(100), Value2 VARCHAR(100), Value3 VARCHAR(100))
INSERT @Unnormalized
VALUES
    (1, 'A', 'B', 'C'),
    (1, 'Z', 'Y', NULL),
    (1, 'X', NULL, NULL),
    (2, 'Red', 'Green', NULL),
    (2, 'Blue', NULL, NULL)

SELECT P.Id, Value1 = P.[1], Value2 = P.[2], P.[3], P.[4], P.[5], P.[6], P.[7], P.[8], P.[9]
FROM (
    SELECT U.Id, U.Value, Sequence = ROW_NUMBER() OVER(PARTITION BY U.ID ORDER BY U.Value)
    FROM (SELECT * FROM @Unnormalized) D
    UNPIVOT (Value FOR Col IN (Value1, Value2, Value3)) U
) A
PIVOT (MAX(Value) FOR Sequence IN ([1],[2],[3],[4],[5],[6],[7],[8],[9])) P
</code>```

Results:

Id
Value1
Value2
3
4
5
6
7
8
9

1
A
B
C
X
Y
Z
NULL
NULL
NULL

2
Blue
Green
Red
NULL
NULL
NULL
NULL
NULL
NULL

You should be able to expand on the above to suit your specific needs.
For more information, take a look at the documentation at FROM - Using PIVOT and UNPIVOT.

Title: Combine SQL Select Lines into "Groups"

Body:
You can use UNPIVOT to normalize your data and then PIVOT to denormalize it again. Below is a sample query that combines the two. It uses ROW_NUMBER() with appropriate partitioning and ordering conditions to assign sequence numbers to the data for use in the final pivot.

DECLARE @Unnormalized TABLE (Id INT, Value1 VARCHAR(100), Value2 VARCHAR(100), Value3 VARCHAR(100))
INSERT @Unnormalized
VALUES
    (1, 'A', 'B', 'C'),
    (1, 'Z', 'Y', NULL),
    (1, 'X', NULL, NULL),
    (2, 'Red', 'Green', NULL),
    (2, 'Blue', NULL, NULL)

SELECT P.Id, Value1 = P.[1], Value2 = P.[2], P.[3], P.[4], P.[5], P.[6], P.[7], P.[8], P.[9]
FROM (
    SELECT U.Id, U.Value, Sequence = ROW_NUMBER() OVER(PARTITION BY U.ID ORDER BY U.Value)
    FROM (SELECT * FROM @Unnormalized) D
    UNPIVOT (Value FOR Col IN (Value1, Value2, Value3)) U
) A
PIVOT (MAX(Value) FOR Sequence IN ([1],[2],[3],[4],[5],[6],[7],[8],[9])) P

Results:

Id
Value1
Value2
3
4
5
6
7
8
9

1
A
B
C
X
Y
Z
NULL
NULL
NULL

2
Blue
Green
Red
NULL
NULL
NULL
NULL
NULL
NULL

You should be able to expand on the above to suit your specific needs.
For more information, take a look at the documentation at FROM - Using PIVOT and UNPIVOT.


问:
There is a way to record my game on unity?
I have a game that I create and I want to add an option to record the game after I build it.
I find the unity recorder but I can use it only at the editor and I want to create a video that the unity save and then the player can watch it at the future.
someone know a solution for that? it seems that anyone don't try it before(or don't publish about it before).</p>

答:
Try using some plug-ins! There are plenty of plug-ins to help you do just that!
As an example, I'm using AVPro to record video in my own project!</p>


问:
How to break out from a ruby block?
Here is Bar#do_things:

```<code>class Bar
  def do_things
    Foo.some_method(x) do |x|
      y = x.do_something
      return y_is_bad if y.bad? # how do i tell it to stop and return do_things?
      y.do_something_else
    end
    keep_doing_more_things
  end
end
</code>```

And here is Foo#some_method:

```<code>class Foo
  def self.some_method(targets, &block)
    targets.each do |target|
      begin
        r = yield(target)
      rescue
        failed << target
      end
    end
  end
end
</code>```

I thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in Foo.

答:
You have four ways to unwind the stack in 'non-exceptional' ways:  next, break, return, and throw.

next will cause the block to return.

break will cause the method that yielded to the block to return.

return will cause the method where the block is defined to return.

throw will traverse up the stack until it finds a catch with a matching symbol, and cause that to return.  This is much like a 'lightweight' exception for non-exceptional situations.

All of them can take a return value that will be returned by whatever they caused to return instead of the value their last expression which they would return normally.

Here are some examples:

def doSomething
  puts "> doSomething"
  yield
  puts "< doSomething"
end

def withNext
  puts "> withNext"
  doSomething do
    puts "> block"
    puts "* NEXT! causes the block to return to doSomething"
    next
    puts "< block"
  end
  puts "< withNext"
end

def withBreak
  puts "> withBreak"
  doSomething do
    puts "> block"
    puts "* BREAK! causes doSomething to return to withBreak"
    break
    puts "< block"
  end
  puts "< withBreak"
end

def withReturn
  puts "> withReturn"
  doSomething do
    puts "> block"
    puts "* RETURN! causes withReturn to return"
    return
    puts "< block"
  end
  puts "< withReturn"
end

def withThrow
  puts "> withThrow"
  catch :label do
    puts "> catch :label"
    doSomething do
      puts "> block 1"
      doSomething do
        puts "> block 2"
        puts "* THROW! causes catch :label to return to withThrow"
        throw :label
        puts "< block 2"
      end
      puts "< block 1"
    end
    puts "< catch :label"
  end
  puts "< withThrow"
end

withNext
puts "* Done"
puts
withBreak
puts "* Done"
puts
withReturn
puts "* Done"
puts
withThrow
puts "* Done"
```
<p>output:</p>
```> withNext
> doSomething
> block
* NEXT! causes the block to return to doSomething
< doSomething
< withNext
* Done

> withBreak
> doSomething
> block
* BREAK! causes doSomething to return to withBreak
< withBreak
* Done

> withReturn
> doSomething
> block
* RETURN! causes withReturn to return
* Done

> withThrow
> catch :label
> doSomething
> block 1
> doSomething
> block 2
* THROW! causes catch :label to return to withThrow
< withThrow
* Done
```

ContentLicense: CC BY-SA 3.0

Title: How to break out from a ruby block?

Body:
Here is Bar#do_things:

class Bar
  def do_things
    Foo.some_method(x) do |x|
      y = x.do_something
      return y_is_bad if y.bad? # how do i tell it to stop and return do_things?
      y.do_something_else
    end
    keep_doing_more_things
  end
end

And here is Foo#some_method:

class Foo
  def self.some_method(targets, &block)
    targets.each do |target|
      begin
        r = yield(target)
      rescue
        failed << target
      end
    end
  end
end

I thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in Foo.

Body:
You have four ways to unwind the stack in 'non-exceptional' ways:  next, break, return, and throw.

next will cause the block to return.

break will cause the method that yielded to the block to return.

return will cause the method where the block is defined to return.

throw will traverse up the stack until it finds a catch with a matching symbol, and cause that to return.  This is much like a 'lightweight' exception for non-exceptional situations.

All of them can take a return value that will be returned by whatever they caused to return instead of the value their last expression which they would return normally.

Here are some examples:

def doSomething
  puts "> doSomething"
  yield
  puts "< doSomething"
end

def withNext
  puts "> withNext"
  doSomething do
    puts "> block"
    puts "* NEXT! causes the block to return to doSomething"
    next
    puts "< block"
  end
  puts "< withNext"
end

def withBreak
  puts "> withBreak"
  doSomething do
    puts "> block"
    puts "* BREAK! causes doSomething to return to withBreak"
    break
    puts "< block"
  end
  puts "< withBreak"
end

def withReturn
  puts "> withReturn"
  doSomething do
    puts "> block"
    puts "* RETURN! causes withReturn to return"
    return
    puts "< block"
  end
  puts "< withReturn"
end

def withThrow
  puts "> withThrow"
  catch :label do
    puts "> catch :label"
    doSomething do
      puts "> block 1"
      doSomething do
        puts "> block 2"
        puts "* THROW! causes catch :label to return to withThrow"
        throw :label
        puts "< block 2"
      end
      puts "< block 1"
    end
    puts "< catch :label"
  end
  puts "< withThrow"
end

withNext
puts "* Done"
puts
withBreak
puts "* Done"
puts
withReturn
puts "* Done"
puts
withThrow
puts "* Done"

output:

> withNext
> doSomething
> block
* NEXT! causes the block to return to doSomething
< doSomething
< withNext
* Done

> withBreak
> doSomething
> block
* BREAK! causes doSomething to return to withBreak
< withBreak
* Done

> withReturn
> doSomething
> block
* RETURN! causes withReturn to return
* Done

> withThrow
> catch :label
> doSomething
> block 1
> doSomething
> block 2
* THROW! causes catch :label to return to withThrow
< withThrow
* Done


问:
Using Classes within an class
Using other classes with a class in Powershell

I have a question about working with classes in powershell, how does one use one class within another? For example I have the class 'SomeClass', I would like to declare that within the other class in the example class below.

Pseudo Code:

```<code>class SomeClass {
    [string] $Status
    [string] $Reason
}

class SomeMasterClass {
    [string] $ServerName
    [string] $FileName
    [SomeClass] $TheClass   # is this correct?
}
</code>```

I am curious of this is the correct way to go about it or is there a better way?

答:
Here you have a reduced simple example of how you can have a class as property of another class, you're actually already doing it just need to add a bit more to it.

Definition

```<code>class SomeOtherClass {
    [string] $Status
    [string] $Reason

    SomeOtherClass () { }
    SomeOtherClass ([string] $Status, [string] $Reason) {
        $this.Status = $Status
        $this.Reason = $Reason
    }
}

class SomeClass {
    [string] $Server
    [string] $File
    [SomeOtherClass] $OtherClass

    SomeMasterClass () { }
    SomeMasterClass ([string] $Server, [string] $File, [SomeOtherClass] $Class) {
        $this.Server     = $Server
        $this.File       = $File
        $this.OtherClass = $Class
    }
}
</code>```

Instantiating

```<code>$testing = [SomeClass]@{
    Server = 'Server01'
    File   = 'SomeFile'
    OtherClass = [SomeOtherClass]@{
        Status = 'OK!'
        Reason = 'Idk'
    }
}
</code>```

Inspecting it's properties

```<code>PS ..\> $testing

Server   File     OtherClass
------   ----     ----------
Server01 SomeFile SomeOtherClass

PS ..\> $testing.OtherClass

Status Reason
------ ------
OK!    Idk
</code>```

Title: Using Classes within an class

Body:
Using other classes with a class in Powershell

I have a question about working with classes in powershell, how does one use one class within another? For example I have the class 'SomeClass', I would like to declare that within the other class in the example class below.

Pseudo Code:

class SomeClass {
    [string] $Status
    [string] $Reason
}

class SomeMasterClass {
    [string] $ServerName
    [string] $FileName
    [SomeClass] $TheClass   # is this correct?
}

I am curious of this is the correct way to go about it or is there a better way?

Body:
Here you have a reduced simple example of how you can have a class as property of another class, you're actually already doing it just need to add a bit more to it.

Definition

class SomeOtherClass {
    [string] $Status
    [string] $Reason

    SomeOtherClass () { }
    SomeOtherClass ([string] $Status, [string] $Reason) {
        $this.Status = $Status
        $this.Reason = $Reason
    }
}

class SomeClass {
    [string] $Server
    [string] $File
    [SomeOtherClass] $OtherClass

    SomeMasterClass () { }
    SomeMasterClass ([string] $Server, [string] $File, [SomeOtherClass] $Class) {
        $this.Server     = $Server
        $this.File       = $File
        $this.OtherClass = $Class
    }
}

Instantiating

$testing = [SomeClass]@{
    Server = 'Server01'
    File   = 'SomeFile'
    OtherClass = [SomeOtherClass]@{
        Status = 'OK!'
        Reason = 'Idk'
    }
}

Inspecting it's properties

PS ..\> $testing

Server   File     OtherClass
------   ----     ----------
Server01 SomeFile SomeOtherClass

PS ..\> $testing.OtherClass

Status Reason
------ ------
OK!    Idk


问:
Diff using filenames only
Is it possible using any sort of diff utility to diff based on filename only, ignoring all folders and subfolders?

So if I have

```<code>/folder_1/a/1243.txt
</code>```

and

```<code>/folder_2/b/1243.txt
</code>```

or

```<code>/folder_2/1234.txt
</code>```

It would match the files when doing a diff between folder_1 and folder_2?

答:
```<code>diff -r directory another
</code>```

compares the files in directories and outputs if they differs, or is missing from either of the directory.

ContentLicense: CC BY-SA 2.5

Title: Diff using filenames only

Body:
Is it possible using any sort of diff utility to diff based on filename only, ignoring all folders and subfolders?

So if I have

/folder_1/a/1243.txt

and

/folder_2/b/1243.txt

or

/folder_2/1234.txt

It would match the files when doing a diff between folder_1 and folder_2?

Body:
diff -r directory another

compares the files in directories and outputs if they differs, or is missing from either of the directory.


问:
how to Iterate through data and pass them into a component in reactjs
I already created a menu button which display some default value, shows below.

And I have a table which have the data I need,

```<code>return (
                        <UitkTableRow {...row.getRowProps()}>
                            {row.cells.map((cell) => {
                                return <UitkTableCell {...cell.getCellProps()}>{cell.render('Cell')}</UitkTableCell>
                            })}

                            {row.cells.map((cell) => {
                                if(cell.column.Header == "Notes"){
                                    console.log(cell)//print result shows below

                                    return  <div style={{margin:'10px 0px 0px 0px'}}>
                                        <NotesSelection />
                                    </div>
                                }
                            })}

                        </UitkTableRow>
                    )
</code>```

I want to put the value, "DELETE COMMENT 1" in my menu list, how can I do this?

I tried something like this, loop through the cell, but got error "cell.map" is not a function

```<code>{cell.map(c => {
                                                return (
                                                    <div>display</div>
                                                )
                                            })}
</code>```

Edit:

```<code>const {value} = cell
                                    {
                                        value.map(c => {
                                            return  <div>
                                                <NotesSelection />
                                            </div>
                                        })
                                    }
</code>```
```<code>interface NotesSelectionProps {
  selectNotes(note:string): string;
}

class NotesSelection extends React.Component<NotesSelectionProps, { show: boolean, noteS: string, value: string }> {
  constructor(props: any) {
    super(props);
    this.state = {
      show: false,
      noteS: "",
      value: "",
    };
    note = notes.notes[0].name
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e: any) {
    const previousState = this.state['show'];
    this.setState({
      show: !previousState,
      noteS: note,
      value: "",
    });
    arrowState = previousState ? " ˅" : " ˄"
  }

  onMenuItemClick(name: string) {
    note = name
    this.setState({
      show: false,
      noteS: note,
      value: "",
    });

    this.props.selectNotes(note)
    arrowState = " ˅"
    return;
  }

  render() {
    var name = this.props
    var noes: any = []
    notes.notes.forEach(element => {
      var note = {
        className: 'uitk-list-item',
        label: element.name,
        onClick:  () => this.onMenuItemClick(element.name),
        typeAnchor: true,
        target: "_blank"
      }
      noes.push(note)
    });

    noes.push(value)
    var buttonStyle = {
      padding:'5px',
      width:'170px',
      display:'flex',
      justifyContent:'space-between',
      background:'white',
      borderRadius: "10px",
      border:'1px solid rgba(0,0,0,.1)',
      fontSize: '14px',
      boxShadow: '0px 2px 2px rgb(0 0 0 / 10%)'
    };

    return (
        <><div>

          <UitkMenu
              id="show10"
              isOpen={this.state.show}
              onTriggerClick={this.handleClick}
          >
            <UitkMenuTrigger >
              <button style={buttonStyle}>
                <div className="notes">
                  {note}
                </div>
                <div className="arrowState">
                  {arrowState}
                </div>
              </button>
            </UitkMenuTrigger>
            <UitkMenuContainer position={PositionType.LEFT} width={200}>
              <UitkMenuList items={noes} />
            </UitkMenuContainer>

          </UitkMenu>
        </div>
        </>
    )
  }
}
</code>```

答:
Since you need to modify the menu list (NotesSelection) pass the value to that component and render it there.

NotesSelection component

```<code>interface NotesSelectionProps {
  selectNotes(note:string): string;
}

class NotesSelection extends React.Component<NotesSelectionProps, { show: boolean, noteS: string, value: string }> {
  constructor(props: any) {
    super(props);
    this.state = {
      show: false,
      noteS: ""
    };
    note = notes.notes[0].name
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e: any) {
    const previousState = this.state['show'];
    this.setState({
      show: !previousState,
      noteS: note
    });
    arrowState = previousState ? " ˅" : " ˄"
  }

  onMenuItemClick(name: string) {
    note = name
    this.setState({
      show: false,
      noteS: note
    });

    this.props.selectNotes(note)
    arrowState = " ˅"
    return;
  }

  render() {
    var name = this.props
    var noes: any = []
    notes.notes.forEach(element => {
      var note = {
        className: 'uitk-list-item',
        label: element.name,
        onClick:  () => this.onMenuItemClick(element.name),
        typeAnchor: true,
        target: "_blank"
      }
      noes.push(note)
    });

    noes.push(value)

    var buttonStyle = {
      padding:'5px',
      width:'170px',
      display:'flex',
      justifyContent:'space-between',
      background:'white',
      borderRadius: "10px",
      border:'1px solid rgba(0,0,0,.1)',
      fontSize: '14px',
      boxShadow: '0px 2px 2px rgb(0 0 0 / 10%)'
    };

    return (
        <><div>

          <UitkMenu
              id="show10"
              isOpen={this.state.show}
              onTriggerClick={this.handleClick}
          >
            <UitkMenuTrigger >
              <button style={buttonStyle}>
                <div className="notes">
                  {note}
                </div>
                <div className="arrowState">
                  {arrowState}
                </div>
              </button>
            </UitkMenuTrigger>
            <UitkMenuContainer position={PositionType.LEFT} width={200}>
              <UitkMenuList items={noes} />
            </UitkMenuContainer>

          </UitkMenu>
        </div>
        </>
    )
  }
}
</code>```

Table component

```<code>return (
                        <UitkTableRow {...row.getRowProps()}>
                            {row.cells.map((cell) => {
                                return <UitkTableCell {...cell.getCellProps()}>{cell.render('Cell')}</UitkTableCell>
                            })}

                            {row.cells.map((cell) => {
                                if(cell.column.Header == "Notes"){
                                    console.log(cell)//print result shows below

                                    return  <div style={{margin:'10px 0px 0px 0px'}}>
                                        <NotesSelection value={cell.value} />
                                    </div>
                                }
                            })}

                        </UitkTableRow>
                    )
</code>```

Body:
I already created a menu button which display some default value, shows below.

And I have a table which have the data I need,

return (
                        <UitkTableRow {...row.getRowProps()}>
                            {row.cells.map((cell) => {
                                return <UitkTableCell {...cell.getCellProps()}>{cell.render('Cell')}</UitkTableCell>
                            })}

                            {row.cells.map((cell) => {
                                if(cell.column.Header == "Notes"){
                                    console.log(cell)//print result shows below

                                    return

                                        <NotesSelection />

                                }
                            })}

                        </UitkTableRow>
                    )

I want to put the value, "DELETE COMMENT 1" in my menu list, how can I do this?

I tried something like this, loop through the cell, but got error "cell.map" is not a function

{cell.map(c => {
                                                return (

display

                                                )
                                            })}

Edit:

const {value} = cell
                                    {
                                        value.map(c => {
                                            return

                                                <NotesSelection />

                                        })
                                    }

interface NotesSelectionProps {
  selectNotes(note:string): string;
}

class NotesSelection extends React.Component<NotesSelectionProps, { show: boolean, noteS: string, value: string }> {
  constructor(props: any) {
    super(props);
    this.state = {
      show: false,
      noteS: "",
      value: "",
    };
    note = notes.notes[0].name
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e: any) {
    const previousState = this.state['show'];
    this.setState({
      show: !previousState,
      noteS: note,
      value: "",
    });
    arrowState = previousState ? " ˅" : " ˄"
  }

  onMenuItemClick(name: string) {
    note = name
    this.setState({
      show: false,
      noteS: note,
      value: "",
    });

    this.props.selectNotes(note)
    arrowState = " ˅"
    return;
  }

  render() {
    var name = this.props
    var noes: any = []
    notes.notes.forEach(element => {
      var note = {
        className: 'uitk-list-item',
        label: element.name,
        onClick:  () => this.onMenuItemClick(element.name),
        typeAnchor: true,
        target: "_blank"
      }
      noes.push(note)
    });

    noes.push(value)
    var buttonStyle = {
      padding:'5px',
      width:'170px',
      display:'flex',
      justifyContent:'space-between',
      background:'white',
      borderRadius: "10px",
      border:'1px solid rgba(0,0,0,.1)',
      fontSize: '14px',
      boxShadow: '0px 2px 2px rgb(0 0 0 / 10%)'
    };

    return (
        <>

          <UitkMenu
              id="show10"
              isOpen={this.state.show}
              onTriggerClick={this.handleClick}
          >
            <UitkMenuTrigger >
              <button style={buttonStyle}>

                  {note}

                  {arrowState}

              </button>
            </UitkMenuTrigger>
            <UitkMenuContainer position={PositionType.LEFT} width={200}>
              <UitkMenuList items={noes} />
            </UitkMenuContainer>

          </UitkMenu>

        </>
    )
  }
}

Body:
Since you need to modify the menu list (NotesSelection) pass the value to that component and render it there.

NotesSelection component

interface NotesSelectionProps {
  selectNotes(note:string): string;
}

class NotesSelection extends React.Component<NotesSelectionProps, { show: boolean, noteS: string, value: string }> {
  constructor(props: any) {
    super(props);
    this.state = {
      show: false,
      noteS: ""
    };
    note = notes.notes[0].name
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e: any) {
    const previousState = this.state['show'];
    this.setState({
      show: !previousState,
      noteS: note
    });
    arrowState = previousState ? " ˅" : " ˄"
  }

  onMenuItemClick(name: string) {
    note = name
    this.setState({
      show: false,
      noteS: note
    });

    this.props.selectNotes(note)
    arrowState = " ˅"
    return;
  }

  render() {
    var name = this.props
    var noes: any = []
    notes.notes.forEach(element => {
      var note = {
        className: 'uitk-list-item',
        label: element.name,
        onClick:  () => this.onMenuItemClick(element.name),
        typeAnchor: true,
        target: "_blank"
      }
      noes.push(note)
    });

    noes.push(value)

    var buttonStyle = {
      padding:'5px',
      width:'170px',
      display:'flex',
      justifyContent:'space-between',
      background:'white',
      borderRadius: "10px",
      border:'1px solid rgba(0,0,0,.1)',
      fontSize: '14px',
      boxShadow: '0px 2px 2px rgb(0 0 0 / 10%)'
    };

    return (
        <><div>

          <UitkMenu
              id="show10"
              isOpen={this.state.show}
              onTriggerClick={this.handleClick}
          >
            <UitkMenuTrigger >
              <button style={buttonStyle}>
                <div className="notes">
                  {note}
                </div>
                <div className="arrowState">
                  {arrowState}
                </div>
              </button>
            </UitkMenuTrigger>
            <UitkMenuContainer position={PositionType.LEFT} width={200}>
              <UitkMenuList items={noes} />
            </UitkMenuContainer>

          </UitkMenu>
        </div>
        </>
    )
  }
}

Table component

return (
                        <UitkTableRow {...row.getRowProps()}>
                            {row.cells.map((cell) => {
                                return <UitkTableCell {...cell.getCellProps()}>{cell.render('Cell')}</UitkTableCell>
                            })}

                            {row.cells.map((cell) => {
                                if(cell.column.Header == "Notes"){
                                    console.log(cell)//print result shows below

                                    return  <div style={{margin:'10px 0px 0px 0px'}}>
                                        <NotesSelection value={cell.value} />
                                    </div>
                                }
                            })}

                        </UitkTableRow>
                    )


问:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

```<code>sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "
</code>```

or should I have set sql_statement to "" and then joined each piece?
Thanks.

答:
@robert has a very good point of using format() for a string.
Another way of concatenating strings is:

```<code>s = ('select count(*)'
     'from ept_inv e'
     'where e.ept_type = {device_type}'
     'and e.inv_id = {endpoint_id};')

sql_statement = sql_statement_format.format(
                    device_type=in_row[cs.DeviceType],
                    endpoint_id=in_row[cs.EndpointId])
</code>```

In fact, in Python, using parenthesis like this is preferred to truncating lines via \.

Title: Proper CPython String Concatenation

Body:
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "

or should I have set sql_statement to "" and then joined each piece?
Thanks.

Body:
@robert has a very good point of using format() for a string.
Another way of concatenating strings is:

s = ('select count(*)'
     'from ept_inv e'
     'where e.ept_type = {device_type}'
     'and e.inv_id = {endpoint_id};')

sql_statement = sql_statement_format.format(
                    device_type=in_row[cs.DeviceType],
                    endpoint_id=in_row[cs.EndpointId])

In fact, in Python, using parenthesis like this is preferred to truncating lines via \.


问:
Default credentials can not be used to assume new style deployment roles
Following pipelines readme to set up a deployment pipeline, I ran

```<code>$ env CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap \
    --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \
    aws://[ACCOUNT_ID]/us-west-2
</code>```

to create the necessary roles. I would assume the roles would automatically add sts assume role permissions from my account principle. However, when I run cdk deploy I get the following warning

current credentials could not be used to assume
'arn:aws:iam::[ACCOUNT_ID]:role/cdk-hnb659fds-file-publishing-role-[ACCOUNT_ID]-us-west-2',
but are for the right account. Proceeding anyway.

I have root credentials in ~/.aws/credentials.

Looking at the deploy role policy, I don't see any sts permissions. What am I missing?

答:
I ran into a similar error. The critical part of my error was

```<code>failed: Error: SSM parameter /cdk-bootstrap/<>/version not found.
</code>```

I had to re-run using the new bootstrap method that creates the SSM parameter. To run the new bootstrap method first set CDK_NEW_BOOTSTRAP via export CDK_NEW_BOOTSTRAP=1

Body:
Following pipelines readme to set up a deployment pipeline, I ran

$ env CDK_NEW_BOOTSTRAP=1 npx cdk bootstrap \
    --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \
    aws://[ACCOUNT_ID]/us-west-2

to create the necessary roles. I would assume the roles would automatically add sts assume role permissions from my account principle. However, when I run cdk deploy I get the following warning

current credentials could not be used to assume
'arn:aws:iam::[ACCOUNT_ID]:role/cdk-hnb659fds-file-publishing-role-[ACCOUNT_ID]-us-west-2',
but are for the right account. Proceeding anyway.

I have root credentials in ~/.aws/credentials.

Looking at the deploy role policy, I don't see any sts permissions. What am I missing?

Body:
I ran into a similar error. The critical part of my error was

failed: Error: SSM parameter /cdk-bootstrap/<>/version not found.

I had to re-run using the new bootstrap method that creates the SSM parameter. To run the new bootstrap method first set CDK_NEW_BOOTSTRAP via export CDK_NEW_BOOTSTRAP=1


问:
Tailing few lines from huge logs of kubectl logs -f
kubectl logs -f pod shows all logs from the beginning and it becomes a problem when the log is huge and we have to wait for a few minutes to get the last log. Its become more worst when connecting remotely. Is there a way that we can tail the logs for the last 100 lines of logs and follow them?

答:
You can ues this way to get the first 10 lines</p>
```<code>kubectl logs my-pod-name  -n my-ns | head -n 10
</code>```

Body:
You can ues this way to get the first 10 lines

kubectl logs my-pod-name  -n my-ns | head -n 10


问:
Docker Website using Node and Yarn wont let we access website
I just started writing docker files and am trying to start a website using docker but every time I run the file I cant access the website.
dockerfile
dockerlog</p>

答:
I actually figured it out when running the docker run command adding the
--network="host" flag let me connect to the website</p>


问:
apperyio, ionic5, input[type=file], load image asset to the image
I'm trying to load an image from the input[type=file] to the image on a page.
Is it possible to do it without uploading a file to the database?

More info about what i need

答:
Here is a solution for this, i've got with a help of Ravi(thanks to him).

1 Create a "fileURL" variable.
How to do it

2 On image set "src" attribute with value of "{{fileURL}}".
How to do it

3 Click on "file" and add "change" evet -> run typescript, with code  How to do it:

//event.target.firstChild - is an input.
let file = event.target.firstChild.files[0];

if(file)
    this.fileURL = URL.createObjectURL(file);```


问:
Problems with ASP.Net State Service
We have an ASP.Net 2.0 web application running in a web farm which is using the ASP.Net State service to store sessions.

We have been having problmes with the service intermittently and have changed a few things such as the machineKey in the machine.config.

My actual question is around the monitoring of the state service service. We have all 4 available performance counters running on the server that hosts the service and as yet we have not seen a single session time out. We have also seen the number of active sessions slowly rise over a period of time, but never become less.

Does the state service recognise when sessions time out? Is there something we should be doing manually?

Edit: We have given up on the state service and gone with SQL server sessions.

To answer the questions below, it seems that sessions go up forever until the service falls over and it is very doubtful that any oen threads are linked to the state server. This is a fairly basic web app at the end of the day.

It seems from the reading I am doing that anumber of other people have experienced similar things, but there seems to be a general lack of common sense and knowledge in any responses flying about.

MS seem to have almost no documentation on this topic.

答:
I am sure this will get modded down, but I have to say it.

If you are having issues with the state server, then there is likely an error somewhere in your web application.  Charles' comment above seems like good places to start checking, but somewhere there is a life cycle issue.

Go back over the code and check your assumptions.  Take a new computer, visit your website (create a session) and let it sit for an hour.  If your session is still alive, then something is wrong.  Create a new web application that just has a single page reporting the the age of the current session and try the same thing.  You should find that after an hour (default is 20 minutes) the session is no longer valid.  Now you have a system that is working as expect and one that is not, both using the same session server, so you can rule that out as the problem, now start going through code/configuration and see where you could be keeping it alive (or preventing the time-out).

Here, by the way, is a 'valid' session config.  If you don't have your looking something like this, you have likely found your issue:

```<code><sessionState
   mode="StateServer"
   stateConnectionString="tcpip=10.1.1.1:55455"
   cookieless="false"
   timeout="20" />
</code>```

Also make sure you are not overriding your web.config with your machine.config to have a longer timeout.

OwnerDisplayName: Blatfrig

Title: Problems with ASP.Net State Service

LastEditorDisplayName: Blatfrig

Body:
I am sure this will get modded down, but I have to say it.

If you are having issues with the state server, then there is likely an error somewhere in your web application.  Charles' comment above seems like good places to start checking, but somewhere there is a life cycle issue.

Go back over the code and check your assumptions.  Take a new computer, visit your website (create a session) and let it sit for an hour.  If your session is still alive, then something is wrong.  Create a new web application that just has a single page reporting the the age of the current session and try the same thing.  You should find that after an hour (default is 20 minutes) the session is no longer valid.  Now you have a system that is working as expect and one that is not, both using the same session server, so you can rule that out as the problem, now start going through code/configuration and see where you could be keeping it alive (or preventing the time-out).

Here, by the way, is a 'valid' session config.  If you don't have your looking something like this, you have likely found your issue:

<sessionState
   mode="StateServer"
   stateConnectionString="tcpip=10.1.1.1:55455"
   cookieless="false"
   timeout="20" />

Also make sure you are not overriding your web.config with your machine.config to have a longer timeout.

OwnerDisplayName: JasonRShaver


问:
Bootstrap Select jump to typed in letters
Hi Im using Bootstrap Select for a state dropdown and would like to implement the functionality where if a user starts typing "c" then it would drop them down to "california" (as an example). This is already out of the box for plugin but I would like to change where if the user "co" then it would drop them down to "Colorado", instead it takes them first to "california" after typing the "c" and then to "ohio" after typing the "o". Is there any way to accomplish this with the bootstrap select plugin?

FYI The plugin is pretty heavily incorporated into the site at the moment and changing to another plugin wouldnt really be an option for me.

Example:
http://jsfiddle.net/2a9xp/513/

$('.selectpicker').selectpicker({size:10});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

<select class="selectpicker">
  <option>California</option>
  <option>Colorado</option>
  <option>Connecticut</option>
  <option>Kansas</option>
  <option>Kentucky</option>
  <option>Ohio</option>
  <option>Oklahoma</option>
  <option>Oregon</option>
</select></code>```

答: Is there any parent component in your project? in my case, this problem causes by select.min.js load every time i open component contains select box. So i move this lib to biggest component, make sure that this lib load only one time.</p>

Body:
Hi Im using Bootstrap Select for a state dropdown and would like to implement the functionality where if a user starts typing "c" then it would drop them down to "california" (as an example). This is already out of the box for plugin but I would like to change where if the user "co" then it would drop them down to "Colorado", instead it takes them first to "california" after typing the "c" and then to "ohio" after typing the "o". Is there any way to accomplish this with the bootstrap select plugin?

FYI The plugin is pretty heavily incorporated into the site at the moment and changing to another plugin wouldnt really be an option for me.

Example:
http://jsfiddle.net/2a9xp/513/

$('.selectpicker').selectpicker({size:10});

<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

<select class="selectpicker">
  <option>California</option>
  <option>Colorado</option>
  <option>Connecticut</option>
  <option>Kansas</option>
  <option>Kentucky</option>
  <option>Ohio</option>
  <option>Oklahoma</option>
  <option>Oregon</option>
</select>


问:
I am a beginner and I want to know how to make a an action last a sertain time or how to end one and start loading another. C#
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StartGame : MonoBehaviour
{
    public void Load12AM()
    {
        SceneManager.LoadScene("12AM");
    }

    IEnumerator officeLoad()
    {
        yield return new WaitForSeconds(4f);
        SceneManager.LoadScene("Office");
    }
}
</code>```

I don t know how to make the code work because, it just stays on the first scene.

答:
I see you have written something called "officeLoad"!
If you are trying to call it, try writing it like this:

```<code>StartCoroutine(officeLoad());
</code>```

The concurrent process is special, so you can't call it directly, you have to use "StartCoroutine" like I did!
(^∀^)

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StartGame : MonoBehaviour
{
    public void Load12AM()
    {
        SceneManager.LoadScene("12AM");
    }

    IEnumerator officeLoad()
    {
        yield return new WaitForSeconds(4f);
        SceneManager.LoadScene("Office");
    }
}

I don t know how to make the code work because, it just stays on the first scene.

Body:
I see you have written something called "officeLoad"!
If you are trying to call it, try writing it like this:

StartCoroutine(officeLoad());

The concurrent process is special, so you can't call it directly, you have to use "StartCoroutine" like I did!
(^∀^)


问:
How can we share OAuth token between backend and frontend
I have SPA app, backend is ruby on rails and frontend is React. Now I am developing new authentication feature; login with GitHub account with omuniauth gem.

However after authorization with GitHub we need to redirect to backend server as that is the server which is sending authorization request to GitHub authentication server. That means my frontend cannot receive response from GitHub which contains auth information such as user name, token, etc.

I understand we can redirect to frontend URL through backend API, but even in that case I believe auth information from GitHub is not passed to frontend.

Is there any way to share the auth info from GitHub after oauth2 authorization? Any help would be really appreciated. Thank you so much in advance!

答:
For your use case (which is implicit grant flow) I think that's not possible, common pattern to solve this is token handler pattern

Basically, after your backend receive callback from the github & exchange it with access token, you can issue a cookie or token (not oauth token) to the frontend. This cookie is associated with the github's access token.

Later, after you redirected back to the frontend, you need to request the github's user profile proxied via backend

If you want to be able to access github api directly from the frontend, consider using client credential flow (typically used for SPA, without backend)


答: Dividing by N-1, as in R, gives an unbiased estimate of the variance; generally speaking one desires an unbiased estimate. The Numpy implementation is incorrect.</p>

Title: Output values differ between R and Python?

Body:
Perhaps I am doing something wrong while z-normalizing my array. Can someone take a look at this and suggest what's going on?

In R:

> data <- c(2.02, 2.33, 2.99, 6.85, 9.20, 8.80, 7.50, 6.00, 5.85, 3.85, 4.85, 3.85, 2.22, 1.45, 1.34)
> data.mean <- mean(data)
> data.sd <- sqrt(var(data))
> data.norm <- (data - data.mean) / data.sd
> print(data.norm)
 [1] -0.9796808 -0.8622706 -0.6123005  0.8496459  1.7396910  1.5881940  1.0958286  0.5277147  0.4709033 -0.2865819
[11]  0.0921607 -0.2865819 -0.9039323 -1.1955641 -1.2372258

In Python using numpy:

>>> import string
>>> import numpy as np
>>> from scipy.stats import norm
>>> data = np.array([np.array([2.02, 2.33, 2.99, 6.85, 9.20, 8.80, 7.50, 6.00, 5.85, 3.85, 4.85, 3.85, 2.22, 1.45, 1.34])])
>>> data -= np.split(np.mean(data, axis=1), data.shape[0])
>>> data *= np.split(1.0/data.std(axis=1), data.shape[0])
>>> print data

[[-1.01406602 -0.89253491 -0.63379126  0.87946705  1.80075126  1.64393692
   1.13429034  0.54623659  0.48743122 -0.29664045  0.09539539 -0.29664045
  -0.93565885 -1.23752644 -1.28065039]]

Am I using numpy incorrectly?


问:
I am not able to achieve the blur effect in swift
I am not able to achieve the appropriate blur effect as per design in swift.

My code to add blur effect -

```<code>func addBlur() {
    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.alpha = 0.75
    imgView.alpha = 0.75
    blurredEffectView.frame = imgView.bounds
    imgView.subviews.forEach {
        $0.removeFromSuperview()
    }
    imgView.addSubview(blurredEffectView)
    imgView.bringSubviewToFront(blurredEffectView)
}
</code>```

Code to remove blur effect. -

```<code>func removeBlur() {
    for subview in imgView.subviews {
        if subview is UIVisualEffectView {
            imgView.alpha = 1
            subview.removeFromSuperview()
        }
    }
}
</code>```

Below is the design -

Desin blur effect

The one I achieve by my code -

Achieved screenshot

答:
Apple does not recommend to change the alpha property of a UIVisualEffectView and is probably why you are not seeing the blur.

Setting the Correct Alpha Value

When using the UIVisualEffectView
class, avoid alpha values that are less than 1. Creating views that
are partially transparent causes the system to combine the view and
all the associated subviews during an offscreen render pass.
UIVisualEffectView objects need to be combined as part of the content
they are layered on top of in order to look correct. Setting the alpha
to less than 1 on the visual effect view or any of its superviews
causes many effects to

So remove this line blurredEffectView.alpha = 0.75

If you want to change the density / brightness of the blur, experiment with different styles UIBlurEffect has to offer and use the one that comes closest to your needs.

Update

If you do not get the desired results from UIVisualEffectView, you might look at CIFilter which might give you more options with more control on the properties.

Here is an example of CIFilter's gaussian blur and if you scroll down you can see some other options

Body:
I am not able to achieve the appropriate blur effect as per design in swift.

My code to add blur effect -

func addBlur() {
    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.alpha = 0.75
    imgView.alpha = 0.75
    blurredEffectView.frame = imgView.bounds
    imgView.subviews.forEach {
        $0.removeFromSuperview()
    }
    imgView.addSubview(blurredEffectView)
    imgView.bringSubviewToFront(blurredEffectView)
}

Code to remove blur effect. -

func removeBlur() {
    for subview in imgView.subviews {
        if subview is UIVisualEffectView {
            imgView.alpha = 1
            subview.removeFromSuperview()
        }
    }
}

Below is the design -

Desin blur effect

The one I achieve by my code -

Achieved screenshot


问:
How do I place variables inside of a triple-quoted string literal?

data = """
{
  "sender": "I want a variable here",
  "memo": "and here another variable",
  "amount": another variable here
}
"""
```

I've tried using f in front of the string, and several other methods, but this is keeping me hung up.

答:
Don't construct JSON strings by hand as there are many intricacies of the JSON spec and your method is prone to errors. Instead, construct a dictionary first:

```<code>my_dict = {
    "sender": my_sender_variable,
    "memo": my_memo_variable,
    "amount": my_amount_variable
    }
</code>```

then use the json module to convert it to a string:

```<code>my_json = json.dumps(my_dict, indent=4)
</code>```

Body:
data = """
{
  "sender": "I want a variable here",
  "memo": "and here another variable",
  "amount": another variable here
}
"""

I've tried using f in front of the string, and several other methods, but this is keeping me hung up.

Body:
Don't construct JSON strings by hand as there are many intricacies of the JSON spec and your method is prone to errors. Instead, construct a dictionary first:

my_dict = {
    "sender": my_sender_variable,
    "memo": my_memo_variable,
    "amount": my_amount_variable
    }

then use the json module to convert it to a string:

my_json = json.dumps(my_dict, indent=4)


问:
Generate array with foreach PDO / MySQL
I am doing a SELECT from MySQL that brings me a different number of rows for the same column. Then I:

foreach to create an array

merge the resulting arraywith another array

echo using json_encode

My problem: I need to remove the extra array and the keys
when generating my result. I tried different things but those didn't worked, could you tell me what I am doing wrong?

Here's my code:

```<code>    $dados2 = [
        'id' => $_POST['id_profissional']
    ];

    $sql2 = "
    SELECT nome
    FROM areas_de_atuacao_dos_advogados_e_escritorios
    LEFT JOIN areas_de_atuacao ON areas_de_atuacao_dos_advogados_e_escritorios.id_areas_de_atuacao = areas_de_atuacao.id
    WHERE id_advogados_e_escritorios=:id
    ORDER BY principal DESC
    ";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute($dados2);
    $areas_de_atuacao = $stmt2->fetchAll();

    $i = '0';
    foreach ($areas_de_atuacao as $row) {

        $aAreas_de_atuacao [] = array(
            'area_de_atuacao_'.$i   =>  $row["nome"]
        );
        $i++;

    }
</code>```

With this output:

```<code>Array ( [0] => Array ( [area_de_atuacao_0] => Direito Civil ) [1] => Array ( [area_de_atuacao_1] => Direito Criminal ) [2] => Array ( [area_de_atuacao_2] => Direito Empresarial ) [3] => Array ( [area_de_atuacao_3] => Direito de Família ) [4] => Array ( [area_de_atuacao_4] => Direito das Sucessões ) [5] => Array ( [area_de_atuacao_5] => Direito do Trabalho ) )
</code>```

But this is my desire output:

```<code>Array ( [area_de_atuacao_0] => Direito Civil [area_de_atuacao_1] => Direito Criminal [area_de_atuacao_2] => Direito Empresarial [area_de_atuacao_3] => Direito de Família [area_de_atuacao_4] => Direito das Sucessões [area_de_atuacao_5] => Direito do Trabalho )
</code>```

Thank you for your time ;)

答:
```<code>foreach ($areas_de_atuacao as $i => $row) {
    $aAreas_de_atuacao ['area_de_atuacao_'.$i] = $row["nome"];
}
</code>```

Title: Generate array with foreach PDO / MySQL

Body:
I am doing a SELECT from MySQL that brings me a different number of rows for the same column. Then I:

foreach to create an array

merge the resulting arraywith another array

echo using json_encode

My problem: I need to remove the extra array and the keys
when generating my result. I tried different things but those didn't worked, could you tell me what I am doing wrong?

Here's my code:

    $dados2 = [
        'id' => $_POST['id_profissional']
    ];

    $sql2 = "
    SELECT nome
    FROM areas_de_atuacao_dos_advogados_e_escritorios
    LEFT JOIN areas_de_atuacao ON areas_de_atuacao_dos_advogados_e_escritorios.id_areas_de_atuacao = areas_de_atuacao.id
    WHERE id_advogados_e_escritorios=:id
    ORDER BY principal DESC
    ";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute($dados2);
    $areas_de_atuacao = $stmt2->fetchAll();

    $i = '0';
    foreach ($areas_de_atuacao as $row) {

        $aAreas_de_atuacao [] = array(
            'area_de_atuacao_'.$i   =>  $row["nome"]
        );
        $i++;

    }

With this output:

Array ( [0] => Array ( [area_de_atuacao_0] => Direito Civil ) [1] => Array ( [area_de_atuacao_1] => Direito Criminal ) [2] => Array ( [area_de_atuacao_2] => Direito Empresarial ) [3] => Array ( [area_de_atuacao_3] => Direito de Família ) [4] => Array ( [area_de_atuacao_4] => Direito das Sucessões ) [5] => Array ( [area_de_atuacao_5] => Direito do Trabalho ) )

But this is my desire output:

Array ( [area_de_atuacao_0] => Direito Civil [area_de_atuacao_1] => Direito Criminal [area_de_atuacao_2] => Direito Empresarial [area_de_atuacao_3] => Direito de Família [area_de_atuacao_4] => Direito das Sucessões [area_de_atuacao_5] => Direito do Trabalho )

Thank you for your time ;)


问:
Leave-one out means by group in R
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:</p>
```<code>foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]
</code>```

Title: Leave-one out means by group in R

Body:
Imagine a table of individuals over time in different firms. I'm trying to compute for every individual the mean wage of their co-workers (ie the mean wage in their firm at time t excluding them). I have a working code using data.table in R which works, but I'm wondering whether there is a better, more efficient of doing this:

foo <- data.table(
  i = rep(1:6, each = 2),
  t = rep(1:2, 6),
  f = rep(1:2, each = 6),
  w = 1:12
)

foo[, x := mean(foo[t == .BY$t & f == foo[i == .BY$i & t == .BY$t]$f & i != .BY$i]$w), by = .(i, t)]

Body:
I don't know if this is any easier to read, but here's an approach with pmap:

library(dplyr); library(purrr)
foo %>%
   mutate(x = pmap_dbl(cur_data(),~ cur_data() %>%
                                      filter(i != ..1, t == ..2, f == ..3) %>%
                                      pull(w) %>%
                                      mean))
#    i t f  w  x
# 1: 1 1 1  1  4
# 2: 1 2 1  2  5
# 3: 2 1 1  3  3
# 4: 2 2 1  4  4
# 5: 3 1 1  5  2
# 6: 3 2 1  6  3
# 7: 4 1 2  7 10
# 8: 4 2 2  8 11
# 9: 5 1 2  9  9
#10: 5 2 2 10 10
#11: 6 1 2 11  8
#12: 6 2 2 12  9


问:
How to incorporate a linearlaout xml file in a compose file?
I'm trying to use Robinhood Spark in my app but my entire UI is built using jetpack compose. I'm going through these docs but it's only mentioned how you can use XML resource files like String, Dimensions, Colors, Images, Vector drawbles, Icons, and Fonts. I don't know which one Spark falls under. Looking at the XML code it's a LinearLayout but I can't see how that falls under any of the resource types I've mentioned prior. So for now I'm going through non-compose documentations to see if there is some kind of class or method I can use but would appreciate some feedback and help.</p>

答:
It is as nglauber mentioned, but you would need to define layout parameters that will fit into your compose view as well.
More about it https://foso.github.io/Jetpack-Compose-Playground/viewinterop/androidview/</p>
```<code>        AndroidView(factory = { ctx ->
            val view = LayoutInflater.from(ctx)
                .inflate(R.layout.activity_sample, null, false)
                .apply {
                    layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
                }
            // Use your view as usual...
            view
        }, update = {
           // here update your view or get element from it and update
        })
</code>```

Body:
It is as nglauber mentioned, but you would need to define layout parameters that will fit into your compose view as well.
More about it https://foso.github.io/Jetpack-Compose-Playground/viewinterop/androidview/

        AndroidView(factory = { ctx ->
            val view = LayoutInflater.from(ctx)
                .inflate(R.layout.activity_sample, null, false)
                .apply {
                    layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
                }
            // Use your view as usual...
            view
        }, update = {
           // here update your view or get element from it and update
        })