问:
Converting Java 1.8 lambdas to Java 1.7 on gs-uploading-files Spring Boot example
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

```<code>@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

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

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}
</code>```

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

```<code>import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}
</code>```

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

```<code>@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}
</code>```

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

```<code>import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}
</code>```

package java.util.stream does not exist

答:
Bulltorious, I'm sorry for your bounty but you really have only very few choices. Stream API was added only in Java 8 and thus does not exist in the Java 7. You can work-around lambda-related issues by manually writting anonymous classes or  even almost automatically (see Retrolambda). However with the Stream API you only have two choices:

Backport Stream API to Java 7 manually. Or use someone else attempt to backport such as streamsupport project on SourceForge (or copy on GitHub)

Get rid of the Stream API and use older Java 7 classes.

Update (replace Files.walk)

In case your Files.walk is the only place you use Java-8-specific API, you can replace it with Java 7 API relatively easily:

interface PathNameMapper
{
    String mapPath(Path path);
}

List<String> loadAll(PathNameMapper mapper)
{
    try
    {
        List<String> result = new ArrayList<>();

        Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
            {
                if (!rootLocation.equals(file))
                {
                    result.add(mapper.mapPath(rootLocation.relativize(file)));
                }
                return FileVisitResult.CONTINUE;
            }
        });

        return result;
    }
    catch (IOException e)
    {
        throw new StorageException("Failed to read stored files", e);
    }
}
```

<p>and then your <code>listUploadedFiles</code> would become something like</p>

<pre class="lang-java prettyprint-override"><code>@GetMapping ("/")
public String listUploadedFiles(Model model) throws IOException
{

    model.addAttribute("files", storageService
            .loadAll(new PathNameMapper()
            {
                @Override
                public String mapPath(Path path)
                {
                    return MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString();
                }
            }));

    return "uploadForm";
}
</code>```

Update 2 (labmda -> anonymous class conversion)

And just for completeness an example of how to convert lambda to an anonymous class manually:

@Bean
CommandLineRunner init(StorageService storageService)
{
    return new CommandLineRunner()
    {
        @Override
        public void run(String... args) throws Exception
        {
            storageService.deleteAll();
            storageService.init();
        }
    };
}
```

Body:
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

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

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

package java.util.stream does not exist

Body:
Bulltorious, I'm sorry for your bounty but you really have only very few choices. Stream API was added only in Java 8 and thus does not exist in the Java 7. You can work-around lambda-related issues by manually writting anonymous classes or  even almost automatically (see Retrolambda). However with the Stream API you only have two choices:

Backport Stream API to Java 7 manually. Or use someone else attempt to backport such as streamsupport project on SourceForge (or copy on GitHub)

Get rid of the Stream API and use older Java 7 classes.

Update (replace Files.walk)

In case your Files.walk is the only place you use Java-8-specific API, you can replace it with Java 7 API relatively easily:

interface PathNameMapper
{
    String mapPath(Path path);
}

List<String> loadAll(PathNameMapper mapper)
{
    try
    {
        List<String> result = new ArrayList<>();

        Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
            {
                if (!rootLocation.equals(file))
                {
                    result.add(mapper.mapPath(rootLocation.relativize(file)));
                }
                return FileVisitResult.CONTINUE;
            }
        });

        return result;
    }
    catch (IOException e)
    {
        throw new StorageException("Failed to read stored files", e);
    }
}

and then your listUploadedFiles would become something like

@GetMapping ("/")
public String listUploadedFiles(Model model) throws IOException
{

    model.addAttribute("files", storageService
            .loadAll(new PathNameMapper()
            {
                @Override
                public String mapPath(Path path)
                {
                    return MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString();
                }
            }));

    return "uploadForm";
}

Update 2 (labmda -> anonymous class conversion)

And just for completeness an example of how to convert lambda to an anonymous class manually:

@Bean
CommandLineRunner init(StorageService storageService)
{
    return new CommandLineRunner()
    {
        @Override
        public void run(String... args) throws Exception
        {
            storageService.deleteAll();
            storageService.init();
        }
    };
}


来源: stackexchange

问:
How to connect sql server express database to VS 2017
I keep running into issues just trying to make a connection from my c# program in Visual Studio 2017 Express to a small local database with one table I created in Sql Server Express. I would like to connect it as a data source within Entity Framework in my solution (which is in c#). I've searched MSDN and this site for days but haven't found a way to solve this.

The issue now is that when I go through the Entity Data Model Wizard (existing database) and go to establish a New Connection, select "Microsoft SQL Server Database File (SqlClient)" and browse to my database -- the Test Connection generates the error:

Unable to open the physical file "C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\MyDatabase.mdf".
  Operating system error 5: "5(Access is denied.)".
  An attempt to attach an auto-named database for file C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\MyDatabase.mdf failed.
  A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

I'm running Visual Studio as Administrator (this got past a prior issue that wouldn't even let me browse to the database without prompting an error message that I didn't have permission to open the database file).

I can view my database, its table, and its data in the SQL Server Object Explorer inside Visual Studio - regardless of whether I'm running it as Administrator or not. Not sure if that is significant.
I'm new to all this, so sorry if I am missing something obvious.

答:
Figured out my issue:
in Visual Studio's "Add New Data Source" wizard, the option I kept choosing was "Microsoft SQL Server Database File", because its description is "Use this selection to attach a database file to a local Microsoft SQL Server instance (including Microsoft SQL Express) using the .NET Framework Data Provider for SQL Server."

However, and I'm not sure why, this was not the right selection.

I tried selecting "other" instead.

Then on the next page input ".\SQLExpress" as the Server Name (mentioned on connectionstrings.com/sql-server/ ...Thanks for the lead @ryguy72!)

Then, under "Connect to a database" my local list of databases popped up, including the one I had created already using SSMS.

Test Connection finally worked then!

ContentLicense: CC BY-SA 3.0


问:
node.js Facebook SDK OAuthException
I want to create a server with node.js to cache data like public page feed from Facebook graph API. I need this, because I wanted to make an Android app which pulls posts from a Facebook page. The app secret should not be used inside a app which can be decompiled, therefore I must have an dedicated application server

UPDATE:
I'm now trying to use Criso's FBgraph.

Example:

```<code>var graph = require('fbgraph');
    // pass it in as part of the url

    graph.get("/4" + "?access_token=appID|appSecret", function(err, res) {

        // returns the post id
        console.log(res); // { id: xxxxx}
    });
</code>```

returns:

```<code>{ name: 'Mark Zuckerberg', id: '4' }
</code>```

But I need to retrieve feed for a page. I can't use the {pageid} in the URL like: https://www.facebook.com/{pagename}-{pageid}/ returns this error "Some of the aliases you requested do not exist" the page is made and assgigned to the app and hasn't been published yet, because I'm testing if it works. Documentation tells me I need a page access code which requires me to login which is not an option.

Also, is there a better way to do this? I'm thinking is "node.js + NoSQL + facebook Node.js SDK" faster than "Apache + NoSQL + PHP facebook SDK" for caching results?

答:
Use, another library other than tenorviol's node.js, this havn't been updated in 6 years and their should be a lot of issues, and according to this by the repo owner this is not an active project https://github.com/tenorviol/node-facebook-sdk/issues/11

Suggestions

Since you're using graph API

https://www.npmjs.com/package/fbgraph

https://www.npmjs.com/package/fb

Update for second part

You should look at this to get public feed of a page

https://developers.facebook.com/docs/graph-api/reference/v2.8/page/feed

but even then it's not possible to access the feed without an access token

eg :
https://graph.facebook.com/SmashBalloon/feed?access_token=APP-ID|APP-SECRET

Title: node.js Facebook SDK OAuthException

Body:
I want to create a server with node.js to cache data like public page feed from Facebook graph API. I need this, because I wanted to make an Android app which pulls posts from a Facebook page. The app secret should not be used inside a app which can be decompiled, therefore I must have an dedicated application server

UPDATE:
I'm now trying to use Criso's FBgraph.

Example:

var graph = require('fbgraph');
    // pass it in as part of the url

    graph.get("/4" + "?access_token=appID|appSecret", function(err, res) {

        // returns the post id
        console.log(res); // { id: xxxxx}
    });

returns:

{ name: 'Mark Zuckerberg', id: '4' }

But I need to retrieve feed for a page. I can't use the {pageid} in the URL like: https://www.facebook.com/{pagename}-{pageid}/ returns this error "Some of the aliases you requested do not exist" the page is made and assgigned to the app and hasn't been published yet, because I'm testing if it works. Documentation tells me I need a page access code which requires me to login which is not an option.

Also, is there a better way to do this? I'm thinking is "node.js + NoSQL + facebook Node.js SDK" faster than "Apache + NoSQL + PHP facebook SDK" for caching results?


问:
Framework target, App target and cocoaPods working together, how to maintain dependencies
I am creating a framework that uses third party frameworks like alamofire. I have created a App that uses this framework and also uses third party framework again like alamofire(both could use it). So now I have 2 targets, I added both in workspace, I did pod init but it could only link with only one .xcodeproj and create its own workspace.

I also tried

Can I use CocoaPods when creating a Cocoa Touch Framework?

but pod install didn't work as it was not able to find target and if dragged in same folder it ask to specify target path as it only want one .xcodeproj

Please if somebody could help me with this. How to access cocoa pods framework in both custom framework and app.

答:
Ideally the Pod should be in your App.

Even though your Framework is also using the same third party framework the pod install should be done for that at App level and both App and framework should be able to read it.
Have said that, if you are developing Framework independently you can install POD at that time in framework but when your are using this framework in app then the third party framework can be installed at app level and frameworks should also be able to read it since they are now also part of same App target.


问:
DropShadowEffect applied multiple times on WPF custom control
I'm writing a WPF custom control that displays an overlay for loading processes. This custom control derives from ContentControl and reuses it's Effect dependency property to display a drop shadow.

However the drop shadow is unexpectely and unwantedly displayed two times. I've tried to find any logic to this, but do not know how to solve this. Anyone got a clue how to remove the shadow on the outer border?

LoadingOverlay.cs

```<code>public class LoadingOverlay : ContentControl
{
    static LoadingOverlay()
    {
        Type currentType = typeof(LoadingOverlay);
        FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(
            currentType,
            new FrameworkPropertyMetadata(currentType));
    }
}
</code>```

Themes\Generic.xaml

```<code><Style TargetType="local:LoadingOverlay">
    <Setter Property="Background" Value="#BBFFFFFF" />
    <Setter Property="BorderBrush" Value="#FF266ECC" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect ShadowDepth="0" />
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:LoadingOverlay">
                <Border Background="{TemplateBinding Background}" Effect="{x:Null}">
                    <Border Effect="{TemplateBinding Effect}" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FFFFFFFF" BorderBrush="#FF266ECC" BorderThickness="1">
                        <ContentPresenter VerticalAlignment="Center" Margin="15" RecognizesAccessKey="True" />
                    </Border>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

答:
Instead of Setting Effect at LoadingOverlay level, try setting Effect at inner Border level. Then you won't have to set the upper Border Effect to {x:null} as well. See below:

```<code><Style TargetType="local:LoadingOverlay">
<Setter Property="Background" Value="#BBFFFFFF" />
<Setter Property="BorderBrush" Value="#FF266ECC" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="local:LoadingOverlay">
            <Border Background="{TemplateBinding Background}">
                <Border HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FFFFFFFF" BorderBrush="#FF266ECC" BorderThickness="1">
                    <ContentPresenter VerticalAlignment="Center" Margin="15" RecognizesAccessKey="True" />
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" />
                    </Border.Effect>
                </Border>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>
</code>```

Body:
I'm writing a WPF custom control that displays an overlay for loading processes. This custom control derives from ContentControl and reuses it's Effect dependency property to display a drop shadow.

However the drop shadow is unexpectely and unwantedly displayed two times. I've tried to find any logic to this, but do not know how to solve this. Anyone got a clue how to remove the shadow on the outer border?

LoadingOverlay.cs

public class LoadingOverlay : ContentControl
{
    static LoadingOverlay()
    {
        Type currentType = typeof(LoadingOverlay);
        FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(
            currentType,
            new FrameworkPropertyMetadata(currentType));
    }
}

Themes\Generic.xaml

Body:
Instead of Setting Effect at LoadingOverlay level, try setting Effect at inner Border level. Then you won't have to set the upper Border Effect to {x:null} as well. See below:

<Style TargetType="local:LoadingOverlay">
<Setter Property="Background" Value="#BBFFFFFF" />
<Setter Property="BorderBrush" Value="#FF266ECC" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="local:LoadingOverlay">
            <Border Background="{TemplateBinding Background}">
                <Border HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FFFFFFFF" BorderBrush="#FF266ECC" BorderThickness="1">
                    <ContentPresenter VerticalAlignment="Center" Margin="15" RecognizesAccessKey="True" />
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" />
                    </Border.Effect>
                </Border>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>


问:
Django CSRF when backend and frontend are separated
After searching the internet, people normally deal with this situation---the front-end is generated by django view function which can send user the cookie of csrf token. When user has a request to server using ajax, people can rewrite the ajaxSend behavior which send the csrf to server.

However, my situation is that my front-end is totally separated from back-end, ie, my front-end is in a dedicated server running nginx, and I only have one html providing all of the different pages using hashbang. My back-end is running in different server using different domain name, and in this case, how does client obtain the csrf cookie? My back-end only provided json api return.

Thank you.

答: If you look at the CRSF token source:  you can see that all the csrf_middleware does it check the cookie against the post value. You just need to get the post value back to your server since the cookie should of already been set though ajax. If you look at the template tag source you can see that it is just taking the variable out of the context. Either stick it in your response by pulling it out of the context if it is available or calling the context processor directly. Now you just need to send it back as the POST variable crsf_token.  </p>


问:
Rx.Observable.merge is not working
I am trying to build a sample stop watch application using Rxjs. But when I try to merge the pause and reset streams it does not work.
Here is my code.

// What we need
/*
  1. interval observer
  2. click streams from 3 buttons
*/

const startButton = document.querySelector("#start")
const stopButton = document.querySelector("#stop")
const resetButton = document.querySelector("reset")

const start$ = Rx.Observable.fromEvent(startButton, 'click')
const stop$ = Rx.Observable.fromEvent(stopButton, 'click')
const reset$ = Rx.Observable.fromEvent(resetButton, 'click')

const interval$ = Rx.Observable.interval(1000)

const stopOrReset$ = Rx.Observable.merge(
  stop$,
  reset$
)

const pausible$ = interval$
  .takeUntil(stopOrReset$)

const init = 0
const inc = acc => acc + 1
const reset = acc => init

const incOrReset$ = Rx.Observable.merge(
  pausible$.mapTo(inc),
  reset$.mapTo(reset)
)

 app$ = start$
  .switchMapTo(incOrReset$)
  .startWith(init)
  .scan((acc, currFunc) => currFunc(acc))
  .subscribe(val => console.log(val))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #ffa600;
  font-family: "HelveticaNeue-Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  height: 100%;
}

.wrapper {
  wdith: 800px;
  margin: 50px auto;
  color: #fff;
  text-align: center;
}

#clock {
  margin: 5$ auto;
  font-size: 4em;
}

button {
  border-radius: 5px;
  background: #fffa600;
  color: #fff;
  border: solid 1px #fff;
  text-decoration: none;
  cursor: pointer;
  font-size: 1.2em;
  padding: 18px 10px;
  width: 180px;
  margin: 10px;
  outline: none;
}

button:hover {
  transition: all 0.5s ease-in-out;
  background: #fff;
  border: solid 1px #fff;
  color: #ffa600;
}</code>```

<!DOCTYPE html>

  <meta name="description" content="Ractive JavaScript Stop Watch Application">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <button id="start">Start</button>
    <button id="stop">Stop</button>

      :
      :

    <button id="reset">Reset</button>

```

If your run this code you will see the .switchMapTo(incOrReset$) functionality is not working. And all the console is spitting out is 0

答:
I did not have a # for the const resetButton = document.querySelector("reset")

That was the problem

const startButton = document.querySelector("#start")
const stopButton = document.querySelector("#stop")
const resetButton = document.querySelector("#reset")

const start$ = Rx.Observable.fromEvent(startButton, 'click')
const stop$ = Rx.Observable.fromEvent(stopButton, 'click')
const reset$ = Rx.Observable.fromEvent(resetButton, 'click')

const interval$ = Rx.Observable.interval(1000)

const pausible$ = interval$
                          .takeUntil(stop$)

const init = 0
const inc = acc => acc+1
const reset = acc => init

const incOrReset$ = Rx.Observable.merge(
  pausible$.mapTo(inc),
  reset$.mapTo(reset)
)

app$ = start$
    .switchMapTo(incOrReset$)
    .startWith(init)
    .scan((acc, currFunc) => currFunc(acc))
    .subscribe(val => console.log(val))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  background: #ffa600;
  font-family: "HelveticaNeue-Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  height: 100%;
}
.wrapper{
  wdith: 800px;
  margin: 50px auto;
  color: #fff;
  text-align: center;
}
#clock{
  margin: 5$ auto;
  font-size: 4em;
}
button{
  border-radius: 5px;
  background: #fffa600;
  color: #fff;
  border: solid 1px #fff;
  text-decoration: none;
  cursor: pointer;
  font-size: 1.2em;
  padding: 18px 10px;
  width: 180px;
  margin: 10px;
  outline: none;
}
button:hover{
  transition: all 0.5s ease-in-out;
  background: #fff;
  border: solid 1px #fff;
  color: #ffa600;
}</code>```

<!DOCTYPE html>

<meta name="description" content="Ractive JavaScript Stop Watch Application">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <button id="start">Start</button>
    <button id="stop">Stop</button>

      :
      :

    <button id="reset">Reset</button>

```

Title: Rx.Observable.merge is not working

Body:
I am trying to build a sample stop watch application using Rxjs. But when I try to merge the pause and reset streams it does not work.
Here is my code.

// What we need
/*
  1. interval observer
  2. click streams from 3 buttons
*/

const startButton = document.querySelector("#start")
const stopButton = document.querySelector("#stop")
const resetButton = document.querySelector("reset")

const start$ = Rx.Observable.fromEvent(startButton, 'click')
const stop$ = Rx.Observable.fromEvent(stopButton, 'click')
const reset$ = Rx.Observable.fromEvent(resetButton, 'click')

const interval$ = Rx.Observable.interval(1000)

const stopOrReset$ = Rx.Observable.merge(
  stop$,
  reset$
)

const pausible$ = interval$
  .takeUntil(stopOrReset$)

const init = 0
const inc = acc => acc + 1
const reset = acc => init

const incOrReset$ = Rx.Observable.merge(
  pausible$.mapTo(inc),
  reset$.mapTo(reset)
)

 app$ = start$
  .switchMapTo(incOrReset$)
  .startWith(init)
  .scan((acc, currFunc) => currFunc(acc))
  .subscribe(val => console.log(val))

body {
  background: #ffa600;
  font-family: "HelveticaNeue-Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  height: 100%;
}

.wrapper {
  wdith: 800px;
  margin: 50px auto;
  color: #fff;
  text-align: center;
}

#clock {
  margin: 5$ auto;
  font-size: 4em;
}

button {
  border-radius: 5px;
  background: #fffa600;
  color: #fff;
  border: solid 1px #fff;
  text-decoration: none;
  cursor: pointer;
  font-size: 1.2em;
  padding: 18px 10px;
  width: 180px;
  margin: 10px;
  outline: none;
}

button:hover {
  transition: all 0.5s ease-in-out;
  background: #fff;
  border: solid 1px #fff;
  color: #ffa600;
}

<!DOCTYPE html>

  <meta name="description" content="Ractive JavaScript Stop Watch Application">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <button id="start">Start</button>
    <button id="stop">Stop</button>

      :
      :

    <button id="reset">Reset</button>

If your run this code you will see the .switchMapTo(incOrReset$) functionality is not working. And all the console is spitting out is 0

Body:
I did not have a # for the const resetButton = document.querySelector("reset")

That was the problem

const startButton = document.querySelector("#start")
const stopButton = document.querySelector("#stop")
const resetButton = document.querySelector("#reset")

const start$ = Rx.Observable.fromEvent(startButton, 'click')
const stop$ = Rx.Observable.fromEvent(stopButton, 'click')
const reset$ = Rx.Observable.fromEvent(resetButton, 'click')

const interval$ = Rx.Observable.interval(1000)

const pausible$ = interval$
                          .takeUntil(stop$)

const init = 0
const inc = acc => acc+1
const reset = acc => init

const incOrReset$ = Rx.Observable.merge(
  pausible$.mapTo(inc),
  reset$.mapTo(reset)
)

app$ = start$
    .switchMapTo(incOrReset$)
    .startWith(init)
    .scan((acc, currFunc) => currFunc(acc))
    .subscribe(val => console.log(val))

body{
  background: #ffa600;
  font-family: "HelveticaNeue-Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  height: 100%;
}
.wrapper{
  wdith: 800px;
  margin: 50px auto;
  color: #fff;
  text-align: center;
}
#clock{
  margin: 5$ auto;
  font-size: 4em;
}
button{
  border-radius: 5px;
  background: #fffa600;
  color: #fff;
  border: solid 1px #fff;
  text-decoration: none;
  cursor: pointer;
  font-size: 1.2em;
  padding: 18px 10px;
  width: 180px;
  margin: 10px;
  outline: none;
}
button:hover{
  transition: all 0.5s ease-in-out;
  background: #fff;
  border: solid 1px #fff;
  color: #ffa600;
}

<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Ractive JavaScript Stop Watch Application">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="wrapper">
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <div id="clock">
      <span id="minutes"></span>:
      <span id="seconds"></span>:
      <span id="milliseconds"></span>
    </div>
    <button id="reset">Reset</button>
  </div>
  <script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
</body>
</html>


问:
Enum Error in C "Unknown Type"
I keep getting "Unknown type name 'place' even though I wrote the enum correct I can not see the error on what I am doing wrong. thanks </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
void pass(place x);

typedef enum{

house, second

} place;

int main()
{

pass(house);

return 0;
}

void pass(place x){

 if(x == house){
  printf("We are in a house \n")
  }else if(x == second){
  printf("We live in the second house \n");
 }

 return;

 }
</code>```

答:
Your enum place declaration is fine. The problem is you're defining a function with place before the existence of place is known. Change the order and define your place enum first, before you pass() function.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

typedef enum{
   house,
   second
} place;

void pass(place x); // This function forward declaration must be after you defined place.

int main()
{ /* .. */ }
</code>```

Title: Enum Error in C "Unknown Type"

Body:
I keep getting "Unknown type name 'place' even though I wrote the enum correct I can not see the error on what I am doing wrong. thanks

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
void pass(place x);

typedef enum{

house, second

} place;

int main()
{

pass(house);

return 0;
}

void pass(place x){

 if(x == house){
  printf("We are in a house \n")
  }else if(x == second){
  printf("We live in the second house \n");
 }

 return;

 }

Body:
Your enum place declaration is fine. The problem is you're defining a function with place before the existence of place is known. Change the order and define your place enum first, before you pass() function.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

typedef enum{
   house,
   second
} place;

void pass(place x); // This function forward declaration must be after you defined place.

int main()
{ /* .. */ }


问:
Neither Node.js PUT or POST routes are presenting the data that is being received
I tried this with a number of different modules and methods.
Even by proving the other modules do work as expected in Node by building a separate test project and testing each module individually.

Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)

This problem is not one of SENDING data to an API.  It must IMO a problem in the receiving API's not giving up the data it IS receiving for some reason.

I've proven the PUT or POST calls are sending the data by sending the call to http://httpbin/org.  That site shows me I'm sending what I expect to be sending.

Here is how I'm sending.  I can even see in the receiving API that that API is certainly getting called successfully.

-- sending --  ((Again.  This shows my node.http attempt.  But I get the same problem using requestjs, requestifyjs, needlejs))

```<code>router.get('/', function (req, res, next) {

    var hst = req.headers.host.split(':');
    var lookbackURL = 'https://' + req.headers.host + req.baseUrl;
    lookbackURL = 'http"httpbin.org/put';
    var dat = {
        what: 'ever'
        , try: 'again'
    };
    var bdy = JSON.stringify(dat);
    var options = {
        host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'
        , headers: { 'Content-Type': 'application/json' }
    };

    var r = nodeHttp.request(options); r.write(bdy); r.end();
    res.sendStatus(200);

});
</code>```

-- receiving --

```<code>router.put('/', function (req, res, next) {
    console.log('r', req);
});
</code>```

No matter what module or method I use, in all cases, the receiving req object doesn't contain the what or try data.

BUT in my test project the data is there as I expect it to be, in all cases.
Doing the same console.log(req); in the test project, reqestjs, requestjs, needlejs, node.http all show a proper body object.
But in this problem there isn't a body object in req.
And sending this put/post to http://httpbin.org I can see the body object is being sent.

Any ideas?

答:
Issue found.  And it was something no one on here could have gotten for the code I posted.

For reasons I will not go into I have to take body-parser out this application.  This also means app.use() won't have a parser given to it.

And that means I have to deal with getting the data on my own.  So I've added a req.on('data') listener to read the chunk from the call to the API.

```<code>router.put('/', function (req, res, next) {
    var data = '';
    req.on('data', function (chunk) {
        data += chunk;
        .....
    });
.....
</code>```

I also decided to do this as a PUT using Requestify.
This just goes to show how easy it is to become complacent and forget how things really work; the assumption of body-parser (or other things) always being there for instance.  Or what it is really doing for you.

NEXT I have to figure out how to get a value out of the `req.on('data) back to the method PUTting to the API.  Any tips?  Appreciated.

Body:
I tried this with a number of different modules and methods.
Even by proving the other modules do work as expected in Node by building a separate test project and testing each module individually.

Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)

This problem is not one of SENDING data to an API.  It must IMO a problem in the receiving API's not giving up the data it IS receiving for some reason.

I've proven the PUT or POST calls are sending the data by sending the call to http://httpbin/org.  That site shows me I'm sending what I expect to be sending.

Here is how I'm sending.  I can even see in the receiving API that that API is certainly getting called successfully.

-- sending --  ((Again.  This shows my node.http attempt.  But I get the same problem using requestjs, requestifyjs, needlejs))

router.get('/', function (req, res, next) {

    var hst = req.headers.host.split(':');
    var lookbackURL = 'https://' + req.headers.host + req.baseUrl;
    lookbackURL = 'http"httpbin.org/put';
    var dat = {
        what: 'ever'
        , try: 'again'
    };
    var bdy = JSON.stringify(dat);
    var options = {
        host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'
        , headers: { 'Content-Type': 'application/json' }
    };

    var r = nodeHttp.request(options); r.write(bdy); r.end();
    res.sendStatus(200);

});

-- receiving --

router.put('/', function (req, res, next) {
    console.log('r', req);
});

No matter what module or method I use, in all cases, the receiving req object doesn't contain the what or try data.

BUT in my test project the data is there as I expect it to be, in all cases.
Doing the same console.log(req); in the test project, reqestjs, requestjs, needlejs, node.http all show a proper body object.
But in this problem there isn't a body object in req.
And sending this put/post to http://httpbin.org I can see the body object is being sent.

Any ideas?

Body:
Issue found.  And it was something no one on here could have gotten for the code I posted.

For reasons I will not go into I have to take body-parser out this application.  This also means app.use() won't have a parser given to it.

And that means I have to deal with getting the data on my own.  So I've added a req.on('data') listener to read the chunk from the call to the API.

router.put('/', function (req, res, next) {
    var data = '';
    req.on('data', function (chunk) {
        data += chunk;
        .....
    });
.....

I also decided to do this as a PUT using Requestify.
This just goes to show how easy it is to become complacent and forget how things really work; the assumption of body-parser (or other things) always being there for instance.  Or what it is really doing for you.

NEXT I have to figure out how to get a value out of the `req.on('data) back to the method PUTting to the API.  Any tips?  Appreciated.


问:
Rails: how to include Rack::Utils
I follow rails convention here: That we shouldn't use directly error code but its symbol. For example:

```<code># bad
...
render status: 500
...

# good
...
render status: :forbidden
...
</code>```

But in fact, those number hasn't been declared yet, so if I want to use I must use as:

```<code>Rack::Utils::SYMBOL_TO_STATUS_CODE[:bad_request]
</code>```

This is messy. My question is: how can I include/extend module Rake::Utils so I only need use :bad_request

答:
Using Rails 4.2.5.1 from rails console, doing:

Rack::Utils::SYMBOL_TO_STATUS_CODE[:bad_request] I get 400

Doing Rack::Utils::SYMBOL_TO_STATUS_CODE. I can see all this statuses...

```<code>{
 :continue=>100,
 :switching_protocols=>101,
 :processing=>102,
 :ok=>200,
 :created=>201,
 :accepted=>202,
 :non_authoritative_information=>203,
 :no_content=>204,
 :reset_content=>205,
 :partial_content=>206,
 :multi_status=>207,
 :already_reported=>208,
 :im_used=>226,
 :multiple_choices=>300,
 :moved_permanently=>301,
 :found=>302,
 :see_other=>303,
 :not_modified=>304,
 :use_proxy=>305,
 :temporary_redirect=>307,
 :permanent_redirect=>308,
 :bad_request=>400,
 :unauthorized=>401,
 :payment_required=>402,
 :forbidden=>403,
 :not_found=>404,
 :method_not_allowed=>405,
 :not_acceptable=>406,
 :proxy_authentication_required=>407,
 :request_timeout=>408,
 :conflict=>409,
 :gone=>410,
 :length_required=>411,
 :precondition_failed=>412,
 :payload_too_large=>413,
 :uri_too_long=>414,
 :unsupported_media_type=>415,
 :range_not_satisfiable=>416,
 :expectation_failed=>417,
 :unprocessable_entity=>422,
 :locked=>423,
 :failed_dependency=>424,
 :upgrade_required=>426,
 :precondition_required=>428,
 :too_many_requests=>429,
 :request_header_fields_too_large=>431,
 :internal_server_error=>500,
 :not_implemented=>501,
 :bad_gateway=>502,
 :service_unavailable=>503,
 :gateway_timeout=>504,
 :http_version_not_supported=>505,
 :variant_also_negotiates=>506,
 :insufficient_storage=>507,
 :loop_detected=>508,
 :not_extended=>510,
 :network_authentication_required=>511
}
</code>```

I think you don't need to define any new status.
If you need to do it anyway, you can add it using an initializer:

/my_app/config/initializers/codes.rb

Rack::Utils::SYMBOL_TO_STATUS_CODE[:my_code] = 666

Then in a controller:

```<code>class Api::V1::RegionsController < Api::V1::BaseController
  def index
    respond_with Region.all, status: :my_code
  end
end
</code>```

As you can see, I'm returning the custom code.

Title: Rails: how to include Rack::Utils

Body:
I follow rails convention here: That we shouldn't use directly error code but its symbol. For example:

# bad
...
render status: 500
...

# good
...
render status: :forbidden
...

But in fact, those number hasn't been declared yet, so if I want to use I must use as:

Rack::Utils::SYMBOL_TO_STATUS_CODE[:bad_request]

This is messy. My question is: how can I include/extend module Rake::Utils so I only need use :bad_request

Body:
Using Rails 4.2.5.1 from rails console, doing:

Rack::Utils::SYMBOL_TO_STATUS_CODE[:bad_request] I get 400

Doing Rack::Utils::SYMBOL_TO_STATUS_CODE. I can see all this statuses...

{
 :continue=>100,
 :switching_protocols=>101,
 :processing=>102,
 :ok=>200,
 :created=>201,
 :accepted=>202,
 :non_authoritative_information=>203,
 :no_content=>204,
 :reset_content=>205,
 :partial_content=>206,
 :multi_status=>207,
 :already_reported=>208,
 :im_used=>226,
 :multiple_choices=>300,
 :moved_permanently=>301,
 :found=>302,
 :see_other=>303,
 :not_modified=>304,
 :use_proxy=>305,
 :temporary_redirect=>307,
 :permanent_redirect=>308,
 :bad_request=>400,
 :unauthorized=>401,
 :payment_required=>402,
 :forbidden=>403,
 :not_found=>404,
 :method_not_allowed=>405,
 :not_acceptable=>406,
 :proxy_authentication_required=>407,
 :request_timeout=>408,
 :conflict=>409,
 :gone=>410,
 :length_required=>411,
 :precondition_failed=>412,
 :payload_too_large=>413,
 :uri_too_long=>414,
 :unsupported_media_type=>415,
 :range_not_satisfiable=>416,
 :expectation_failed=>417,
 :unprocessable_entity=>422,
 :locked=>423,
 :failed_dependency=>424,
 :upgrade_required=>426,
 :precondition_required=>428,
 :too_many_requests=>429,
 :request_header_fields_too_large=>431,
 :internal_server_error=>500,
 :not_implemented=>501,
 :bad_gateway=>502,
 :service_unavailable=>503,
 :gateway_timeout=>504,
 :http_version_not_supported=>505,
 :variant_also_negotiates=>506,
 :insufficient_storage=>507,
 :loop_detected=>508,
 :not_extended=>510,
 :network_authentication_required=>511
}

I think you don't need to define any new status.
If you need to do it anyway, you can add it using an initializer:

/my_app/config/initializers/codes.rb

Rack::Utils::SYMBOL_TO_STATUS_CODE[:my_code] = 666

Then in a controller:

class Api::V1::RegionsController < Api::V1::BaseController
  def index
    respond_with Region.all, status: :my_code
  end
end

As you can see, I'm returning the custom code.


问:
Middleware doesn't work as expected - Laravel
I want to make a middleware to protect admin routes in laravel 5.2 app.
user_type isn't a field in users table in my db, but in a separate table :

Admin's user_type_id is 4
I made this middleware :

```<code>class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}
</code>```

and put this in $routeMiddleware array in kernel.php :

```<code>'admin' => \App\Http\Middleware\AdminMiddleware::class
</code>```

and this is one of admin routes I want to apply my middleware on :

```<code>Route::get('ptyadmin', 'AdminController@show')->middleware('admin');
</code>```

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

答:
It works when I put jwt.auth middleware in routes.php :

```<code>Route::get('ptyadmin', 'AdminController@show')
->middleware('jwt.auth')
->middleware('admin');
</code>```

instead of putting it in AdminController :

```<code>public function __construct(User $user, JWTAuth $jwtauth)
</code>```

{

```<code>   $this->middleware('jwt.auth', ['except' => []]);
</code>```

}

Body:
I want to make a middleware to protect admin routes in laravel 5.2 app.
user_type isn't a field in users table in my db, but in a separate table :

Admin's user_type_id is 4
I made this middleware :

class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}

and put this in $routeMiddleware array in kernel.php :

'admin' => \App\Http\Middleware\AdminMiddleware::class

and this is one of admin routes I want to apply my middleware on :

Route::get('ptyadmin', 'AdminController@show')->middleware('admin');

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

Body:
It works when I put jwt.auth middleware in routes.php :

Route::get('ptyadmin', 'AdminController@show')
->middleware('jwt.auth')
->middleware('admin');

instead of putting it in AdminController :

public function __construct(User $user, JWTAuth $jwtauth)

{

   $this->middleware('jwt.auth', ['except' => []]);

}


问:
Performing synchronus Requests using $.ajax
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

```<code>function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }
</code>```

答:
Use the complete function and make a case for "timeout"

from jQuery Docs

complete(XMLHttpRequest,
textStatus) - Function

A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

so Code would look something like this on your ajax:

```<code>function empvalidate() {
      var exists = false;             // default return value is false
      var empno = $("#empno").val();
      if (empno != '') {
        $.ajax({
          url: "emp.php",
          async: false,
          dataType: "json",
          data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
          success: function (data, ts) {

              if(ts == "success")
                   exists = data.status; // set status of existence to outer variable
              else if(ts == "timeout")
              {
                   $(document).trigger('customTimeoutHandler');
              }
          }
        });
      }
      return exists;                  // return actual value
    }
</code>```

Not really sure of the application here, but remember that you can also set a custom timeout variable here too.  Not too sure what you would want it to be, it just depends on your scenario.

ContentLicense: CC BY-SA 2.5

Body:
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }

Body:
Use the complete function and make a case for "timeout"

from jQuery Docs

complete(XMLHttpRequest,
textStatus) - Function

A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

so Code would look something like this on your ajax:

function empvalidate() {
      var exists = false;             // default return value is false
      var empno = $("#empno").val();
      if (empno != '') {
        $.ajax({
          url: "emp.php",
          async: false,
          dataType: "json",
          data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
          success: function (data, ts) {

              if(ts == "success")
                   exists = data.status; // set status of existence to outer variable
              else if(ts == "timeout")
              {
                   $(document).trigger('customTimeoutHandler');
              }
          }
        });
      }
      return exists;                  // return actual value
    }

Not really sure of the application here, but remember that you can also set a custom timeout variable here too.  Not too sure what you would want it to be, it just depends on your scenario.


问:
How do I switch rows and columns in a 2D array?
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

```<code>def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1
</code>```

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]
```

<p>Here is the full code if you are curious about the project, but it requires <code>rhinoscriptsyntax</code> to make the model.</p>

```import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1
```

答:
You could do it as shown. It works by first making the array square so that all the rows have the same number of elements. then transposes the rows and columns using the built-in zip() function, and then finally removes the elements it initially added.

Note also I removed the use of the global variable array. Global variables are best avoided.

```<code>from pprint import pprint

def pascal(n):
    """Creates n rows of Pascal's triangle."""
    array = [None for y in range(n)]

    row = [1]
    array[0] = row
    k = [0]
    for x in range(max(n, 0)-1):
       row = [l+r for l,r in zip(row+k, k+row)]
       array[x+1] = row

    return array

def transpose(array):
    array = array[:]  # make copy to avoid changing original
    n = len(array)
    for i, row in enumerate(array):
        array[i] = row + [None for _ in range(n - len(row))]

    array = zip(*array)

    for i, row in enumerate(array):
        array[i] = [elem for elem in row if elem is not None]

    return array

array = pascal(8)
array = transpose(array)
pprint(array)
</code>```

Output:

[[1, 1, 1, 1, 1, 1, 1, 1],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 3, 6, 10, 15, 21],
 [1, 4, 10, 20, 35],
 [1, 5, 15, 35],
 [1, 6, 21],
 [1, 7],
 [1]]
```

Body:
I am working on a code that will create a visual Sierpinski triangle to 3D print, and in order for it to work I have to use a Pascal triangle algorithm that will create an array so I can use to tell my algorithm that will create my triangles where not to put triangles.

Anyway the problem is, that my code that arranges the triangles creates the triangles by column instead of by row like the Pascal algorithm does so I am just trying to do a quick fix by having a subroutine that rearranges the Pascal array. I am just stumped on how to do it since I am not sure how to avoid index out of range errors.

This is the code that creates the array for Pascal's triangle.

TL:DR I am trying to make an rearrange an array where rows are the columns and columns are the rows

def pascal(n):
    """Prints out n rows of Pascal's triangle."""
    row = [1]
    global array
    array = [[0 for x in range(int(n))] for y in range(int(n))]
    array[0]=row
    k = [0]
    for x in range(int(max(n,0)-1)):
       row=[l+r for l,r in zip(row+k,k+row)]
       array[x+1]=row
    return 1

This is the output of printing the array. I just want the rows to be columns and columns to be rows

[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1]]

Here is the full code if you are curious about the project, but it requires rhinoscriptsyntax to make the model.

import rhinoscriptsyntax as rhino
import math

obj = rhino.GetObject("Select object to transform", preselect=True)
scale = 3
n=math.pow(3,scale)
def pascal(n):
   """Prints out n rows of Pascal's triangle."""
   row = [1]
   global array
   array = [[0 for x in range(int(n))] for y in range(int(n))]
   array[0]=row
   k = [0]
   for x in range(int(max(n,0)-1)):
      row=[l+r for l,r in zip(row+k,k+row)]
      array[x+1]=row
   return 1
pascal(math.pow(2,scale))
print array
def remakePascal():
    pass
my_horizontalVector = [[1,0,0,6],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

my_tsfm = [[1,0,0,0],  #identity
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]

def makeTriangle(scale,obj):
    w=1/scale
    h=1/scale
    tsfm= [[w,0,0,0],   #scale about origin
            [0,h,0,0],
            [0,0,1,0],
            [0,0,0,1]]
    output= rhino.XformMultiply(my_tsfm,tsfm)
    new_obj=rhino.TransformObject(obj,output,copy=True)
    return new_obj
def placeObj(i):
    my_moveUpVector = [[1,0,0,(3/scale)*i],
           [0,1,0,(4/scale)*i],
           [0,0,1,0],
           [0,0,0,1]]
    vector = rhino.XformMultiply(my_tsfm,my_moveUpVector)
    return vector
n=0
for i in range(int(math.pow(2,scale))):
    if(i>0):
       hPlace=rhino.XformMultiply(my_tsfm,my_horizontalVector)
       obj = rhino.TransformObject(obj,hPlace)
    factor = int(math.pow(2,scale))-n
    for j in range(factor):
        if():
            pass
        else:
            Vertobj=makeTriangle(scale,obj)
            tsfm = rhino.TransformObject(Vertobj,placeObj(j),copy=True)
    n=n+1

Body:
You could do it as shown. It works by first making the array square so that all the rows have the same number of elements. then transposes the rows and columns using the built-in zip() function, and then finally removes the elements it initially added.

Note also I removed the use of the global variable array. Global variables are best avoided.

from pprint import pprint

def pascal(n):
    """Creates n rows of Pascal's triangle."""
    array = [None for y in range(n)]

    row = [1]
    array[0] = row
    k = [0]
    for x in range(max(n, 0)-1):
       row = [l+r for l,r in zip(row+k, k+row)]
       array[x+1] = row

    return array

def transpose(array):
    array = array[:]  # make copy to avoid changing original
    n = len(array)
    for i, row in enumerate(array):
        array[i] = row + [None for _ in range(n - len(row))]

    array = zip(*array)

    for i, row in enumerate(array):
        array[i] = [elem for elem in row if elem is not None]

    return array

array = pascal(8)
array = transpose(array)
pprint(array)

Output:

[[1, 1, 1, 1, 1, 1, 1, 1],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 3, 6, 10, 15, 21],
 [1, 4, 10, 20, 35],
 [1, 5, 15, 35],
 [1, 6, 21],
 [1, 7],
 [1]]


问:
find nested array based on given value
```<code>var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);
</code>```

How to display one array from myarr? For example if I enter 002 in input box it should display: 002,"John",700000

答:
I would recommend changing your data structure to something resembling  a map.  Then you can print out each person's data using the number (or string representation thereof) as a key.  Something like this:

```<code>var data = {};
data["001"] = ["Ravi", 800000];
data["002"] = ["John", 700000];
data["003"] = ["Vishal", 500000];
data["004"] = ["Michel", 600000];
data["005"] = ["Stella", 700000];

var input = "002";
console.log(data[input]);
</code>```

Demo here:

Rextester

Title: find nested array based on given value

Body:
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);

How to display one array from myarr? For example if I enter 002 in input box it should display: 002,"John",700000

Body:
I would recommend changing your data structure to something resembling  a map.  Then you can print out each person's data using the number (or string representation thereof) as a key.  Something like this:

var data = {};
data["001"] = ["Ravi", 800000];
data["002"] = ["John", 700000];
data["003"] = ["Vishal", 500000];
data["004"] = ["Michel", 600000];
data["005"] = ["Stella", 700000];

var input = "002";
console.log(data[input]);

Demo here:

Rextester


问:
Angular JS Custom Directive not working as element tag
I'm playing around with basic Angular JS stuff. I thought I knew custom directives pretty well but I'm only able to get them to show up in the template if I use them as element attributes. And I'm not wanting to use comments or class names as those are not best practices. Based on documentation and other sources these directives SHOULD work as an element AND an element attribute.

In my index you'll see that I'm declaring my directives twice -- in the top block as attributes (which work) and the bottom block as elements (which don't work). I'm hours deep into this problem. Any insight is tremendously appreciated.

Index.html

```<code><head>
  <title>Test App</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href='styles/css/style.css' rel='stylesheet' type="text/css">

  <script src="vendor/angular_1.2.13/angular.min.js"></script>

</head>

<body ng-app="testApp" class="app__body">
    <div class="body__inner">
        <header>
          <h1>My New Test App</h1>
        </header>

        <div first-directive></div>
        <div second-directive></div>

        <first-directive></first-directive>
        <second-directive></second-directive>

    </div>
    <script src="scripts/all-in-one.js" type="text/javascript"></script>
</body>
</code>```

all-in-one.js

```<code>'use strict';

angular.module('testApp', [])

.directive('firstDirective', function() {
    return {
        template: 'Hello World'
    }
})

.directive('secondDirective', function() {
    return {
        templateUrl: '/scripts/directives/secondDirective.js'
    }
})

.controller('firstCtrl', function($scope) {
    $scope.message = "Hola Amigos!"
})
</code>```

secondDirective.js

```<code><div>
    <h2>Esta Aqui!</h2>
</div>
</code>```

答:
In angular 1.2x you have to set the restrict value to include 'E' as its not included by default.

```<code>.directive('secondDirective', function() {
    return {
        restrict: 'EA',
        template: '<div><h2>Esta Aqui!</h2></div>'
    }
})
</code>```

Upgrading to a newer angular version, 'EA' is set as a default value.

Body:
I'm playing around with basic Angular JS stuff. I thought I knew custom directives pretty well but I'm only able to get them to show up in the template if I use them as element attributes. And I'm not wanting to use comments or class names as those are not best practices. Based on documentation and other sources these directives SHOULD work as an element AND an element attribute.

In my index you'll see that I'm declaring my directives twice -- in the top block as attributes (which work) and the bottom block as elements (which don't work). I'm hours deep into this problem. Any insight is tremendously appreciated.

Index.html

  <title>Test App</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href='styles/css/style.css' rel='stylesheet' type="text/css">

My New Test App

        <first-directive></first-directive>
        <second-directive></second-directive>

all-in-one.js

'use strict';

angular.module('testApp', [])

.directive('firstDirective', function() {
    return {
        template: 'Hello World'
    }
})

.directive('secondDirective', function() {
    return {
        templateUrl: '/scripts/directives/secondDirective.js'
    }
})

.controller('firstCtrl', function($scope) {
    $scope.message = "Hola Amigos!"
})

secondDirective.js

Esta Aqui!

Body:
In angular 1.2x you have to set the restrict value to include 'E' as its not included by default.

.directive('secondDirective', function() {
    return {
        restrict: 'EA',
        template: '<div><h2>Esta Aqui!</h2></div>'
    }
})

Upgrading to a newer angular version, 'EA' is set as a default value.


问:
Matrix of random permutations
I want to create a matrix of x columns of random permutations from 1 to 10, say. The command randperm(10) works great, yet I would like to create x of those.

Is there a way to do it without a loop?
Thanks,

答:
I assume that each permutation should be generated with the same probability and independently of others (and so some permutations can happen to be the same).

To generate x permutations in a vectorized way you can use:

```<code>N = 10; % population
x = 5; % desired number of permutations
[~, result] = sort(rand(x,N), 2);
</code>```

This gives (example):

```<code>result =
     7     1     2     9     6    10     3     4     5     8
     2     6     4    10     1     7     5     9     3     8
     6    10     2     7     9     5     4     3     1     8
     7     5     4     6     2    10     8     1     3     9
     6     4     2     8    10     9     5     1     7     3
</code>```

How this works

A simple way to generate one permutation of 1, ..., N is

Generate N random numbers.

Sort them, and get the indices of the sorting. Those indices are a random permutation of the integers 1, ..., N.

So, to generate x permutations in a vectorized way:

Generate an x-by-N matrix of random numbers.

Sort each row, and get the indices of each sorting.

Title: Matrix of random permutations

Body:
I assume that each permutation should be generated with the same probability and independently of others (and so some permutations can happen to be the same).

To generate x permutations in a vectorized way you can use:

N = 10; % population
x = 5; % desired number of permutations
[~, result] = sort(rand(x,N), 2);

This gives (example):

result =
     7     1     2     9     6    10     3     4     5     8
     2     6     4    10     1     7     5     9     3     8
     6    10     2     7     9     5     4     3     1     8
     7     5     4     6     2    10     8     1     3     9
     6     4     2     8    10     9     5     1     7     3

How this works

A simple way to generate one permutation of 1, ..., N is

Generate N random numbers.

Sort them, and get the indices of the sorting. Those indices are a random permutation of the integers 1, ..., N.

So, to generate x permutations in a vectorized way:

Generate an x-by-N matrix of random numbers.

Sort each row, and get the indices of each sorting.


问:
How to add css style to the all children of element at the same time?
Such as:

```<code><div class="mostOut">
    <div class="a">
        <h3 class="b"></h3>
        <div class="d"></div>
    </div>
</div>
</code>```

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

答:
Have you considered using a 100% CSS method?

As Nick Craver pointed out: "Children can't have a greater opacity then their parent, why not set the opacity only on the .mostOut element?"

HTML

```<code><div class="mostOut">
  div class mostOut
  <div class="a">
    div class a
    <h3 class="b">h3 class b</h3>
    <div class="d">div class d</div>
  </div>
</div>
</code>```

CSS

```<code>.mostOut{
  opacity:0.5;
}
.mostOut:active{
  opacity:1;
}
</code>```

jsFiddle demo 1

Or, use the CSS Child Selector (same HTML as above):

CSS

```<code>.mostOut:active > div{
  border:solid 1px gray;
  opacity:0.5;
}
</code>```

jsFiddle demo 2

Body:
Such as:

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

Body:
Have you considered using a 100% CSS method?

As Nick Craver pointed out: "Children can't have a greater opacity then their parent, why not set the opacity only on the .mostOut element?"

HTML

<div class="mostOut">
  div class mostOut
  <div class="a">
    div class a
    <h3 class="b">h3 class b</h3>
    <div class="d">div class d</div>
  </div>
</div>

CSS

.mostOut{
  opacity:0.5;
}
.mostOut:active{
  opacity:1;
}

jsFiddle demo 1

Or, use the CSS Child Selector (same HTML as above):

CSS

.mostOut:active > div{
  border:solid 1px gray;
  opacity:0.5;
}

jsFiddle demo 2


问:
pass a static value to a controller from routes in laravel
i would like to pass a static value(variable or a static string) from route definition to a controller.
for example if consider the following route:

```<code>Route::get('/', [
      'uses' => '\Controllers\FoController@show',
      'as' => 'show'
]);
</code>```

i want to pass a variable(ex, $var1) to that, and then can access to that in the FoController constructor or other controller methods , so i don't like that variable's value shows in the url.
how can i do this? thanks...

答:
Use a closure and call the controller yourself and pass what ever you want.. </p>

```<code>Route::get('/', function(){
  $controller = app()->make('FoController');
  return $controller->callAction('show', ['foo' => 'bar', 'ping' => 'pong']);
});
</code>```

Body:
i would like to pass a static value(variable or a static string) from route definition to a controller.
for example if consider the following route:

Route::get('/', [
      'uses' => '\Controllers\FoController@show',
      'as' => 'show'
]);

i want to pass a variable(ex, $var1) to that, and then can access to that in the FoController constructor or other controller methods , so i don't like that variable's value shows in the url.
how can i do this? thanks...

Body:
Use a closure and call the controller yourself and pass what ever you want..

Route::get('/', function(){
  $controller = app()->make('FoController');
  return $controller->callAction('show', ['foo' => 'bar', 'ping' => 'pong']);
});


问:
Import existing C++ project into Xcode IDE
I am trying to open an existing C++ open-source library in Xcode to publish it with my own modification/additions. The library is Tesseract-OCR, which does not include a .xcodeproj file.

Since Xcode can function as an IDE, is it possible to open a bunch of files as a single project in Xcode? Is there an easy way to produce an Xcode project?

答: In Xcode8,there is "Xcode->file->add files to...",then choose your files.If you want to add several files at a time,press "Cmd" when you are choosing. </p>

ContentLicense: CC BY-SA 4.0


问:
React Redux deeply nested objects
Say I have a fairly simple nested, fetched object.

It contains many pieces of information and the schema is fixed.

Some items are nested such:

```<code>obj:{
  one:{
    x: "A",
    y: "B",
    more:{
      z: [1, 2],
      0: "C",
      extra: {
        a1: "b1",
        a2: "b2"
      }
    }
  }
}
</code>```

That's as deep as it goes.

Redux stores this information fine.

Why cant I retrieve one.more.0 or one.more.extra.a1 in react?

I can get one.x.

I can set state with one.more, then retrieve .0, but not .extra.a1.

I understand there are supposed to be reasons for this, but where this simple use-case exists, I find it troubling that it requires hoops to use information which is both accessible and available otherwise.

Any suggestions to get around this which don't involve normalising/redesigning the data to fit the package?

Ideal world: this.props.aReducer.one.more.extra.a1

Many thanks

EDIT*
Is this possible, or must such nested values be knit together pre-render:

```<code>render(){
  return(
    <div>
      {this.props.aReducer.one.more.extra.a1}<br />
    </div>
  )
}
</code>```

答:
The issue isn't with the deeply nested object, but more likely with the defaults of your state or lack of validation. In order to render one.more.extra.a1 each part of the path must exist, ie one must be an object with more as an object with extra as an object (extra doesn't have to have an a1 property to render properly as it would just return undefined instead of throwing an error). Trying to get a property on undefined will always throw an error. This typically means the state wasn't properly initialized or you aren't checking to make sure each part of the path exists.

One way to check each part of the path:

```<code>var a1 = 'Some default value';
if (one && one.more && one.more.extra) {
  a1 = one.more.extra.a1;
}
</code>```

Another option is to use something like lodash's _.get link which does this check for you.

Title: React Redux deeply nested objects

Body:
Say I have a fairly simple nested, fetched object.

It contains many pieces of information and the schema is fixed.

Some items are nested such:

obj:{
  one:{
    x: "A",
    y: "B",
    more:{
      z: [1, 2],
      0: "C",
      extra: {
        a1: "b1",
        a2: "b2"
      }
    }
  }
}

That's as deep as it goes.

Redux stores this information fine.

Why cant I retrieve one.more.0 or one.more.extra.a1 in react?

I can get one.x.

I can set state with one.more, then retrieve .0, but not .extra.a1.

I understand there are supposed to be reasons for this, but where this simple use-case exists, I find it troubling that it requires hoops to use information which is both accessible and available otherwise.

Any suggestions to get around this which don't involve normalising/redesigning the data to fit the package?

Ideal world: this.props.aReducer.one.more.extra.a1

Many thanks

EDIT*
Is this possible, or must such nested values be knit together pre-render:

render(){
  return(

      {this.props.aReducer.one.more.extra.a1}

  )
}

Body:
The issue isn't with the deeply nested object, but more likely with the defaults of your state or lack of validation. In order to render one.more.extra.a1 each part of the path must exist, ie one must be an object with more as an object with extra as an object (extra doesn't have to have an a1 property to render properly as it would just return undefined instead of throwing an error). Trying to get a property on undefined will always throw an error. This typically means the state wasn't properly initialized or you aren't checking to make sure each part of the path exists.

One way to check each part of the path:

var a1 = 'Some default value';
if (one && one.more && one.more.extra) {
  a1 = one.more.extra.a1;
}

Another option is to use something like lodash's _.get link which does this check for you.


问:
wordpress css editor doesn't work
some part of my css code written in wordpress editor dedicated for mobile version of a website does not work and it doesn't appear in inspect page dedicated

i would like for my table to have horizontal scroll when used by mobile phone

```<code>@media (max-width: 768px) {

.gem-textbox-content {
padding-right: 30px !important;
}

.vc_tta.vc_general.vc_tta-accordion .vc_tta-panel-body {
padding: 25px;
}

/*form here forward code doesn't word*/
.gem-table .gem-table-responsive .gem-table-style-1 .row-headers {
    display: block !important;
    overflow-x: scroll !important;
}

.tabletolist .rh .nrh {
    display:none !important;
}

table {
display:block !important;
}

}
</code>```

and when i write this code directly in dev console it works, but when i write it in wp css editor it doesnt, i put !important to overwrite inline css

答:
You should change the version number in your enqueue code (usually in functions.php for themes) so that the style sheet is reloaded.

```<code>    wp_enqueue_style( 'my_styles', plugins_url( 'mystyles.css' , dirname(__FILE__) ), array(), 5.52);
</code>```

In the above example, I would change 5.52 to 5.53 to trigger a style change.

```<code>    wp_enqueue_style( 'my_styles', plugins_url( 'mystyles.css' , dirname(__FILE__) ), array(), 5.53);
</code>```

Title: wordpress css editor doesn't work

Body:
some part of my css code written in wordpress editor dedicated for mobile version of a website does not work and it doesn't appear in inspect page dedicated

i would like for my table to have horizontal scroll when used by mobile phone

@media (max-width: 768px) {

.gem-textbox-content {
padding-right: 30px !important;
}

.vc_tta.vc_general.vc_tta-accordion .vc_tta-panel-body {
padding: 25px;
}

/*form here forward code doesn't word*/
.gem-table .gem-table-responsive .gem-table-style-1 .row-headers {
    display: block !important;
    overflow-x: scroll !important;
}

.tabletolist .rh .nrh {
    display:none !important;
}

table {
display:block !important;
}

}

and when i write this code directly in dev console it works, but when i write it in wp css editor it doesnt, i put !important to overwrite inline css

Body:
You should change the version number in your enqueue code (usually in functions.php for themes) so that the style sheet is reloaded.

    wp_enqueue_style( 'my_styles', plugins_url( 'mystyles.css' , dirname(__FILE__) ), array(), 5.52);

In the above example, I would change 5.52 to 5.53 to trigger a style change.

    wp_enqueue_style( 'my_styles', plugins_url( 'mystyles.css' , dirname(__FILE__) ), array(), 5.53);


问:
Code coverage of just my feature branch
I'm implementing new feature to legacy (poorly tested) system.
I'm working in separate feature branch and I would like to have my new code fully covered. Is there any tool available, that computes the code coverage, but only for diff between my branch and other specified (master, for example).

I'm using C# and git, but I'm ok with tool for any other platform.

答:
The approach I would take is this:

(1) Run a code coverage tool for the master/trunk code (e.g. Open Cover). If this is 0% for the legacy just add an arbitrary test to make it non-zero (0.001% will suffice).

(2) Repeat for your feature branch. If the percentage stays the same or increases then you have made an improvement, if the percentage decreases you've made things worse.

I realise this approach doesn't ensure full 100% coverage of new code in your feature branch (please note that 100% coverage is widely accepted as not a wise investment of time) but you do get code coverage into your master trunk code, which can be used to drive forward a better rest regime in the long run.

Title: Code coverage of just my feature branch


问:
User Control creating problem in Asp.Net MVC 2
Im facing a problem. I have a listing page in which i list all the links and for searching purpose i render the form in

```<code>Ajax.BeginForm("InitializeUserSearch", new AjaxOptions {UpdateTargetId="divGrid" })
</code>```

and in divGrid the resultant records displays. In Controller if the session expires then i redirect it to login view

```<code>if (!SessionAlive)
{
return RedirectToAction("Login", "UserLogin");
}
</code>```

The problem is when session expires it renders the View in that user control and it looks like a new page in main page. What may be the problem?
For reference im attaching the screenshot after session expires
Im using Asp.Net-MVC 2

答:
If you redirect in an AJAX invoked action it will most probably return an entire HTML page whereas you need to return only an HTML partial. After checking for session expiration instead of redirect you could return a partial view containing the login partial:</p>

```<code>if (!SessionAlive)
{
    return PartialView("~/Login/UserLogin.ascx");
}
</code>```

Body:
Im facing a problem. I have a listing page in which i list all the links and for searching purpose i render the form in

Ajax.BeginForm("InitializeUserSearch", new AjaxOptions {UpdateTargetId="divGrid" })

and in divGrid the resultant records displays. In Controller if the session expires then i redirect it to login view

if (!SessionAlive)
{
return RedirectToAction("Login", "UserLogin");
}

The problem is when session expires it renders the View in that user control and it looks like a new page in main page. What may be the problem?
For reference im attaching the screenshot after session expires
Im using Asp.Net-MVC 2

Body:
If you redirect in an AJAX invoked action it will most probably return an entire HTML page whereas you need to return only an HTML partial. After checking for session expiration instead of redirect you could return a partial view containing the login partial:

if (!SessionAlive)
{
    return PartialView("~/Login/UserLogin.ascx");
}


答:
[Update]
A user @Ace points out, you might be using and old version of Angular. You need to declare restrict: 'EA' when you return to make it work.

Also, and just in case, if you ran your code and get a cross origin error in the console. Here AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https says it is because you are trying to load an html template from the browser. You need to use something like MAMP.

Title: Angular JS Custom Directive not working as element tag


问:
Number to Words in Java
I am struggling while doing this programme on BlueJ. Here is my code:

```<code>public class NumberToWords {
    public static void main(String[] args) {
        System.out.print("Number: ");
        int value = In.nextInt();
        int onesDigit;
        int tensDigit;
        String [] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
            "eleven", "tweleve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

        String [] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

        String [] hundreds = {"one hundred", "two hundred", "three hundred", "four hundred", "five hundred",
            "six hundred", "seven hundred", "eight hundred", "nine hundred" };
  while(value != -1)
 {
   if (value < 20)
    {

        String result = ones[value];
        System.out.println("" + result);
        value = In.nextInt();
    }
   if (value > 20 && value < 100)
    {
        tensDigit = value/10;
        onesDigit = value%10;
        System.out.print("" + ones[onesDigit] + " " + tens[tensDigit]);
        value = In.nextInt();

    }
 }

}
}
</code>```

So my problem is when I executed this it only appears word "Number" on my screen once when I entered the first number. For example:
Number: 1 => one and
2 => two
Now I want "Number: 2" will print out 2. Can someone have a look if anything is wrong with my code. Thanks!

答:
The following code should help you to get desired output:</p>

```<code>    public class NumberToWords  {
        public static void main(String[] args) {

            int onesDigit;
            int tensDigit;
            String [] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                "eleven", "tweleve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

            String [] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

            String [] hundreds = {"one hundred", "two hundred", "three hundred", "four hundred", "five hundred",
                "six hundred", "seven hundred", "eight hundred", "nine hundred" };
            System.out.print("Number: ");
          int value = In.nextInt();
      while(value != -1)
     {

       if (value < 20)
        {

            String result = ones[value];
            System.out.println("" + result);
            System.out.print("Number: ");
            value = In.nextInt();
        }
       if (value > 20 && value < 100)
        {
            tensDigit = value/10;
            onesDigit = value%10;
            System.out.print("" + ones[onesDigit] + " " + tens[tensDigit]);
            System.out.print("Number: ");
            value = In.nextInt();

        }
     }

    }
    }
</code>```

Title: Number to Words in Java

Body:
I am struggling while doing this programme on BlueJ. Here is my code:

public class NumberToWords {
    public static void main(String[] args) {
        System.out.print("Number: ");
        int value = In.nextInt();
        int onesDigit;
        int tensDigit;
        String [] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
            "eleven", "tweleve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

        String [] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

        String [] hundreds = {"one hundred", "two hundred", "three hundred", "four hundred", "five hundred",
            "six hundred", "seven hundred", "eight hundred", "nine hundred" };
  while(value != -1)
 {
   if (value < 20)
    {

        String result = ones[value];
        System.out.println("" + result);
        value = In.nextInt();
    }
   if (value > 20 && value < 100)
    {
        tensDigit = value/10;
        onesDigit = value%10;
        System.out.print("" + ones[onesDigit] + " " + tens[tensDigit]);
        value = In.nextInt();

    }
 }

}
}

So my problem is when I executed this it only appears word "Number" on my screen once when I entered the first number. For example:
Number: 1 => one and
2 => two
Now I want "Number: 2" will print out 2. Can someone have a look if anything is wrong with my code. Thanks!

Body:
The following code should help you to get desired output:

    public class NumberToWords  {
        public static void main(String[] args) {

            int onesDigit;
            int tensDigit;
            String [] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                "eleven", "tweleve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

            String [] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

            String [] hundreds = {"one hundred", "two hundred", "three hundred", "four hundred", "five hundred",
                "six hundred", "seven hundred", "eight hundred", "nine hundred" };
            System.out.print("Number: ");
          int value = In.nextInt();
      while(value != -1)
     {

       if (value < 20)
        {

            String result = ones[value];
            System.out.println("" + result);
            System.out.print("Number: ");
            value = In.nextInt();
        }
       if (value > 20 && value < 100)
        {
            tensDigit = value/10;
            onesDigit = value%10;
            System.out.print("" + ones[onesDigit] + " " + tens[tensDigit]);
            System.out.print("Number: ");
            value = In.nextInt();

        }
     }

    }
    }


问:
How can I color a graph (vertices and edges) with excel data?
I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices.

Can anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it?

THANKS!

答:
If you have the x and y values you can plot them directly on a worksheet.  The following is an example that randomly generates x and y coordinates for 5 points.  A small filled circle is drawn at each point.  A line is drawn between the previous and the next point forming a closed loop.

To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria.

vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray.

```<code>Option Explicit

Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long)
  With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = c
  End With
End Sub

Sub drawNode(r As Double, x As Double, y As Double, c As Long)
  With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r)
    .Fill.ForeColor.RGB = c
  End With
End Sub

Sub ConnectedOverLappingLoop()
  Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double
  Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double
  Dim radius As Double
  Dim vbGray As Long, clr As Long

  xMax = 200
  yMax = 200
  radius = 5
  vbGray = RGB(150, 150, 150)

  xFrm = Rnd() * xMax
  yFrm = Rnd() * yMax
  x1 = xFrm
  y1 = yFrm
  clr = vbBlue

  drawNode radius, x1, y1, vbBlue

  Dim i As Integer
  For i = 1 To 5:
    xTo = Rnd() * xMax
    yTo = Rnd() * yMax

    drawNode radius, xTo, yTo, vbBlue
    drawALine xFrm, yFrm, xTo, yTo, clr
    xFrm = xTo
    yFrm = yTo

    If clr = vbBlue Then
       clr = vbGray
    Else
       clr = vbBlue
    End If

  Next
  drawALine xFrm, yFrm, x1, y1, clr

End Sub
</code>```

Body:
If you have the x and y values you can plot them directly on a worksheet.  The following is an example that randomly generates x and y coordinates for 5 points.  A small filled circle is drawn at each point.  A line is drawn between the previous and the next point forming a closed loop.

To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria.

vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray.

Option Explicit

Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long)
  With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = c
  End With
End Sub

Sub drawNode(r As Double, x As Double, y As Double, c As Long)
  With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r)
    .Fill.ForeColor.RGB = c
  End With
End Sub

Sub ConnectedOverLappingLoop()
  Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double
  Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double
  Dim radius As Double
  Dim vbGray As Long, clr As Long

  xMax = 200
  yMax = 200
  radius = 5
  vbGray = RGB(150, 150, 150)

  xFrm = Rnd() * xMax
  yFrm = Rnd() * yMax
  x1 = xFrm
  y1 = yFrm
  clr = vbBlue

  drawNode radius, x1, y1, vbBlue

  Dim i As Integer
  For i = 1 To 5:
    xTo = Rnd() * xMax
    yTo = Rnd() * yMax

    drawNode radius, xTo, yTo, vbBlue
    drawALine xFrm, yFrm, xTo, yTo, clr
    xFrm = xTo
    yFrm = yTo

    If clr = vbBlue Then
       clr = vbGray
    Else
       clr = vbBlue
    End If

  Next
  drawALine xFrm, yFrm, x1, y1, clr

End Sub


问:
No route matches [POST] "/account/new"
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

```<code><%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
</code>```

ROUTES

```<code>account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy
</code>```

ROUTES.RB

```<code>resources :account
</code>```

ACCOUNT CONTROLLER:

```<code>class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end
</code>```

NEW.HTML.ERB

```<code><div class="plans">
  <h1>New Account Plan</h1>

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
    <div class="plans__trial">
      <h3>Trial</h3>
      <p>1 Worker</p>
      <p>1 Assignment</p>

      <p class="price">Price: Free</p>

      <label>
        <%= form.submit "Select", name: "trial", class: "button" %>
      </label>
    </div>

    <div class="plans__tier-1">
      <h3>Tier 1</h3>
      <p>Unlimited Workers</p>
      <p>Unlimited Assignments</p>

      <p class="price">Price: $9.00</p>

      <label>
        <input type="radio" required  />
        <a href="" class="button">Select</a>
      </label>
    </div>

    <div class="cc-fields">
      <%= render partial: "shared/cc-fields" %>
    </div>
    <%= form.submit name: "tier_1" %>
  <% end %>
</div>
</code>```

What am I doing wrong. Should it hit the create action? It's not currently.

答:
It's right in your routes.

You're POSTing to the NEW route.  That doesn't work.  New is where you render a form for users to enter data.  Create is the action that will accept that data posted to it.

So change this:

```<code><%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>
</code>```

To this:

```<code><%= form_for @account, url: account_path, html: { method: :post }  do |form| %>
</code>```

Simplified:

```<code><%= form_for @account do |form| %>
</code>```

As long as your @account is a Account.new, which it is, it should work.

Title: No route matches [POST] "/account/new"

Body:
I'm trying to create a new account. but for some reason I'm getting this error when trying to submit the form No route matches [POST] "/account/new". Here is my form_for:

<%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

ROUTES

account_index GET    /account(.:format)                                      account#index
                                  POST   /account(.:format)                                      account#create
                      new_account GET    /account/new(.:format)                                  account#new
                     edit_account GET    /account/:id/edit(.:format)                             account#edit
                          account GET    /account/:id(.:format)                                  account#show
                                  PATCH  /account/:id(.:format)                                  account#update
                                  PUT    /account/:id(.:format)                                  account#update
                                  DELETE /account/:id(.:format)                                  account#destroy

ROUTES.RB

resources :account

ACCOUNT CONTROLLER:

class AccountController < ApplicationController
  def new
    @account = Account.new
  end

  def create
    binding.pry
    interactor = CreateAccount.call(
      params: account_params,
      user: current_user
    )

    if interactor.success?
      redirect_to pages_dashboard_path
    else
      render :new
    end
  end

  private

  def account_params
    params.require(:account).permit(:name)
  end
end

NEW.HTML.ERB

New Account Plan

  <%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

Trial

1 Worker

1 Assignment

Price: Free

        <%= form.submit "Select", name: "trial", class: "button" %>

Tier 1

Unlimited Workers

Unlimited Assignments

Price: $9.00

        <input type="radio" required  />
        Select

      <%= render partial: "shared/cc-fields" %>

    <%= form.submit name: "tier_1" %>
  <% end %>

What am I doing wrong. Should it hit the create action? It's not currently.

Body:
It's right in your routes.

You're POSTing to the NEW route.  That doesn't work.  New is where you render a form for users to enter data.  Create is the action that will accept that data posted to it.

So change this:

<%= form_for @account, url: new_account_path, html: { method: :post }  do |form| %>

To this:

<%= form_for @account, url: account_path, html: { method: :post }  do |form| %>

Simplified:

<%= form_for @account do |form| %>

As long as your @account is a Account.new, which it is, it should work.