问:
Is it possible in DynamoDb to get all the items with a given Sort Key?
As primary key I have an id for a recipe and the sort key is the type of food (breakfast, meal, snack, etc).

Is there a way with scan or query to get all the items with a given sort key?

答:
As others have pointed in the comments, you can't query a sort key in the sense that there is no operation that gives a list of items that have the same sort key.

In fact, the whole reason for a sort key is generally to order items in a particular partition.

Putting the two together, what you need is a way to partition the items by the food type and then query on that. Enter the Global Secondary Index (GSI).

With the help of a GSI you can index the data in your table in a way that the food type becomes the partition key, and some other attribute becomes the sort key. Then, getting all the items that match a particular food type becomes possible with a Query.

There are a few things to keep in mind:

a GSI is like another table: it consumes capacity that you will be charged for

a GSI is eventually consistent, meaning changes in the table could take a bit of time before being reflected in the GSI

if you end up creating a GSI where the choice of partition key results in very large partitions, it can lead to throttling (reduced throughput) if any one partition receives a lot of requests

Some more guidelines: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-general.html

But before you start creating GSIs, consider for a moment the schema of your table: your choice of partition key seems less than ideal. On the one hand, using the recipe id as the partition key is great because it probably results in very good spread of data but on the other hand, you have no ability to use queries on your table without creating GSIs.

Instead of recipe id as the partition key, consider creating a partition key composed of food type, and perhaps another attribute. This way, you can actually query on food type, or perhaps issue several queries to retrieve all items of a particular food type.


来源: stackexchange

问:
MODX - what can be improved?
I'm researching MODX as a CMS and found this interview with the creator of FoxyCart.
He really gives MODX a lot of positive comments and when asked about improving MODX he pointed out the following:

User management can be awkward, and
  some things related to webusers have
  never really been brought current.
  (Newspublisher can’t handle TVs;
  Weblogin is temperamental and not easy
  to customize; Webusers need “TVs” for
  additional fields.)

Can others on this site shed some light on this? What other kind of user management issues are there?

What are some areas of MODX that people think should be improved?

I'm trying to figure out whether to go with MODX or not. I've been reading a lot of positive things about it and want to make sure that I get the whole picture.

答:
Brett (Foxycart) is talking about MODX Evolution, the older codebase, and makes reference to add-ons, which are (for the most part) independently authored - so definitely improvable. MODX Revolution is the newer version, currently at 2.1 RC3. I've worked with everything from Enterprise CRMs (Tridion, Rhythmyx, Mediasurface as was) to other FOSS systems Silverstripe, Wordpress etc, and it is by far the most intelligently put together and executed of the lot.

It has some niggles - the permissions system is overly abstract and complex, it lacks some plug-and-play features, fine-tuning performance is a bit of a black art, and it doesn't have the ecosystem support of bigger players like Drupal or Joomla (or even WP). But the peer support is fantastic, the core team are committed and talented, and with a modicum of php and willingness to RTFM you can make it do almost anything with MODX.

Strongly recommended.

ContentLicense: CC BY-SA 2.5

Title: MODX - what can be improved?

ContentLicense: CC BY-SA 3.0


问:
IS Azure subscript required to use power BI embedded ServicePrincipal login?
```<code>IS Azure subscript required to use power BI embedded Service Principal login?
I dont have subscript and I am trying to login using Service Principal login ,
it give me Unauthorized.
</code>```

I am following this below link.

https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#assign-the-application-to-a-role

答: Authenticating with service principal works and requires the new workspaces experience, i.e. you need Power BI Pro account for that. But you don't need to pay for separate Azure subscription. In Azure portal you need to create a security group and add the registered application in it, which you can do for free.</p>

ContentLicense: CC BY-SA 4.0

Body:
IS Azure subscript required to use power BI embedded Service Principal login?
I dont have subscript and I am trying to login using Service Principal login ,
it give me Unauthorized.

I am following this below link.

https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#assign-the-application-to-a-role


问:
Cannot create release apk in Android Studio 2.2
I followed come tutorials about building my apk file.
I can generate the debug apk file, but not the release one.

But, when I try to generate a signed apk, i get the following error message:

Error:(53, 19) No resource found that matches the given name (at
  'menu' with value '@menu/activity_main_drawer').

Error:Execution failed for task ':app:processReleaseResources'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
    'C:\Users\Diego\AppData\Local\Android\sdk\build-tools\23.0.3\aapt.exe''
    finished with non-zero exit value 1

I believe there is nothing wrong with my activity_main_drawer.xml file:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_distance"
            android:icon="@android:drawable/ic_menu_directions"
            android:title="Distance Threshold" />
        <item
            android:id="@+id/nav_clear_map"
            android:icon="@android:drawable/ic_menu_delete"
            android:title="Clear Map" />
    </group>
</menu>
</code>```

Here my folder structure:

Folder structure with res folder on detail:

Could you guys help me how to search for a solution?

Thank you

答:
```<code>release {
            lintOptions {
                checkReleaseBuilds false
                disable 'MissingTranslation'
            }
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
</code>```

Body:
I followed come tutorials about building my apk file.
I can generate the debug apk file, but not the release one.

But, when I try to generate a signed apk, i get the following error message:

Error:(53, 19) No resource found that matches the given name (at
  'menu' with value '@menu/activity_main_drawer').

Error:Execution failed for task ':app:processReleaseResources'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
    'C:\Users\Diego\AppData\Local\Android\sdk\build-tools\23.0.3\aapt.exe''
    finished with non-zero exit value 1

I believe there is nothing wrong with my activity_main_drawer.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_distance"
            android:icon="@android:drawable/ic_menu_directions"
            android:title="Distance Threshold" />
        <item
            android:id="@+id/nav_clear_map"
            android:icon="@android:drawable/ic_menu_delete"
            android:title="Clear Map" />
    </group>
</menu>

Here my folder structure:

Folder structure with res folder on detail:

Could you guys help me how to search for a solution?

Thank you


问:
PyAudio in pycharm
I have written a program for speech to text in which I use speech recognition by pycharm ask for PyAudio so I tried to do so . But PyAudio in pycharm is not getting installed</p>

答:
I guess you need to configure a Python interpreter

https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html

Title: PyAudio in pycharm


问:
How to Create and Use Enum in Mongoose
I am trying to create and use an enum type in Mongoose. I checked it out, but I'm not getting the proper result. I'm using enum in my program as follows:

My schema is:

```<code>var RequirementSchema = new mongooseSchema({
   status: {
        type: String,
        enum : ['NEW,'STATUS'],
        default: 'NEW'
    },
})
</code>```

But I am little bit confused here, how can I put the value of an enum like in Java NEW("new"). How can I save an enum in to the database according to it's enumerable values. I am using it in express node.js.

答:
From the docs

Mongoose has several inbuilt validators. Strings have enum as one of the validators.
So enum creates a validator and checks if the value is given in an array.
E.g:

const userSchema = new mongoose.Schema({
   userType: {
        type: String,
        enum : ['user','admin'],
        default: 'user'
    },
})

```

Title: How to Create and Use Enum in Mongoose

Body:
I am trying to create and use an enum type in Mongoose. I checked it out, but I'm not getting the proper result. I'm using enum in my program as follows:

My schema is:

var RequirementSchema = new mongooseSchema({
   status: {
        type: String,
        enum : ['NEW,'STATUS'],
        default: 'NEW'
    },
})

But I am little bit confused here, how can I put the value of an enum like in Java NEW("new"). How can I save an enum in to the database according to it's enumerable values. I am using it in express node.js.


问:
Android Activity lifecycle issue
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }
</code>```

In Cart activity when I press a button it comes to activity Home.

For That

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }
</code>```

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?

答:
How to solve what? That is the intended behavior of activities. Nevertheless, if you do not want that the methods in your onCreate method are called, you could use a flag like this:</p>

```<code>public class YourActivity extends Activity {

   private boolean firstStart = true;

   public void OnCreate(...) {

      if (firstStart) {
         //do your stuff here
         firstStart = false;
      }

   }
}
</code>```

Title: Android Activity lifecycle issue

Body:
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

 public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }

In Cart activity when I press a button it comes to activity Home.

For That

 public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?

Body:
How to solve what? That is the intended behavior of activities. Nevertheless, if you do not want that the methods in your onCreate method are called, you could use a flag like this:

public class YourActivity extends Activity {

   private boolean firstStart = true;

   public void OnCreate(...) {

      if (firstStart) {
         //do your stuff here
         firstStart = false;
      }

   }
}

OwnerDisplayName: anon


问:
Cancel REST service when request is cancelled
I have a snippet from angular UI that will call myService.getNames() when user types in a letter in the field.  The switchMap will cancel the previous request whenever the user types in another letter in the field.

```<code>.pipe(
    debounceTime(500),
    switchMap(value => this.myService.getNames(value))
)
</code>```

This service will call the REST endpoint http://localhost:8080/listing?value=<value_sent_from_client>.  The query for retrieving the list of names takes some time to complete.  If the user edited the field 3 times, there will be 2 cancelled requests and 1 on-going request.

On the server side, how do you cancel the 2 previously running queries? Or will they get cancelled automatically?

答:
You cannot cancel request on server side. The solution might be in more sophisticated algorithm, like:

each request are putting into queue and return immediately not waiting for processing to be finished (storing in DB, etc.)

queue replace previous items if new items are present from same user

client subscribes to updates from server via web-sockets

Or any other approach.

Body:
I have a snippet from angular UI that will call myService.getNames() when user types in a letter in the field.  The switchMap will cancel the previous request whenever the user types in another letter in the field.

.pipe(
    debounceTime(500),
    switchMap(value => this.myService.getNames(value))
)

This service will call the REST endpoint http://localhost:8080/listing?value=<value_sent_from_client>.  The query for retrieving the list of names takes some time to complete.  If the user edited the field 3 times, there will be 2 cancelled requests and 1 on-going request.

On the server side, how do you cancel the 2 previously running queries? Or will they get cancelled automatically?


问:
load routes from api and import views dynamically
The most of my routes are protected and require permissions to access them. When the user signed in successfully my Navbar component makes an API call and retrieves a bunch of routes the user is able to access.

After that I add all the view files matching to the routes to the navbar.

This is an example code showing the process

```<code><template>
  <div>
    <router-link
      v-for="navItem in navItems"
      :key="navItem.title"
      :to="navItem.url"
    >{{ navItem.title }}</router-link>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      navItems: []
    };
  },
  created: async function() { // Setup the router here
    this.navItems = [
      // !!! API CALL !!!
      {
        title: "Dashboard",
        url: "/Dashboard"
      },
      {
        title: "Users",
        url: "/users/Users"
      },
      {
        title: "Groups",
        url: "/groups/Groups"
      }
    ];

    const routes = await this.navItems.map(async navItem => {
      const { url } = navItem;

      return {
        path: url,
        component: await import(`../views${url}.vue`)
      };
    });

    this.$router.addRoutes(routes);
  }
};
</script>
</code>```

Unfortunately I get this error

Uncaught (in promise) Error: [vue-router] "path" is required in a
  route configuration.

but as you can see in the example code this attribute is set. I created an sample project here

https://codesandbox.io/s/vue-routing-example-i2znt

If you call this route

https://i2znt.codesandbox.io/#/Dashboard

I would expect the router to render the Dashboard.vue file.

答:
the routes array that you build doesn't contains your routes objects.
It's an array of promises.

you should do something like

```<code>Promise.all(routes).then(resolvedRoutes => {
    this.$router.addRoutes(resolvedRoutes)
})
</code>```

Body:
The most of my routes are protected and require permissions to access them. When the user signed in successfully my Navbar component makes an API call and retrieves a bunch of routes the user is able to access.

After that I add all the view files matching to the routes to the navbar.

This is an example code showing the process

<template>

    <router-link
      v-for="navItem in navItems"
      :key="navItem.title"
      :to="navItem.url"
    >{{ navItem.title }}</router-link>

</template>

Unfortunately I get this error

Uncaught (in promise) Error: [vue-router] "path" is required in a
  route configuration.

but as you can see in the example code this attribute is set. I created an sample project here

https://codesandbox.io/s/vue-routing-example-i2znt

If you call this route

https://i2znt.codesandbox.io/#/Dashboard

I would expect the router to render the Dashboard.vue file.

Body:
the routes array that you build doesn't contains your routes objects.
It's an array of promises.

you should do something like

Promise.all(routes).then(resolvedRoutes => {
    this.$router.addRoutes(resolvedRoutes)
})


问:
Is there any way to update my .html file if i have used funtion names and parameters in .js file which will be mixed to 'a, b, c,d..'?
I want to compress and mix my js code, but i find i have used some function and parameter in my html file and they will not work if i mix the names in js file.

Here is the js code in the begining:

```<code>function Add(str1, str2)
{
    var strSum = str1 + str2;
    return strSum;
}
var sum = Add(1,2);
</code>```

I compress and mix the code by uglifyjs:

```<code>function n(n,r){return n+r}var r=n(1,2);
</code>```

I used 'Add' and 'sum' in my html file:

```<code>var val = Add(2,3);
document.getElementById('BOX1').innerHTML = val;
document.getElementById('BOX2').innerHTML = sum;
</code>```

Do i have to change 'Add' and 'sum' to 'n' and 'r'? Is there any other way to do this?

答: An Identifier(Variable or Function name) do not change when you compress or minify your javascript code. Try minifying your code using javascript-minifier or JSCompresser. I have tried them and they will not change the function names of your code.</p>

Body:
I want to compress and mix my js code, but i find i have used some function and parameter in my html file and they will not work if i mix the names in js file.

Here is the js code in the begining:

function Add(str1, str2)
{
    var strSum = str1 + str2;
    return strSum;
}
var sum = Add(1,2);

I compress and mix the code by uglifyjs:

function n(n,r){return n+r}var r=n(1,2);

I used 'Add' and 'sum' in my html file:

var val = Add(2,3);
document.getElementById('BOX1').innerHTML = val;
document.getElementById('BOX2').innerHTML = sum;

Do i have to change 'Add' and 'sum' to 'n' and 'r'? Is there any other way to do this?


问:
getting back to folder in asp.net
protected void Button1_Click(object sender, EventArgs e)
{
     Response.Redirect("Page2.aspx");
}
this is code to go on .aspx but what if i want to go in Folder in my solution explorer, tried with location but it dont work
Who knows post it.

this is location >
website\admin
-news.aspx
-project.aspx
and i created in news.aspx button go back to admin, and when i hit button location is next > website\admin\admin why he  duplicate admin ?

答:
```<code>Response.Redirect("~/Folder/Page.aspx");
</code>```

The tilde ~ is very useful for redirects, it signifies your site root.  So wherever you are on the site, you can redirect to folders relative to the domain root.  I hope this is what you meant!

Title: getting back to folder in asp.net

Body:
Response.Redirect("~/Folder/Page.aspx");

The tilde ~ is very useful for redirects, it signifies your site root.  So wherever you are on the site, you can redirect to folders relative to the domain root.  I hope this is what you meant!


问:
Undefined variable: posts (View: C:\xampp\htdocs\practiseapp\resources\views\dashboard.blade.php)
I am new to laravel in here i am just creating a simple app in which user can login and register and after that write post in dashboard after logging in, I am trying to display user posts data in dashboard which is saved in database, But i am getting this error:

Undefined variable: posts (View: C:\xampp\htdocs\practiseapp\resources\views\dashboard.blade.php)

i think i have defined the posts,I can't figure out what's wrong,Any help would be appreciated Thanks....

My dashboard:

```<code>@extends('layout.master')

@section('content')
<div class="col-sm-6 col-sm-offset-3">
    <header><h3>What do you wanna say</h3></header>
    <form method="post" action="{{route('post.create')}}">
        {{csrf_field()}}
        <div class="panel-body">
        <div class="form-group">
            <textarea class="form-control" name="body" id="body" rows="5" placeholder="Enter your post">

            </textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create post</button>

    </form>
    </div>

</div>

<section class="row-posts">
    <div class="col-md-6 col-sm-offset-3">
        <header><h3>Other people posts</h3></header>

        @foreach($posts as $post)
        <article class="post">
            <p>{{ $post->body }}</p>
            <div class="info">
                posted by {{ $post->user->name}} on {{$post->created_at}}
            </div>
            <div class="interaction">
                <a href="#">Like</a>|
                <a href="#">Disike</a>|
                <a href="#">Edit</a>|
                <a href="#">Delete</a>
            </div>
        </article>
        @endforeach

    </div>

</section>
@endsection
</code>```

PostController.php

```<code><?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Post;
use App\UserTypes;

use Auth;
use Hashids;
use Redirect;
use Illuminate\Http\Request;
use Hash;

class PostController extends Controller
{

    public function show()
    {
        //Fetching all the posts from the database
        $posts = Post::all();
        return view('dashboard',['posts'=> $posts]);
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'body' => 'required'

        ]);

        $post = new Post;
        $post->body = $request->body;
        $request->user()->posts()->save($post);

        return redirect()->route('dashboard');
    }
}
</code>```

答:
Try the below code,</p>

```<code><?php

    namespace App\Http\Controllers;

    use App\Http\Requests;
    use App\Post;
    use App\UserTypes;

    use Auth;
    use Hashids;
    use Redirect;
    use Illuminate\Http\Request;
    use Hash;

    class PostController extends Controller
    {

        public function show()
        {
            //Fetching all the posts from the database
            $posts = Post::get();
            return view('dashboard', compact('posts'));
        }

        public function store(Request $request)
        {
            $this->validate($request,[
                'body' => 'required'

            ]);

            $post = new Post;
            $post->body = $request->body;
            $request->user()->posts()->save($post);

            return redirect()->route('dashboard');
        }
    }
</code>```

Body:
I am new to laravel in here i am just creating a simple app in which user can login and register and after that write post in dashboard after logging in, I am trying to display user posts data in dashboard which is saved in database, But i am getting this error:

Undefined variable: posts (View: C:\xampp\htdocs\practiseapp\resources\views\dashboard.blade.php)

i think i have defined the posts,I can't figure out what's wrong,Any help would be appreciated Thanks....

My dashboard:

@extends('layout.master')

@section('content')

What do you wanna say

    <form method="post" action="{{route('post.create')}}">
        {{csrf_field()}}

            <textarea class="form-control" name="body" id="body" rows="5" placeholder="Enter your post">

            </textarea>

        <button type="submit" class="btn btn-primary">Create post</button>

    </form>

Other people posts

        @foreach($posts as $post)

{{ $post->body }}

                posted by {{ $post->user->name}} on {{$post->created_at}}

                Like|
                Disike|
                Edit|
                Delete

        @endforeach

@endsection

PostController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Post;
use App\UserTypes;

use Auth;
use Hashids;
use Redirect;
use Illuminate\Http\Request;
use Hash;

class PostController extends Controller
{

    public function show()
    {
        //Fetching all the posts from the database
        $posts = Post::all();
        return view('dashboard',['posts'=> $posts]);
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'body' => 'required'

        ]);

        $post = new Post;
        $post->body = $request->body;
        $request->user()->posts()->save($post);

        return redirect()->route('dashboard');
    }
}

Body:
Try the below code,

<?php

    namespace App\Http\Controllers;

    use App\Http\Requests;
    use App\Post;
    use App\UserTypes;

    use Auth;
    use Hashids;
    use Redirect;
    use Illuminate\Http\Request;
    use Hash;

    class PostController extends Controller
    {

        public function show()
        {
            //Fetching all the posts from the database
            $posts = Post::get();
            return view('dashboard', compact('posts'));
        }

        public function store(Request $request)
        {
            $this->validate($request,[
                'body' => 'required'

            ]);

            $post = new Post;
            $post->body = $request->body;
            $request->user()->posts()->save($post);

            return redirect()->route('dashboard');
        }
    }


问:
golang check tcp port open
I need to check if remote address has specific TCP ports open or not.
I have chosen to use golang for this purpose.
Here is my attempt so far:

```<code>func raw_connect(host string, ports []string) {
  for _, port := range ports {
     timeout := time.Second
     conn, err := net.DialTimeout("tcp", host + ":" + port, timeout)
     if err != nil {
        _, err_msg := err.Error()[0], err.Error()[5:]
        fmt.Println(err_msg)
     } else {
        msg, _, err := bufio.NewReader(conn).ReadLine()
        if err != nil {
           if err == io.EOF {
              fmt.Print(host + " " + port + " - Open!\n")
           }
        } else {
           fmt.Print(host + " " + port + " - " + string(msg))
        }
        conn.Close()
     }
   }
 }
</code>```

This is working just fine for TCP port when application (such as SSH) returns first a string, I read it and print it with no time.

However, when the application above TCP is waiting for command from the client first (such as HTTP), there is a timeout (if err == io.EOF clause).

This timeout is quite long. I would need to know immediately if the port is open or not.

Is there a more suitable technique for this purpose ?

Many thanks!

答:
To check the port, you can check if the connection was successful. For example:</p>

```<code>func raw_connect(host string, ports []string) {
    for _, port := range ports {
        timeout := time.Second
        conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
        if err != nil {
            fmt.Println("Connecting error:", err)
        }
        if conn != nil {
            defer conn.Close()
            fmt.Println("Opened", net.JoinHostPort(host, port))
        }
    }
}
</code>```

Title: golang check tcp port open

Body:
I need to check if remote address has specific TCP ports open or not.
I have chosen to use golang for this purpose.
Here is my attempt so far:

func raw_connect(host string, ports []string) {
  for _, port := range ports {
     timeout := time.Second
     conn, err := net.DialTimeout("tcp", host + ":" + port, timeout)
     if err != nil {
        _, err_msg := err.Error()[0], err.Error()[5:]
        fmt.Println(err_msg)
     } else {
        msg, _, err := bufio.NewReader(conn).ReadLine()
        if err != nil {
           if err == io.EOF {
              fmt.Print(host + " " + port + " - Open!\n")
           }
        } else {
           fmt.Print(host + " " + port + " - " + string(msg))
        }
        conn.Close()
     }
   }
 }

This is working just fine for TCP port when application (such as SSH) returns first a string, I read it and print it with no time.

However, when the application above TCP is waiting for command from the client first (such as HTTP), there is a timeout (if err == io.EOF clause).

This timeout is quite long. I would need to know immediately if the port is open or not.

Is there a more suitable technique for this purpose ?

Many thanks!

Body:
To check the port, you can check if the connection was successful. For example:

func raw_connect(host string, ports []string) {
    for _, port := range ports {
        timeout := time.Second
        conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
        if err != nil {
            fmt.Println("Connecting error:", err)
        }
        if conn != nil {
            defer conn.Close()
            fmt.Println("Opened", net.JoinHostPort(host, port))
        }
    }
}


问:
Why is 'error: unbound symbol' returned why I run my array comparison algorithm?
Given a list of lists in which the first element of the list is a name and the rest of the elements are integers, I am trying to build an algorithm that compares the similarity of two sub-lists by summing the difference between the elements at each position in the list.  I am using a let statement in this algorithm, and when I try to run it, the following error is returned:

Error: execute: unbound symbol: "arr2" [similarity-arrays, (anon)]

Why does this happen?

Code:

(define (get-list name arr)
  (if (eq? name (car (car arr)))
      (cdr (car arr))
      (get-list name (cdr arr))))
(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
       ((arr2 (get-list name2 arrs))))
        (if (= (length arr1)(length arr2))
          (let ((x1 (car arr1))
                (x2 (car arr2)))
                  (if (= 0 (length arr1))
                    result
                    (similarity-arrays
                      (cdr arr1)
                      (cdr arr2)
                      (+ result (- (car arr1)(car arr2))))))
          #f)))
(define dust
  (list (list 'akko 11 3 7 5 4 1 9 8 10 6 2)
        (list 'Alex 9 7 11 3 6 1 5 4 10 2 8)
        (list 'Aron 11 4 1 2 6 3 7 9 8 10 5)
        (list 'carter 7 3 8 2 5 4 11 9 10 6 1)
        (list 'Connery 10 2 6 4 5 1 7 3 9 11 8)
        (list 'Embryo 11 8 9 6 7 4 2 3 1 10 5)
        (list 'Jaycee 9 1 11 7 10 8 4 2 5 6 3)
        (list 'jeeelm 11 8 5 2 1 6 7 3 9 10 4)
        (list 'Jodast 10 7 4 6 5 1 11 9 8 3 2)
        (list 'KingDolphin 11 4 7 2 6 3 5 9 8 10 1)
        (list 'Knowledge 11 8 2 9 3 1 5 6 4 10 7)
        (list 'ruben 11 1 6 4 7 3 9 5 8 10 2)
        (list 'SickLizard 11 6 7 2 8 3 9 10 5 4 1)
        (list 'XIN 11 3 4 1 8 5 7 9 6 10 2)
        (list 'ZIPF 10 7 11 5 9 3 6 2 4 8 1)))

(similarity-arrays 'Jodast 'Akko dust 0)
```

答:
One thing you need to improve is indentation of your code.
If code is properly indented then it is easier to spot syntax errors.
If your code looks like below, then you have an indentation problem.

```<code>(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
       ((arr2 (get-list name2 arrs))))       ; <- wrong indentation, wrong syntax
        (if (= (length arr1)(length arr2))
          (let ((x1 (car arr1))
                (x2 (car arr2)))
                  (if (= 0 (length arr1))    ; <- wrong indentation
                    result
                    (similarity-arrays
                      (cdr arr1)
                      (cdr arr2)
                      (+ result (- (car arr1)(car arr2))))))
          #f)))
</code>```

This would be properly indented code:

```<code>(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
        ((arr2 (get-list name2 arrs))))      ; <- wrong syntax
    (if (= (length arr1) (length arr2))
        (let ((x1 (car arr1))
              (x2 (car arr2)))
          (if (= 0 (length arr1))
              result
              (similarity-arrays
               (cdr arr1)
               (cdr arr2)
               (+ result (- (car arr1) (car arr2))))))
        #f)))
</code>```

Best to not indent code manually -> use the editor/IDE to do it.

Body:
One thing you need to improve is indentation of your code.
If code is properly indented then it is easier to spot syntax errors.
If your code looks like below, then you have an indentation problem.

(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
       ((arr2 (get-list name2 arrs))))       ; <- wrong indentation, wrong syntax
        (if (= (length arr1)(length arr2))
          (let ((x1 (car arr1))
                (x2 (car arr2)))
                  (if (= 0 (length arr1))    ; <- wrong indentation
                    result
                    (similarity-arrays
                      (cdr arr1)
                      (cdr arr2)
                      (+ result (- (car arr1)(car arr2))))))
          #f)))

This would be properly indented code:

(define (similarity-arrays name1 name2 arrs result)
  (let ((arr1 (get-list name1 arrs))
        ((arr2 (get-list name2 arrs))))      ; <- wrong syntax
    (if (= (length arr1) (length arr2))
        (let ((x1 (car arr1))
              (x2 (car arr2)))
          (if (= 0 (length arr1))
              result
              (similarity-arrays
               (cdr arr1)
               (cdr arr2)
               (+ result (- (car arr1) (car arr2))))))
        #f)))

Best to not indent code manually -> use the editor/IDE to do it.


问:
How to multiply value in datagridview column by a textbox in a button click and get output same column c#
I need to multiply value in Datagrid view by a text box in a button click.
Example
Value in Datagrid view column (Cell [10]) Column Index ["Deposit"] Values 1000, 2000, 300.75
I need to input the number of months into the textbox and click the button and hope a result: Example: textbox value is 2 after button click / Deposit value should be 2000, 4000, 601.50
Note: I need to change these values to the same column ["Deposit"] Cell [10], not another column

See below code i have tried to get output, but it was not working, can anyone help me for this?

```<code>var xs = listA.Exists(listB);
for (int i = 0; i < DataGridView1.Rows.Count; i++)
     {
       double val1, val2, tot;
       double.TryParse(Txtmonth.Text, out val1);
       val2 = Convert.ToDouble(DataGridView1.Rows[i].Cells[10].Value);
       tot = (val1 * val2);

     }
</code>```

答:
try this </p>

```<code>for (int i = 0; i < DataGridView1.Rows.Count; i++)
     {
       double val1, val2;
       double.TryParse(Txtmonth.Text, out val1);
       DataGridView1.Rows[i].Cells[10].Value = Convert.ToDouble(DataGridView1.Rows[i].Cells[10].Value) * val1;
     }
</code>```

Body:
I need to multiply value in Datagrid view by a text box in a button click.
Example
Value in Datagrid view column (Cell [10]) Column Index ["Deposit"] Values 1000, 2000, 300.75
I need to input the number of months into the textbox and click the button and hope a result: Example: textbox value is 2 after button click / Deposit value should be 2000, 4000, 601.50
Note: I need to change these values to the same column ["Deposit"] Cell [10], not another column

See below code i have tried to get output, but it was not working, can anyone help me for this?

var xs = listA.Exists(listB);
for (int i = 0; i < DataGridView1.Rows.Count; i++)
     {
       double val1, val2, tot;
       double.TryParse(Txtmonth.Text, out val1);
       val2 = Convert.ToDouble(DataGridView1.Rows[i].Cells[10].Value);
       tot = (val1 * val2);

     }

Body:
try this

for (int i = 0; i < DataGridView1.Rows.Count; i++)
     {
       double val1, val2;
       double.TryParse(Txtmonth.Text, out val1);
       DataGridView1.Rows[i].Cells[10].Value = Convert.ToDouble(DataGridView1.Rows[i].Cells[10].Value) * val1;
     }


问:
How to reuse a scenario in citrus framework?
I set this testing scenario with citrus framework. Now I'm trying to reuse it in other scenarios.
I'm creating a behavior for each step. My behaviors are mainly http requests

```<code>public class NoProductDocumentValidationScenarioIT {

    private @CitrusResource TestContext parentContext;

    @CitrusEndpoint(name = "todoBasicAuthClient")
    private HttpClient cmsAuthClient;

    @CitrusEndpoint(name = "vdmBasicAuthClient")
    private HttpClient vdmAuthClient;

    @CitrusEndpoint(name = "gvHttpClient")
    private HttpClient gvHttpClient;

    @Test
    @CitrusTest
    public String NoProductDocumentValidation(@CitrusResource TestRunner runner, @CitrusResource TestContext context)
            throws BadNewsMLG2Exception {
        String pdtIdentifier = "EDIT-FR-SVID2-YM9N001479";
        String videoDocument = VideoDocument.setUpVideoDocument("fr", "v1_afptv_sport_broadcast_photos");
        int jobPublicationID = 5;
        // CMS Authentification
        TestBehavior authenticateCMS = new ProductAuthenticationBehavior(cmsAuthClient);
        ApplyTestBehaviorAction authenticateActionCMS = new ApplyTestBehaviorAction(runner, authenticateCMS);
        authenticateActionCMS.doExecute(context);

        // Document Creation
        CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument);
        ApplyTestBehaviorAction createDocAction = new ApplyTestBehaviorAction(runner, createDoc);
        createDocAction.doExecute(context);

        // get document data
        videoDocument = createDoc.getVideoDocument();
        G2VideoDocument g2VideoDocument = ((G2VideoDocument) G2ObjectFactory.parse(videoDocument));
        g2VideoDocument.getProducts();
        String linkToVideoDocument = g2VideoDocument.getLinkToSelf().toString();
        String linkToProject = g2VideoDocument.getLinkToVideoProject().toString();
        String projectID = IrisStringTools.extractIdFromUri(linkToProject);
        String documentID = IrisStringTools.extractIdFromUri(linkToVideoDocument);
        String etag = g2VideoDocument.getEditorialTag();

        // Lock document Metadata
        EditVideoDocumentMetaBehavior lockDocMeta = new EditVideoDocumentMetaBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument, documentID);
        ApplyTestBehaviorAction lockDocMetaAction = new ApplyTestBehaviorAction(runner, lockDocMeta);
        lockDocMetaAction.doExecute(context);
}
}
</code>```

I run this in eclipse as JUnit test.

I thought about using a super class but it didn't work.

```<code>public class ProductDocumentValidationScenarioIT extends NoProductDocumentValidationScenarioIT {

    public String ProductDocumentValidation(@CitrusResource TestRunner runner, @CitrusResource TestContext context)
            throws BadNewsMLG2Exception {
                return something;

    }
}
</code>```

答:
Test behaviors is the way to go here. I suggest to use something like this</p>

```<code>CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument);

runner.applyBehavior(createDoc);
</code>```

Body:
I set this testing scenario with citrus framework. Now I'm trying to reuse it in other scenarios.
I'm creating a behavior for each step. My behaviors are mainly http requests

public class NoProductDocumentValidationScenarioIT {

    private @CitrusResource TestContext parentContext;

    @CitrusEndpoint(name = "todoBasicAuthClient")
    private HttpClient cmsAuthClient;

    @CitrusEndpoint(name = "vdmBasicAuthClient")
    private HttpClient vdmAuthClient;

    @CitrusEndpoint(name = "gvHttpClient")
    private HttpClient gvHttpClient;

    @Test
    @CitrusTest
    public String NoProductDocumentValidation(@CitrusResource TestRunner runner, @CitrusResource TestContext context)
            throws BadNewsMLG2Exception {
        String pdtIdentifier = "EDIT-FR-SVID2-YM9N001479";
        String videoDocument = VideoDocument.setUpVideoDocument("fr", "v1_afptv_sport_broadcast_photos");
        int jobPublicationID = 5;
        // CMS Authentification
        TestBehavior authenticateCMS = new ProductAuthenticationBehavior(cmsAuthClient);
        ApplyTestBehaviorAction authenticateActionCMS = new ApplyTestBehaviorAction(runner, authenticateCMS);
        authenticateActionCMS.doExecute(context);

        // Document Creation
        CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument);
        ApplyTestBehaviorAction createDocAction = new ApplyTestBehaviorAction(runner, createDoc);
        createDocAction.doExecute(context);

        // get document data
        videoDocument = createDoc.getVideoDocument();
        G2VideoDocument g2VideoDocument = ((G2VideoDocument) G2ObjectFactory.parse(videoDocument));
        g2VideoDocument.getProducts();
        String linkToVideoDocument = g2VideoDocument.getLinkToSelf().toString();
        String linkToProject = g2VideoDocument.getLinkToVideoProject().toString();
        String projectID = IrisStringTools.extractIdFromUri(linkToProject);
        String documentID = IrisStringTools.extractIdFromUri(linkToVideoDocument);
        String etag = g2VideoDocument.getEditorialTag();

        // Lock document Metadata
        EditVideoDocumentMetaBehavior lockDocMeta = new EditVideoDocumentMetaBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument, documentID);
        ApplyTestBehaviorAction lockDocMetaAction = new ApplyTestBehaviorAction(runner, lockDocMeta);
        lockDocMetaAction.doExecute(context);
}
}

I run this in eclipse as JUnit test.

I thought about using a super class but it didn't work.

public class ProductDocumentValidationScenarioIT extends NoProductDocumentValidationScenarioIT {

    public String ProductDocumentValidation(@CitrusResource TestRunner runner, @CitrusResource TestContext context)
            throws BadNewsMLG2Exception {
                return something;

    }
}

Body:
Test behaviors is the way to go here. I suggest to use something like this

CreateVideoDocumentBehavior createDoc = new CreateVideoDocumentBehavior(cmsAuthClient, pdtIdentifier,
                videoDocument);

runner.applyBehavior(createDoc);


问:
Handle Auth User in shopping cart
I written a code for shopping cart and store cart items in Session, now i want to handle individually Auth user Cart

Here is Cart.php

```<code>namespace App;

class Cart
{
    public $items=null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart)
    {
        if($oldCart){
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }

    public function add($item,$id){
        $storedItems = ['qty'=>0,'price'=>$item->price,'item'=>$item];
        if ($this->items){
            if (array_key_exists($id,$this->items)){
                $storedItems = $this->items[$id];
            }
        }
        $storedItems['qty']++;
        $storedItems['price'] = $item->ucp * $storedItems['qty'];
        $this->items[$id] = $storedItems;
        $this->totalQty++;
        $this->totalPrice += $item->ucp;
    }

}
</code>```

Here is cart controller

```<code>namespace App\Http\Controllers;

use App\Cart;
use App\Models\CartDetail;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function addToCart(Request $request)
    {

        $id = $request->product_id;

        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        if ($request->get_quantity) {
            while ($request->get_quantity > 0) {
                $cart->add($product, $product->id);
                $request->get_quantity--;
            }
        } else {
            $cart->add($product, $product->id);
        }

        $request->session()->put('cart', $cart);

        return Session::get('cart')->totalQty;

    }

   }
</code>```

Where i am handle auth user? In this scenario when one user add product in cart those item shows to another user as well :( please give a solution

答:
You can make it unique with userId. Something like below

```<code>$request->session()->put('cart'.$userId, $cart);
</code>```

when you need to get that cart, get it like below.

```<code>return Session::get('cart'.$userId)->totalQty;
</code>```

Now let me explain you.

Am just concatenating userId with cart so it becomes unique.
when first user is logged in and i need to get his cart. so i simply right below.

```<code>Session::get('cart'.Auth::id())->totalQty;
</code>```

that's how you will get cart of the related user only.

You can also use some laravel cart package. Let me know if you need one in the comment section.

Title: Handle Auth User in shopping cart

Body:
I written a code for shopping cart and store cart items in Session, now i want to handle individually Auth user Cart

Here is Cart.php

namespace App;

class Cart
{
    public $items=null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart)
    {
        if($oldCart){
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }

    public function add($item,$id){
        $storedItems = ['qty'=>0,'price'=>$item->price,'item'=>$item];
        if ($this->items){
            if (array_key_exists($id,$this->items)){
                $storedItems = $this->items[$id];
            }
        }
        $storedItems['qty']++;
        $storedItems['price'] = $item->ucp * $storedItems['qty'];
        $this->items[$id] = $storedItems;
        $this->totalQty++;
        $this->totalPrice += $item->ucp;
    }

}

Here is cart controller

namespace App\Http\Controllers;

use App\Cart;
use App\Models\CartDetail;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function addToCart(Request $request)
    {

        $id = $request->product_id;

        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        if ($request->get_quantity) {
            while ($request->get_quantity > 0) {
                $cart->add($product, $product->id);
                $request->get_quantity--;
            }
        } else {
            $cart->add($product, $product->id);
        }

        $request->session()->put('cart', $cart);

        return Session::get('cart')->totalQty;

    }

   }

Where i am handle auth user? In this scenario when one user add product in cart those item shows to another user as well :( please give a solution

Body:
You can make it unique with userId. Something like below

$request->session()->put('cart'.$userId, $cart);

when you need to get that cart, get it like below.

return Session::get('cart'.$userId)->totalQty;

Now let me explain you.

Am just concatenating userId with cart so it becomes unique.
when first user is logged in and i need to get his cart. so i simply right below.

Session::get('cart'.Auth::id())->totalQty;

that's how you will get cart of the related user only.

You can also use some laravel cart package. Let me know if you need one in the comment section.


问:
How to specify multiple files in $sourcePath
I'm trying to copy multiple files locally to network share.

Method I am using

```<code>$sourcePath = "C:\folder\file.csv"
</code>```

Works fine, but when I add addition file to the same sourcepath it fails, e.g

```<code>$sourcePath = "C:\folder\file.csv, C:\folder\file2.csv"
</code>```

I would like to be able to copy two separate files specified in sourcepath.

答:
Per the other answer, just declare your paths as an array of strings by comma separating them. You can then provide them as input to the -Path parameter (which accepts an array of strings as input):

```<code>Copy-Item -Path 'C:\folder\file.csv','C:\folder\file2.csv' -Destination 'C:\Temp'
</code>```

Or you can provide them via pipeline input, where they are sent to the -Path parameter:

```<code>'C:\folder\file.csv','C:\folder\file2.csv' | Copy-Item -Destination 'C:\Temp'
</code>```

Body:
I'm trying to copy multiple files locally to network share.

Method I am using

$sourcePath = "C:\folder\file.csv"

Works fine, but when I add addition file to the same sourcepath it fails, e.g

$sourcePath = "C:\folder\file.csv, C:\folder\file2.csv"

I would like to be able to copy two separate files specified in sourcepath.

Body:
Per the other answer, just declare your paths as an array of strings by comma separating them. You can then provide them as input to the -Path parameter (which accepts an array of strings as input):

Copy-Item -Path 'C:\folder\file.csv','C:\folder\file2.csv' -Destination 'C:\Temp'

Or you can provide them via pipeline input, where they are sent to the -Path parameter:

'C:\folder\file.csv','C:\folder\file2.csv' | Copy-Item -Destination 'C:\Temp'


问:
How do I make a link open an Instagram page in an app installed on android?
I need to know how to make a link open an Instagram page in an app if the app is installed on a smartphone.

A simple way such as www.instagram.com/example links you to page by browser, which is not what I want.

How do I achieve this?

答:
You can try this method. You can have the POPUP to choice open link via Instagram or Browser.
(This method uses for any link you want, Not just Instagram.)</p>

```<code>***.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "Your URL";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
</code>```

Body:
You can try this method. You can have the POPUP to choice open link via Instagram or Browser.
(This method uses for any link you want, Not just Instagram.)

***.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "Your URL";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});


问:
How can I create a subset of a dataframe with the indices starting at 0?
I am creating a subset of a dataframe like this:

dist = df['distance'][23:42]

The start index of the result I am getting is then 23, but i want to start the series at index 0.

How can I tell Python to create new indices for my subset and not reuse the ones from the initial dataframe?

答:
Use .reset_index() with drop=True

drop : bool, default False
  Do not try to insert index into dataframe columns. This resets the index to the default integer index.

```<code>df['distance'].iloc[23:42].reset_index(drop=True)
</code>```

Or as @yatu suggests:

```<code>df.loc[23:42, 'distance'].reset_index(drop=True)
</code>```

Body:
Use .reset_index() with drop=True

drop : bool, default False
  Do not try to insert index into dataframe columns. This resets the index to the default integer index.

df['distance'].iloc[23:42].reset_index(drop=True)

Or as @yatu suggests:

df.loc[23:42, 'distance'].reset_index(drop=True)


问:
How to dispose shared variable in VB.NET
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

```<code>  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub
</code>```

can any one please help to do that

Thanks,
Senthil

答:
I think the problem is not in the disposing of the ManagerConnection.
Asterisk.NET Manager doesn't implement IDisposable.
You have to Logoff.

```<code>objManager.Logoff();
</code>```

for vb.net would be

```<code>objManager.Logoff()
</code>```

and then destroy the reference:

```<code>objManager = Nothing
</code>```

Body:
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub

can any one please help to do that

Thanks,
Senthil

Body:
I think the problem is not in the disposing of the ManagerConnection.
Asterisk.NET Manager doesn't implement IDisposable.
You have to Logoff.

objManager.Logoff();

for vb.net would be

objManager.Logoff()

and then destroy the reference:

objManager = Nothing


问:
SVG as a CSS Background - Is there ANY way to repeat-x with NO space in between?
In Webkit and Blink-based browsers, SVGs do not tile correctly. There is a space between the images at various zoom levels. There are a number of topics on StackOverflow addressing this, all marked as solved, but those people must not have tested their solutions thoroughly enough.

My SVGs are a perfectly even number of pixels (130 x 24).
They have background-size set to 130px 24px.
They are set to preserveAspectRatio="none".
There is absolutely zero empty space on the edges of the SVG.

Yet, while it looks fine at 100%, there is still a thin space between the SVGs if you zoom in to the right level.

It surprises me this bug has not been reported before, given the widespread recommendations of using SVGs for backgrounds.

Here is the exact SVG:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
      viewBox="0 0 130 24" xml:space="preserve" preserveAspectRatio="none">

    <path class="st0" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </svg>```

I can confirm this behavior with other SVGs as well, such as the ones at https://www.heropatterns.com/

Codepen for testing: https://codepen.io/TelFiRE/pen/gJzqaG

The space between the images is usually sub 1 pixel (meaning the line is just a lighter shade of green). It's subtle and may be hard to see if you have a dull monitor.

In asking this question, I'm hoping to understand WHY it is occurring in a way that lets me make lots of repeating SVG backgrounds without issue. It's not just about the one image, so I want to avoid hacky solutions/workarounds if at all possible. For example, chopping 2 pixels off the edge fixes it 99% of the way, but not entirely, and it leaves me wondering what I would do if I actually needed those two pixels. This particular SVG looks okay like that but more complicated patterns would be knocked out of alignment.

答:
It seems that some browsers do have trouble with repeating backgrounds made from SVG images.

One solution to this is to do the repeating inside the SVG instead.  We can use a <pattern> element to define the repeating pattern and use that to fill a rectangle.

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="24">
  <defs>
    <pattern id="bg" patternUnits="userSpaceOnUse" width="130" height="24">
      <path fill="#A5EF8B" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </pattern>
  </defs>
  <rect width="100%" height="100%" fill="url(#bg)"/>
</svg>```
</div>
</div>
</p>

<p>And when used as a <code>background-image</code> to a <code><div></code>, it becomes:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  margin: 4rem 0;
  height: 24px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%' height='24'%3E%3Cdefs%3E%3Cpattern id='bg' patternUnits='userSpaceOnUse' width='130' height='24'%3E%3Cpath fill='%23A5EF8B' d='M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0'/%3E%3C/pattern%3E%3C/defs%3E%3Crect width='100%' height='100%' fill='url(%23bg)'/%3E%3C/svg%3E");
  background-size: 100% 24px;
  background-repeat: no-repeat;
}</code>```

```

Body:
In Webkit and Blink-based browsers, SVGs do not tile correctly. There is a space between the images at various zoom levels. There are a number of topics on StackOverflow addressing this, all marked as solved, but those people must not have tested their solutions thoroughly enough.

My SVGs are a perfectly even number of pixels (130 x 24).
They have background-size set to 130px 24px.
They are set to preserveAspectRatio="none".
There is absolutely zero empty space on the edges of the SVG.

Yet, while it looks fine at 100%, there is still a thin space between the SVGs if you zoom in to the right level.

It surprises me this bug has not been reported before, given the widespread recommendations of using SVGs for backgrounds.

Here is the exact SVG:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
      viewBox="0 0 130 24" xml:space="preserve" preserveAspectRatio="none">

    <path class="st0" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </svg>

I can confirm this behavior with other SVGs as well, such as the ones at https://www.heropatterns.com/

Codepen for testing: https://codepen.io/TelFiRE/pen/gJzqaG

The space between the images is usually sub 1 pixel (meaning the line is just a lighter shade of green). It's subtle and may be hard to see if you have a dull monitor.

In asking this question, I'm hoping to understand WHY it is occurring in a way that lets me make lots of repeating SVG backgrounds without issue. It's not just about the one image, so I want to avoid hacky solutions/workarounds if at all possible. For example, chopping 2 pixels off the edge fixes it 99% of the way, but not entirely, and it leaves me wondering what I would do if I actually needed those two pixels. This particular SVG looks okay like that but more complicated patterns would be knocked out of alignment.

Body:
It seems that some browsers do have trouble with repeating backgrounds made from SVG images.

One solution to this is to do the repeating inside the SVG instead.  We can use a <pattern> element to define the repeating pattern and use that to fill a rectangle.

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="24">
  <defs>
    <pattern id="bg" patternUnits="userSpaceOnUse" width="130" height="24">
      <path fill="#A5EF8B" d="M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0"/>
    </pattern>
  </defs>
  <rect width="100%" height="100%" fill="url(#bg)"/>
</svg>

And when used as a background-image to a <div>, it becomes:

div {
  margin: 4rem 0;
  height: 24px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%' height='24'%3E%3Cdefs%3E%3Cpattern id='bg' patternUnits='userSpaceOnUse' width='130' height='24'%3E%3Cpath fill='%23A5EF8B' d='M0,12c32.5,0,32.5,12,65,12s32.5-12,65-12V0C97.5,0,92.9,12,65,12C32.5,12,20.7,0,0,0'/%3E%3C/pattern%3E%3C/defs%3E%3Crect width='100%' height='100%' fill='url(%23bg)'/%3E%3C/svg%3E");
  background-size: 100% 24px;
  background-repeat: no-repeat;
}

<div></div>


问:
Jenkins X error: secrets "jenkins" not found
I am following this tutorial. I'm trying to create a Jenkins X app locally in minikube and setting it up with Github.

But when I do jx create quickstart and follow the steps I get error: secrets "jenkins" not found as error.

Also, I found out that there is no secret named jenkins

```<code>root@Unix:/home/dadart/Downloads# kubectl get secret -n jx jenkins
Error from server (NotFound): secrets "jenkins" not found
</code>```

Someone please point out what I'm doing wrong.

答:
Please follow this post on Github with set-up "env settings" before installation.

You can find also in "Common problems" section "How do I get the Password and Username for Jenkins?"

As per documentation - it seems you missed some part during installation:

What happens during installation

Jenkins X generates an administration password for Monocular/Nexus/Jenkins and save it in secrets. It then retrieves git secrets for the helm install (so they can be used in the pipelines).

this can be helpful "jenkins image" issue.

In case you still notice more problems with jenkis installation please open an issue here

Please share with your findings

Body:
I am following this tutorial. I'm trying to create a Jenkins X app locally in minikube and setting it up with Github.

But when I do jx create quickstart and follow the steps I get error: secrets "jenkins" not found as error.

Also, I found out that there is no secret named jenkins

root@Unix:/home/dadart/Downloads# kubectl get secret -n jx jenkins
Error from server (NotFound): secrets "jenkins" not found

Someone please point out what I'm doing wrong.


问:
Is there a way to bulk/batch download all repos from Github based on a search result?
I run this search on Guthub and I get 881 repos. Blazor & C# repos.
https://github.com/search?l=C%23&q=blazor&type=Repositories

Is there a way to download all these repos easily instead of one by one?

答:
Yes, your query can be run via the github search api:

https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=1

That gives you one page of 100 repositories. You can loop over all pages, extract the ssh_url (or http if you prefer), and write the result to a file:

# cheating knowing we currently have 9 pages
for i in {1..9}
do
    curl "https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=$i" \
     | jq -r '.items[].ssh_url' >> urls.txt
done

cat urls.txt | xargs -P8 -L1 git clone
```

You can optimize to extract the number of pages from the response headers.

References:

https://developer.github.com/v3/search/

Parsing JSON with Unix tools

How to apply shell command to each line of a command output?

Running programs in parallel using xargs

Similar question:

GitHub API - Different number of results for jq filtered response

Body:
Yes, your query can be run via the github search api:

https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=1

That gives you one page of 100 repositories. You can loop over all pages, extract the ssh_url (or http if you prefer), and write the result to a file:

# cheating knowing we currently have 9 pages
for i in {1..9}
do
    curl "https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=$i" \
     | jq -r '.items[].ssh_url' >> urls.txt
done

cat urls.txt | xargs -P8 -L1 git clone

You can optimize to extract the number of pages from the response headers.

References:

https://developer.github.com/v3/search/

Parsing JSON with Unix tools

How to apply shell command to each line of a command output?

Running programs in parallel using xargs

Similar question:

GitHub API - Different number of results for jq filtered response


问:
How to pass async data retrieved in splashscreen to App.js?
This article explains how to use splash screen to load data before initial screen. Basically it defines:

```<code>const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);
</code>```

Here is the AppNavigator:

```<code>const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);
</code>```

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

```<code>class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......
</code>```

But how can I pass the value of result and user to App?

答:
One solution is to save those data in global state (e.g. React Hook or redux), or in storage (e.g. using react-native-async-storage). The next screen will need to access shared resource to retrieve data. Following example uses async storage to store data:

```<code>import AsyncStorage from '@react-native-community/async-storage';

performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      await AsyncStorage.setItem('jwtToken', result);
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      await AsyncStorage.setItem('user', user);
    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }
</code>```

Another solution is passing result & user as params in method navigation.navigate. To do that, your function performTimeConsumingTask needs to return both objects.

```<code>class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      return {
        user,
        result,
        success: true
      }
    } else {
      throw new Error("App.js result is false");
    };
    throw new Error("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return {
      success: false,
      error: err.message
    };

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null && data.success === true) {
      this.props.navigation.navigate('App', data);
    }
  }
</code>```

Body:
This article explains how to use splash screen to load data before initial screen. Basically it defines:

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);

Here is the AppNavigator:

const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......

But how can I pass the value of result and user to App?

Body:
One solution is to save those data in global state (e.g. React Hook or redux), or in storage (e.g. using react-native-async-storage). The next screen will need to access shared resource to retrieve data. Following example uses async storage to store data:

import AsyncStorage from '@react-native-community/async-storage';

performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      await AsyncStorage.setItem('jwtToken', result);
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      await AsyncStorage.setItem('user', user);
    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

Another solution is passing result & user as params in method navigation.navigate. To do that, your function performTimeConsumingTask needs to return both objects.

class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      return {
        user,
        result,
        success: true
      }
    } else {
      throw new Error("App.js result is false");
    };
    throw new Error("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return {
      success: false,
      error: err.message
    };

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null && data.success === true) {
      this.props.navigation.navigate('App', data);
    }
  }


问:
Output Range same as input range
I have some history working with VBA, but can't seem to find the solution to this problem.  I found an iteration process to select a cell, do a process, and then select the next cell and do the process again, until NULL.  I am having a problem outputting each of the processes solutions into the next column. Here is what I have:

```<code>Sub Name ()

Dim X As Integer
Dim MyString as String

Application.ScreenUpdating = False
NumRows = Range("D2", Range("D2").End(xlDown)).Rows.Count
Range("D2").Select
For X = 1 To NumRows
    MyString = ActiveCell.Value
    MyString = Right(MyString, Len(MyString)-6)
    Range("I2 to I#").Value = MyString
    ActiveCell.Offset(1,0).Select
Next X

End Sub
</code>```

Range("I2 to I#").Value = MyString is the line that I need help with.  I need it to increment to I3, I4, I5, etc. until it reaches NumRows count.

答:
When working with Cells the best way to loop through them is For Each Cell in Range so taking this and as comments told you to avoid selecting, this should help you:

```<code>Option Explicit
Sub Name()

    Dim C As Range, MyRange As Range
    Dim LastRow As Long

    Application.ScreenUpdating = False
    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
        LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row 'last row on column D
        Set MyRange = .Range("D2:D" & LastRow) 'declare your working range
        For Each C In MyRange
            If Not C = vbNullString Then .Cells(C.Row, "I") = Right(C, Len(C) - 6)
        Next C
    End With
    Application.ScreenUpdating = True

End Sub
</code>```

Title: Output Range same as input range

Body:
I have some history working with VBA, but can't seem to find the solution to this problem.  I found an iteration process to select a cell, do a process, and then select the next cell and do the process again, until NULL.  I am having a problem outputting each of the processes solutions into the next column. Here is what I have:

Sub Name ()

Dim X As Integer
Dim MyString as String

Application.ScreenUpdating = False
NumRows = Range("D2", Range("D2").End(xlDown)).Rows.Count
Range("D2").Select
For X = 1 To NumRows
    MyString = ActiveCell.Value
    MyString = Right(MyString, Len(MyString)-6)
    Range("I2 to I#").Value = MyString
    ActiveCell.Offset(1,0).Select
Next X

End Sub

Range("I2 to I#").Value = MyString is the line that I need help with.  I need it to increment to I3, I4, I5, etc. until it reaches NumRows count.

Body:
When working with Cells the best way to loop through them is For Each Cell in Range so taking this and as comments told you to avoid selecting, this should help you:

Option Explicit
Sub Name()

    Dim C As Range, MyRange As Range
    Dim LastRow As Long

    Application.ScreenUpdating = False
    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
        LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row 'last row on column D
        Set MyRange = .Range("D2:D" & LastRow) 'declare your working range
        For Each C In MyRange
            If Not C = vbNullString Then .Cells(C.Row, "I") = Right(C, Len(C) - 6)
        Next C
    End With
    Application.ScreenUpdating = True

End Sub


问:
Find next greater number with zeros in sql number
I'm looking for a way to find next greater number starting by 1 and followed by zeros in Microsoft SQL. Numbers could vary in digits. ie:

Query: 9856, Result after procedure: 10000
Query: 98999, Result after procedure: 100000

Thanks.

EDIT: There is no chance of having negative numbers. This is a calculation for a energy meter. For example, numbers can go up to 99999 or 999999 or 9999999. When energy overcome that number, it will start again at 0. So I can't read what energy has been used in that period. To know it, I need to calculate the number as asked, then perform some basic maths.

There is no need for knowing what is going on on 10, 100, etc, because of the nature of the operation. It will only be used when the above escenario happend.

答:
This is a fairly crude way of doing it, however it does work. The query basically looks at the number of digits your number has, assumes the next integer you want starts with a 1 and then adds the relevant number of 0's to it.

Note this only looks for the next increment and does not round down.

Also for 10 you will get 100 and for 1000 you will get 10000.

```<code>declare @number int = 98999;
declare @len int = len(@number);
declare @stringtoreturn nvarchar(200)='1';

declare @runs int = 1;

while @runs<=@len
    begin
    select @stringtoreturn = @stringtoreturn + '0';
    select @runs=@runs+1;
    end

select @stringtoreturn;
</code>```

Body:
This is a fairly crude way of doing it, however it does work. The query basically looks at the number of digits your number has, assumes the next integer you want starts with a 1 and then adds the relevant number of 0's to it.

Note this only looks for the next increment and does not round down.

Also for 10 you will get 100 and for 1000 you will get 10000.

declare @number int = 98999;
declare @len int = len(@number);
declare @stringtoreturn nvarchar(200)='1';

declare @runs int = 1;

while @runs<=@len
    begin
    select @stringtoreturn = @stringtoreturn + '0';
    select @runs=@runs+1;
    end

select @stringtoreturn;


问:
Xcode10: The operation couldn't be completed. (DVTCoreSimulatorAdditionsErrorDomain error 0.)
I have tried:

restart the simulator and Xcode

delete Xcode and reinstall it

run xcrun simctl erase all this command

I already try but can't solve this issue

答: You can delete this simulator and add it back.I had solved this problem by this way. Maybe you can try it.</p>


问:
Promise.all getting Unhandled rejection
I'm using Promise.all and catch error but still getting Unhandled rejection

```<code>const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();
</code>```

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.

答:
The reason is you are not handling error on this sleep method.
It should look like this.

```<code>function sleep(milis) {
return new Promise(function (resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
 }).catch(error => {
    console.log(error);
 })
}
</code>```

Title: Promise.all getting Unhandled rejection

Body:
I'm using Promise.all and catch error but still getting Unhandled rejection

const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.

Body:
The reason is you are not handling error on this sleep method.
It should look like this.

function sleep(milis) {
return new Promise(function (resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
 }).catch(error => {
    console.log(error);
 })
}


问:
How do I pass a parameter value from one stored procedure to another?
I'm trying to pass the input parameters from one stored procedure to another stored procedure, the value of the parameter will be used to be inserted into a table.

I have two stored procedures, here is the logic for the SP's:

First one -

```<code>CREATE PROCEDURE [abc].[SP1](
@ID1     INT
@ID2     INT
@Date    VARCHAR(10)
@Value   VARCHAR(50)
)

AS

Select into #temp...

EXEC [abc].[SP2] @ID1, @ID2, @Date, @Value

Select...
</code>```

Second one -

```<code>CREATE PROCEDURE [abc].[sp2](
@bID1    INT
@bID2    INT
@bDate   VARCHAR(10)
@Value   VARCHAR(50)
)

DECLARE @bID1 INT, @bID2 INT, @bDate VARCHAR(10), @Value VARCHAR(50)

--main part that I'm concerned with, getting the parameter values to work
SELECT @bID1, @bID2, @bDate, @Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x

</code>```

When I try this I receive an error saying that I, "must declare the scalar variable"

答:
It's not how you create procedures in SQL Server. You should do something like this:

```<code>CREATE PROCEDURE [SP1]
 @ID1     INT
,@ID2     INT
,@Date    VARCHAR(10)
,@Value   VARCHAR(50)

AS

Select into #temp...
</code>```

Secondly, when you declared parameteres for the procedure you cannot declare variables with the same names below:

```<code> CREATE PROCEDURE [abc].[sp2]
 @bID1    INT
,@bID2    INT
,@bDate   VARCHAR(10)
,@Value   VARCHAR(50)

AS

--main part that I'm concerned with, getting the parameter values to work
SELECT @bID1, @bID2, @bDate, @Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x
</code>```

Body:
I'm trying to pass the input parameters from one stored procedure to another stored procedure, the value of the parameter will be used to be inserted into a table.

I have two stored procedures, here is the logic for the SP's:

First one -

CREATE PROCEDURE [abc].[SP1](
@ID1     INT
@ID2     INT
@Date    VARCHAR(10)
@Value   VARCHAR(50)
)

AS

Select into #temp...

EXEC [abc].[SP2] @ID1, @ID2, @Date, @Value

Select...

Second one -

CREATE PROCEDURE [abc].[sp2](
@bID1    INT
@bID2    INT
@bDate   VARCHAR(10)
@Value   VARCHAR(50)
)

DECLARE @bID1 INT, @bID2 INT, @bDate VARCHAR(10), @Value VARCHAR(50)

--main part that I'm concerned with, getting the parameter values to work
SELECT @bID1, @bID2, @bDate, @Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x

When I try this I receive an error saying that I, "must declare the scalar variable"

Body:
It's not how you create procedures in SQL Server. You should do something like this:

CREATE PROCEDURE [SP1]
 @ID1     INT
,@ID2     INT
,@Date    VARCHAR(10)
,@Value   VARCHAR(50)

AS

Select into #temp...

Secondly, when you declared parameteres for the procedure you cannot declare variables with the same names below:

 CREATE PROCEDURE [abc].[sp2]
 @bID1    INT
,@bID2    INT
,@bDate   VARCHAR(10)
,@Value   VARCHAR(50)

AS

--main part that I'm concerned with, getting the parameter values to work
SELECT @bID1, @bID2, @bDate, @Value, x.col1, x.col2
INTO [abc].[tableA]
FROM tableX x


问:
How to print PartialView
i was looking for this and tried to fix for couple of days but with no sucess. What wrong im doing in this code? I want to print _Champions
and _SearchEngine as PartialView in Home/Index but it show error.

My HomeController

```<code> public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
[HttpGet]
        public ActionResult _SearchEngine()
        {
            SearchLeagueModel searchLeagueModel = new SearchLeagueModel();
            searchLeagueModel.MainSelector = "champions";
            return PartialView("_SearchEngine", searchLeagueModel);
        }
        public ActionResult _SearchEngine(SearchLeagueModel searchLeagueModel)
        {
            if (searchLeagueModel.MainSelector == "champions")
            {
                return RedirectToAction("_Champions", searchLeagueModel);
            }
            else return View();
        }
        [HttpPost]
        public ActionResult _Champions(SearchLeagueModel searchLeagueModel)
        {
            string chooser = searchLeagueModel.MainSelector;
            string selector;
            if (searchLeagueModel.MainSelector != null)
            {
                selector = "filter[name]=" + searchLeagueModel.MainSelector;
            }
            else
            {
                selector = "";
            }
                WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/" + chooser + "?" + selector + "&token=mytoken);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string responseFromServer = reader.ReadToEnd();
                List<ChampionsModel> champions = JsonConvert.DeserializeObject<List<ChampionsModel>>(responseFromServer);
                return PartialView("_Champions", champions);
        }
//other views
}
</code>```

My IndexModelView

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LeagueAPI.Models
{
    public class IndexModelView
    {
        public IndexModelView()
        {
            ChampionsList = new ChampionsModel();
            Searcher = new SearchLeagueModel();
        }
        public ChampionsModel ChampionsList { get; set; }
        public SearchLeagueModel Searcher { get; set; }
    }

    public class ChampionsModel
    {
        public List<string> videogame_versions { get; set; }
        public double spellblockperlevel { get; set; }
        public double spellblock { get; set; }
        public string name { get; set; }
        public double mpregenperlevel { get; set; }
        public double mpregen { get; set; }
        public double mpperlevel { get; set; }
        public double mp { get; set; }
        public double movespeed { get; set; }
        public string image_url { get; set; }
        public int id { get; set; }
        public double hpregenperlevel { get; set; }
        public double hpregen { get; set; }
        public double hpperlevel { get; set; }
        public double hp { get; set; }
        public double critperlevel { get; set; }
        public double crit { get; set; }
        public string big_image_url { get; set; }
        public double attackspeedperlevel { get; set; }
        public object attackspeedoffset { get; set; }
        public double attackrange { get; set; }
        public double attackdamageperlevel { get; set; }
        public double attackdamage { get; set; }
        public double armorperlevel { get; set; }
        public double armor { get; set; }
    }
}
</code>```

My _Champions.cshtml PartialView(made as PartialView)

```<code>@using LeagueAPI.Models
@model System.Collections.Generic.List<ChampionsModel>
<fieldset>
    <div class="d-flex p-3 w-auto h-auto">
        @foreach (var element in @Model)
        {
            <div class="p-3 flex-lg-wrap">
                <div class="card p-2" style="width: 15rem ;">
                    <img class="card-img-top" src="@Html.DisplayFor(model => element.big_image_url)">
                    <div class="card-body p-0 m-0">
                        <h5 class="card-title p-0 m-0 text-center">@Html.DisplayFor(model => element.name)</h5>
                        <p class="card-text p-0 m-0">DMG/LVL: @Html.DisplayFor(model => element.attackdamageperlevel)</p>
                        <p class="card-text p-0 m-0">ARMOR/LVL: @Html.DisplayFor(model => element.armorperlevel)</p>
                        <p class="card-text p-0 m-0">MOVEMENT SPEED: @Html.DisplayFor(model => element.movespeed)</p>
                        <p class="card-text p-0 m-0">ATTACK RANGE: @Html.DisplayFor(model => element.attackrange)</p>
                        <a href="/Home/Details"
                           class="btn btn-primary m-1 "
                           OnClick="GreetingBtn_Click">More details</a>
                    </div>
                </div>
            </div>
        }
    </div>
</fieldset>
</code>```

Index View

```<code>@model LeagueAPI.Models.IndexModelView

@Html.Action("_SearchEngine", Model.Searcher)
@Html.Action("_Champions", Model.ChampionsList)

</code>```

Everything else looks standard, in _Layout i have @RenderBody()
My second question is about _Champions Controller. Why when i put IndexModelView indexModelView = new IndexModelView() as parametr and bring necessary changes in code to this ActionResult, the MainSelector is null in that case.
Im still learning, if You can explain whats wrong here i will be thankful. cheers

答:
I would say instead of ActionResults rather use PartialViewResult on both actions _Champions and _SearchEngine

```<code>[HttpPost]
public PartialViewResult _Champions(SearchLeagueModel searchLeagueModel)
{
       return PartialView("_Champions", champions);
}
</code>```

And then from the index view Render those action like below:

```<code>@model LeagueAPI.Models.IndexModelView
<div>
@Html.RenderAction("_Champions");
@Html.RenderAction("_SearchEngine");
</div>
</code>```

Title: How to print PartialView

Body:
i was looking for this and tried to fix for couple of days but with no sucess. What wrong im doing in this code? I want to print _Champions
and _SearchEngine as PartialView in Home/Index but it show error.

My HomeController

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
[HttpGet]
        public ActionResult _SearchEngine()
        {
            SearchLeagueModel searchLeagueModel = new SearchLeagueModel();
            searchLeagueModel.MainSelector = "champions";
            return PartialView("_SearchEngine", searchLeagueModel);
        }
        public ActionResult _SearchEngine(SearchLeagueModel searchLeagueModel)
        {
            if (searchLeagueModel.MainSelector == "champions")
            {
                return RedirectToAction("_Champions", searchLeagueModel);
            }
            else return View();
        }
        [HttpPost]
        public ActionResult _Champions(SearchLeagueModel searchLeagueModel)
        {
            string chooser = searchLeagueModel.MainSelector;
            string selector;
            if (searchLeagueModel.MainSelector != null)
            {
                selector = "filter[name]=" + searchLeagueModel.MainSelector;
            }
            else
            {
                selector = "";
            }
                WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/" + chooser + "?" + selector + "&token=mytoken);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string responseFromServer = reader.ReadToEnd();
                List<ChampionsModel> champions = JsonConvert.DeserializeObject<List<ChampionsModel>>(responseFromServer);
                return PartialView("_Champions", champions);
        }
//other views
}

My IndexModelView

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LeagueAPI.Models
{
    public class IndexModelView
    {
        public IndexModelView()
        {
            ChampionsList = new ChampionsModel();
            Searcher = new SearchLeagueModel();
        }
        public ChampionsModel ChampionsList { get; set; }
        public SearchLeagueModel Searcher { get; set; }
    }

    public class ChampionsModel
    {
        public List<string> videogame_versions { get; set; }
        public double spellblockperlevel { get; set; }
        public double spellblock { get; set; }
        public string name { get; set; }
        public double mpregenperlevel { get; set; }
        public double mpregen { get; set; }
        public double mpperlevel { get; set; }
        public double mp { get; set; }
        public double movespeed { get; set; }
        public string image_url { get; set; }
        public int id { get; set; }
        public double hpregenperlevel { get; set; }
        public double hpregen { get; set; }
        public double hpperlevel { get; set; }
        public double hp { get; set; }
        public double critperlevel { get; set; }
        public double crit { get; set; }
        public string big_image_url { get; set; }
        public double attackspeedperlevel { get; set; }
        public object attackspeedoffset { get; set; }
        public double attackrange { get; set; }
        public double attackdamageperlevel { get; set; }
        public double attackdamage { get; set; }
        public double armorperlevel { get; set; }
        public double armor { get; set; }
    }
}

My _Champions.cshtml PartialView(made as PartialView)

@using LeagueAPI.Models
@model System.Collections.Generic.List<ChampionsModel>
<fieldset>

        @foreach (var element in @Model)
        {

                     element.big_image_url)">

@Html.DisplayFor(model => element.name)

DMG/LVL: @Html.DisplayFor(model => element.attackdamageperlevel)

ARMOR/LVL: @Html.DisplayFor(model => element.armorperlevel)

MOVEMENT SPEED: @Html.DisplayFor(model => element.movespeed)

ATTACK RANGE: @Html.DisplayFor(model => element.attackrange)

                        More details

        }

</fieldset>

Index View

@model LeagueAPI.Models.IndexModelView

@Html.Action("_SearchEngine", Model.Searcher)
@Html.Action("_Champions", Model.ChampionsList)

Everything else looks standard, in _Layout i have @RenderBody()
My second question is about _Champions Controller. Why when i put IndexModelView indexModelView = new IndexModelView() as parametr and bring necessary changes in code to this ActionResult, the MainSelector is null in that case.
Im still learning, if You can explain whats wrong here i will be thankful. cheers

Body:
I would say instead of ActionResults rather use PartialViewResult on both actions _Champions and _SearchEngine

[HttpPost]
public PartialViewResult _Champions(SearchLeagueModel searchLeagueModel)
{
       return PartialView("_Champions", champions);
}

And then from the index view Render those action like below:

@model LeagueAPI.Models.IndexModelView
<div>
@Html.RenderAction("_Champions");
@Html.RenderAction("_SearchEngine");
</div>