问:
Using authenticate function for WHERE in Rails MongoDB throws an Error
I created a way to generate a password using secure password with 'has_secure_password'. I was able to generate a password_digest:

```<code>//this is the data in my mongo db

/* 1 */
{
    "_id" : ObjectId("5e4b43d55c260c07b48cbf38"),
    "username" : "admin",
    "password_digest" : "$2a$12$93GElGpXK2AcfRvhNsH23O2mPlTiV.sHLrtuesFO5HSllxDqEE796"
}

/* 2 */
{
    "_id" : ObjectId("5e4b46c95c260c07b48cbf3c"),
    "username" : "jenuel",
    "password_digest" : "$2a$12$6LPYNpAzCAT/k8HHFVJT7..E0GO2iuBJolY0TPHbklz0J58/OLkRm"
}
</code>```

this is my model in rails

```<code>class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include ActiveModel::Validations

  field :username, type: String
  field :password_digest, type: String
  has_secure_password
  validates_confirmation_of :password
end
</code>```

I was able to create this users above using this function, inside my controller:

```<code>def create
    if check_username(params[:username]) == false
      @user = User.new(user_params)

      if @user.save
        render json: @user, status: :created, location: @user
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    else
      render json: { error: "Username Already Exist" }, status: :unprocessable_entity
    end
  end
</code>```

And this is my login function:

```<code> def login
    user = User.where(username: params[:username])
    if user.exists? && user.authenticate(params[:password])
        render json: { message: "Logged In!" }, status: :ok
    else
      render json: { error: "unauthorized" }, status: :unauthorized
    end
  end
</code>```

My problem in the Login Function, when I use authenticate their is an error:

Please help. Is their other way to do this, to authenticate the password using Rails for MongoDB/mongoloid. Thank you So much :)

答:
I was able to find the answer of my own problem. For others who are stock in this kind of problem, you can just change this line of code.

```<code>user = User.where(username: params[:username])
</code>```

to

```<code>user = User.find_by(username: params[:username])
</code>```

Body:
I created a way to generate a password using secure password with 'has_secure_password'. I was able to generate a password_digest:

//this is the data in my mongo db

/* 1 */
{
    "_id" : ObjectId("5e4b43d55c260c07b48cbf38"),
    "username" : "admin",
    "password_digest" : "$2a$12$93GElGpXK2AcfRvhNsH23O2mPlTiV.sHLrtuesFO5HSllxDqEE796"
}

/* 2 */
{
    "_id" : ObjectId("5e4b46c95c260c07b48cbf3c"),
    "username" : "jenuel",
    "password_digest" : "$2a$12$6LPYNpAzCAT/k8HHFVJT7..E0GO2iuBJolY0TPHbklz0J58/OLkRm"
}

this is my model in rails

class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include ActiveModel::Validations

  field :username, type: String
  field :password_digest, type: String
  has_secure_password
  validates_confirmation_of :password
end

I was able to create this users above using this function, inside my controller:

def create
    if check_username(params[:username]) == false
      @user = User.new(user_params)

      if @user.save
        render json: @user, status: :created, location: @user
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    else
      render json: { error: "Username Already Exist" }, status: :unprocessable_entity
    end
  end

And this is my login function:

 def login
    user = User.where(username: params[:username])
    if user.exists? && user.authenticate(params[:password])
        render json: { message: "Logged In!" }, status: :ok
    else
      render json: { error: "unauthorized" }, status: :unauthorized
    end
  end

My problem in the Login Function, when I use authenticate their is an error:

Please help. Is their other way to do this, to authenticate the password using Rails for MongoDB/mongoloid. Thank you So much :)

Body:
I was able to find the answer of my own problem. For others who are stock in this kind of problem, you can just change this line of code.

user = User.where(username: params[:username])

to

user = User.find_by(username: params[:username])


来源: stackexchange

问:
How i can run command by run schedule and by button also?
I have created commands in kernel.php which is running twiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.

Currently, I have just created twiceDaily command I need better way to implement button idea.

kernel.php

```<code>protected function schedule(Schedule $schedule)
{
    $schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}
</code>```

I want to run command by cron job on server and by button also.

答:
What you are doing now is scheduling a job to run twice daily.
However, you can also manually dispatch a job to run at that instance (or as soon as a runner is free to handle your job).

You can create a controller action so that when the button is clicked, the controller dispatch the job. For example,

```<code><?php

namespace App\Http\Controllers;

use App\Jobs\ResendAttachment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExampleController extends Controller
{
    /**
     * Resend attachment.
     *
     * @param  Request  $request
     * @return Response
     */
    public function resendAttachment(Request $request)
    {
        ResendAttachment::dispatch();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created commands in kernel.php which is running twiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.

Currently, I have just created twiceDaily command I need better way to implement button idea.

kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}

I want to run command by cron job on server and by button also.

Body:
What you are doing now is scheduling a job to run twice daily.
However, you can also manually dispatch a job to run at that instance (or as soon as a runner is free to handle your job).

You can create a controller action so that when the button is clicked, the controller dispatch the job. For example,

<?php

namespace App\Http\Controllers;

use App\Jobs\ResendAttachment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExampleController extends Controller
{
    /**
     * Resend attachment.
     *
     * @param  Request  $request
     * @return Response
     */
    public function resendAttachment(Request $request)
    {
        ResendAttachment::dispatch();
    }
}


ContentLicense: CC BY-SA 3.0

Title: coding variable values into classes using R

Body:
I have a set of data in which I need to code values of certain variables (numeric) into 3 classes.

My data set is similar to this but has 60 more variables:

anim <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
wt <- c(181,179,180.5,201,201.5,245,246.4,189.3,301,354,369,205,199,394,231.3)
data <- data.frame(anim,wt)

> data
   anim    wt
1     1 181.0
2     2 179.0
3     3 180.5
4     4 201.0
5     5 201.5
6     6 245.0
7     7 246.4
8     8 189.3
9     9 301.0
10   10 354.0
11   11 369.0
12   12 205.0
13   13 199.0
14   14 394.0
15   15 231.3

I need to code values of the variable "wt" up into 3 classes: (wt >= 179 & wt < 200) = 1; (wt >= 200 & wt < 300) = 2; (wt > 300) = 3

which should give me this

> data2
   anim    wt SWT
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   2
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

Body:
Just to show an alternate (similar to recode in SPSS) method from package car:

> data$SWT <- with(data, recode(wt, "lo:200=1; 300:hi=3; else=2"))
> data
   anim    wt SWT
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   2
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2


问:
What does map.put return?
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value.
So, can anyone tell me what is the return type of the put method in the map interface?</p>

```<code>Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC
</code>```

答: This method returns returns previous value associated with the key if present, else return null. So return type in above case is String.</p>

Title: What does map.put return?

Body:
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value.
So, can anyone tell me what is the return type of the put method in the map interface?

Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC


问:
How to filter using ksql with array attribute type
I have a Stream on a topic with schema:

```<code>--root
  --name: string
  --age: integer
  --accounts: Array
    --email
</code>```

I would like to select all root elements having accounts with email ='xx'

Thanks you for help.

答:
```<code>select * from t1 where accounts->email='xx'
</code>```

Assumption table or stream name is t1.

Body:
I have a Stream on a topic with schema:

--root
  --name: string
  --age: integer
  --accounts: Array
    --email

I would like to select all root elements having accounts with email ='xx'

Thanks you for help.

Body:
select * from t1 where accounts->email='xx'

Assumption table or stream name is t1.


问:
Is it possible to change standard CSS colors in VS CODE?
When you type CSS code in VS CODE, it uses Intellisense to suggest a color presets, for example, black is equal to #000.

So, can I change this black again, for example, to be #495057?

答:
You can use css variables for this.
For example in your css files.

```<code>:root {
  --main-bg-color: coral;
  --black-color: #495057;
}

#div1 {
  background-color: var(--main-bg-color);
  color: var(--black-color);
}

#div2 {
  background-color: var(--main-bg-color);
  color: var(--black-color);
}
</code>```

You can now use these css variables and throughout your code and assign different shades of black to them

Body:
You can use css variables for this.
For example in your css files.

:root {
  --main-bg-color: coral;
  --black-color: #495057;
}

#div1 {
  background-color: var(--main-bg-color);
  color: var(--black-color);
}

#div2 {
  background-color: var(--main-bg-color);
  color: var(--black-color);
}

You can now use these css variables and throughout your code and assign different shades of black to them


答:
you can read in the doc:  here

```<code>V put(K key, V value)
</code>```

Returns:
      the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map
  previously associated null with key, if the implementation supports
  null values.)

so, since your map is declared as

```<code>Map<Integer, String> map
</code>```

the Value V is the String type, and therefore calling put will return string.

but what is the value that I get? may you be asking to yourself....

then take a deep look in the source code...

HashMap's put method is actually invoking the final method putVal

and is implemented like:

```<code>final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
</code>```

and in the logic, the method returns the previous value found in the map for the given key...

that means the first time you do

put(1,"abc");
it returns null, because there was nothing in the map.
if you do again
put(1,"xyz"); then the method is returning "abc", because is the last value found in the map for the key = 1

Title: What does map.put return?

Body:
you can read in the doc:  here

V put(K key, V value)

Returns:
      the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map
  previously associated null with key, if the implementation supports
  null values.)

so, since your map is declared as

Map<Integer, String> map

the Value V is the String type, and therefore calling put will return string.

but what is the value that I get? may you be asking to yourself....

then take a deep look in the source code...

HashMap's put method is actually invoking the final method putVal

and is implemented like:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

and in the logic, the method returns the previous value found in the map for the given key...

that means the first time you do

put(1,"abc");
it returns null, because there was nothing in the map.
if you do again
put(1,"xyz"); then the method is returning "abc", because is the last value found in the map for the key = 1


问:
Need help applying animation in transform group in wpf
I have a piece of xaml that applies a scale transform and a rotatetransform.

```<code>        <Image.RenderTransform>
            <TransformGroup>
                <RotateTransform Angle="0" x:Name="RotateTransform"/>
                <TranslateTransform X="0" Y="0"/>
                <ScaleTransform ScaleX="2" ScaleY="2"/>
            </TransformGroup>
        </Image.RenderTransform>
</code>```

I also have a storyboard that needs to accesss RotateTransform like so:

```<code>        <Storyboard x:Key="Storyboard"
                Storyboard.TargetProperty="(RenderTransform).(RotateTransform.Angle)"
                Storyboard.TargetName="RotateTransform">
        <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
    </Storyboard>
</code>```

However I can not get the image to rotate, but it does scale up. Does anyone have suggestions to fix the problem?

Edit: I did figure out that i can use

```<code>    <Storyboard x:Key="Storyboard"
                Storyboard.TargetProperty="(Image.RenderTransform).Children[0].Angle"
                Storyboard.TargetName="ContentImage">
        <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
    </Storyboard>
</code>```

And call the animation by the array position, but why is it not possible to actually call the transform property's angle property automatically by x:Name?

答:
The RenderTransform and RotateTransform are associated properties and need parenthesis around them. This is the correct syntax.

```<code><Storyboard x:Key="Storyboard"
            TargetProperty="(RenderTransform).Children[0].(RotateTransform.Angle)"
            TargetName="ContentImage">
    <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
</Storyboard>
</code>```

as you pointed out in your edit you could also write this as

```<code><Storyboard x:Key="Storyboard"
            TargetProperty="(RenderTransform).Children[0].Angle"
            TargetName="ContentImage">
    <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
</Storyboard>
</code>```

Body:
I have a piece of xaml that applies a scale transform and a rotatetransform.

        <Image.RenderTransform>
            <TransformGroup>
                <RotateTransform Angle="0" x:Name="RotateTransform"/>
                <TranslateTransform X="0" Y="0"/>
                <ScaleTransform ScaleX="2" ScaleY="2"/>
            </TransformGroup>
        </Image.RenderTransform>

I also have a storyboard that needs to accesss RotateTransform like so:

        <Storyboard x:Key="Storyboard"
                Storyboard.TargetProperty="(RenderTransform).(RotateTransform.Angle)"
                Storyboard.TargetName="RotateTransform">
        <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
    </Storyboard>

However I can not get the image to rotate, but it does scale up. Does anyone have suggestions to fix the problem?

Edit: I did figure out that i can use

    <Storyboard x:Key="Storyboard"
                Storyboard.TargetProperty="(Image.RenderTransform).Children[0].Angle"
                Storyboard.TargetName="ContentImage">
        <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
    </Storyboard>

And call the animation by the array position, but why is it not possible to actually call the transform property's angle property automatically by x:Name?

Body:
The RenderTransform and RotateTransform are associated properties and need parenthesis around them. This is the correct syntax.

<Storyboard x:Key="Storyboard"
            TargetProperty="(RenderTransform).Children[0].(RotateTransform.Angle)"
            TargetName="ContentImage">
    <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
</Storyboard>

as you pointed out in your edit you could also write this as

<Storyboard x:Key="Storyboard"
            TargetProperty="(RenderTransform).Children[0].Angle"
            TargetName="ContentImage">
    <DoubleAnimation From="0" To="360" RepeatBehavior="Forever" SpeedRatio="0.25" />
</Storyboard>


问:
WiX with database MYSQL
I am going to make wix with database MYSQL, i have searched in google.
Connect to mysql example from wix. After i used code from that, i had error. The DataSource:ODBCExecute element contains an unexpected attribute 'File'.

and my question are: is that right ? Do you have another option to make wix generate script to mysql.
Thank you everyone.

答: You can use the ODBCExecuteFile, look here.

ContentLicense: CC BY-SA 2.5

Title: WiX with database MYSQL


问:
What is best way to add product features in django with database mysql
I want to store product features in MySQL database so, I've some confusion about which way is better to store it for better performance as well as for scalability.

Basically as per my idea, I design models like given below: in that, I have a product table, features table which contains field product type for which type of product belongs to this particular feature. the last table is product_features in that I actually storing data of specific product_id and feature_id is it the right way?

I'm using Django. so here's is my model!

```<code>class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_slug = models.SlugField(unique=True, blank=True, null=True)
    product_title = models.CharField(max_length=255, null = True)
    product_info = models.TextField(null = False)
    product_description = models.CharField(max_length = 255)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    product_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Feature(models.Model):
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
</code>```

答:
As per my thought your model is looks good for the product feature except primary key field in all model, no need to manage primary key in django model because django already manage id field as primary key for each model.

Second thing is generally many time there will be discounts on particular product in online shopping site so, if your plan is also something like that then you can also add one discount model in your app.

Body:
I want to store product features in MySQL database so, I've some confusion about which way is better to store it for better performance as well as for scalability.

Basically as per my idea, I design models like given below: in that, I have a product table, features table which contains field product type for which type of product belongs to this particular feature. the last table is product_features in that I actually storing data of specific product_id and feature_id is it the right way?

I'm using Django. so here's is my model!

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_slug = models.SlugField(unique=True, blank=True, null=True)
    product_title = models.CharField(max_length=255, null = True)
    product_info = models.TextField(null = False)
    product_description = models.CharField(max_length = 255)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    product_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Feature(models.Model):
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)


问:
Hyperledger fabric 1.4 ./byfn.sh up is giving error when peer0_Org2 connecting to channel
I am trying to build 3 Organisations of which , Org1 and Org2 has 1 node and Org3 has 4 nodes. i am using the same architecture as byfn.sh file. I have added extras for making the third organisation. When i run ./byfn.sh up it gives the following error.

```<code>Error: error getting endorser client for channel: endorser client failed to connect to peer0.org2.example.com:9051: failed to create new connection: connection error: desc = "transport: error while dialing: dial tcp 172.28.0.2:9051: connect: connection refused"
peer0.org2 failed to join the channel, Retry after 10 seconds
</code>```

I am new to hyperledger fabric. Please help me.
Thanks in advance.

My Configtx.yaml file:

```<code>Organizations:
    - &OrdererOrg
        Name: OrdererOrg
        ID: OrdererMSP
        MSPDir: crypto-config/ordererOrganizations/example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Writers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Admins:
                Type: Signature
                Rule: "OR('OrdererMSP.admin')"

    - &Org1
        Name: Org1MSP
        ID: Org1MSP

        MSPDir: crypto-config/peerOrganizations/org1.example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org1MSP.admin', 'Org1MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org1MSP.admin')"

        AnchorPeers:
            - Host: peer0.org1.example.com
              Port: 7051

    - &Org2
        Name: Org2MSP

        ID: Org2MSP

        MSPDir: crypto-config/peerOrganizations/org2.example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org2MSP.admin', 'Org2MSP.peer', 'Org2MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org2MSP.admin', 'Org2MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org2MSP.admin')"

        AnchorPeers:
            - Host: peer0.org2.example.com
              Port: 7051
    - &Org3

        Name: Org3MSP
        ID: Org3MSP
        MSPDir: crypto-config/peerOrganizations/org3.example.com/msp
        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org3MSP.admin', 'Org3MSP.peer', 'Org3MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org3MSP.admin', 'Org3MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org3MSP.admin')"
        AnchorPeers:
            - Host: peer0.org3.example.com
              Port: 7051
Capabilities:
    Channel: &ChannelCapabilities
         V1_4_2: true
    Orderer: &OrdererCapabilities
      V1_4_2: true
    Application: &ApplicationCapabilities
        V1_4_2: true
        V1_3: false
        V1_2: false
        V1_1: false
Application: &ApplicationDefaults
    Organizations:
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"

    Capabilities:
        <<: *ApplicationCapabilities

Orderer: &OrdererDefaults
    OrdererType: solo
    Addresses:
        - orderer.example.com:7050

    BatchTimeout: 2s
    BatchSize:
        MaxMessageCount: 10
        AbsoluteMaxBytes: 99 MB
        PreferredMaxBytes: 512 KB

    Kafka:
      Brokers:
            - 127.0.0.1:9092
    Organizations:
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"
        # BlockValidation specifies what signatures must be included in the block
        # from the orderer for the peer to validate it.
        BlockValidation:
            Type: ImplicitMeta
            Rule: "ANY Writers"

Channel: &ChannelDefaults
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"

    Capabilities:
        <<: *ChannelCapabilities

Profiles:
    ThreeOrgsOrdererGenesis:
        <<: *ChannelDefaults
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
            Capabilities:
                <<: *OrdererCapabilities
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org1
                    - *Org2
                    - *Org3
    ThreeOrgsChannel:
        Consortium: SampleConsortium
        <<: *ChannelDefaults
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org1
                - *Org2
                - *Org3
            Capabilities:
                <<: *ApplicationCapabilities

</code>```

Docker-compose-cli.yaml file:

```<code>  cli:
    container_name: cli
    image: hyperledger/fabric-tools:$IMAGE_TAG
    tty: true
    stdin_open: true
    environment:
      - SYS_CHANNEL=$SYS_CHANNEL
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      #- FABRIC_LOGGING_SPEC=DEBUG
      - FABRIC_LOGGING_SPEC=INFO
      - CORE_PEER_ID=cli
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
      - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: /bin/bash
    volumes:
        - /var/run/:/host/var/run/
        - ./../chaincode/:/opt/gopath/src/github.com/chaincode
        - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
        - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
        - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts
    depends_on:
      - orderer.example.com
      - peer0.org1.example.com
      - peer0.org2.example.com
      - peer0.org3.example.com
      - peer1.org3.example.com
      - peer2.org3.example.com
      - peer3.org3.example.com
    networks:
      - byfn
</code>```

docker-compose-base.yaml file:

```<code>version: '2'

services:

  orderer.example.com:
    container_name: orderer.example.com
    image: hyperledger/fabric-orderer:$IMAGE_TAG
    environment:
      - ORDERER_GENERAL_LOGLEVEL=INFO
      - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0 # 0.0.0.0 it means it can listen to any ip-address in the network. If you want ordere to listen to specific ip address, you can override the same here.
      - ORDERER_GENERAL_GENESISMETHOD=file  # file= indicates the genesis file we are using is a file system
      - ORDERER_GENERAL_GENESISFILE=/var/hyperledger/orderer/orderer.genesis.block
      - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
      - ORDERER_GENERAL_LOCALMSPDIR=/var/hyperledger/orderer/msp
      # enabled TLS
      - ORDERER_GENERAL_TLS_ENABLED=true
      - ORDERER_GENERAL_TLS_PRIVATEKEY=/var/hyperledger/orderer/tls/server.key
      - ORDERER_GENERAL_TLS_CERTIFICATE=/var/hyperledger/orderer/tls/server.crt
      - ORDERER_GENERAL_TLS_ROOTCAS=[/var/hyperledger/orderer/tls/ca.crt]
      - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
      - ORDERER_KAFKA_VERBOSE=true
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
    command: orderer
    volumes:
        - ../channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
        - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp
        - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls
        - orderer.example.com:/var/hyperledger/production/orderer
    ports:
      - 7050:7050 # see the web page

  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051  #https://lists.hyperledger.org/g/fabric/topic/defining_peer_for_multiple/19199485?p=,,,20,0,0,0::recentpostdate%2Fsticky,,,20,2,0,19199485
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051    #if you only have 1 peer per org, you don't need a bootstrap config.
      - CORE_PEER_LISTENADDRESS=0.0.0.0:7051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org1.example.com:7052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org1.example.com:/var/hyperledger/production
    ports:
      - 7051:7051

  peer0.org2.example.com:
    container_name: peer0.org1.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org2.example.com
      - CORE_PEER_ADDRESS=peer0.org2.example.com:8051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:8051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org2.example.com:8052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:8052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:8051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:8051
      - CORE_PEER_LOCALMSPID=Org2MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org2.example.com:/var/hyperledger/production

    ports:
      - 8051:8051

  peer0.org3.example.com:
    container_name: peer0.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org3.example.com
      - CORE_PEER_ADDRESS=peer0.org3.example.com:9051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:9051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org3.example.com:9052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:9052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:9051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org3.example.com:10051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org3.example.com:/var/hyperledger/production
    ports:
      - 9051:9051

  peer1.org3.example.com:
    container_name: peer1.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer1.org3.example.com
      - CORE_PEER_ADDRESS=peer1.org3.example.com:10051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:10051
      - CORE_PEER_CHAINCODEADDRESS=peer1.org3.example.com:10052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:10052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org3.example.com:10051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer2.org3.example.com:11051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer1.org3.example.com:/var/hyperledger/production
    ports:
      - 10051:10051

  peer2.org3.example.com:
    container_name: peer2.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer2.org3.example.com
      - CORE_PEER_ADDRESS=peer2.org3.example.com:11051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:11051
      - CORE_PEER_CHAINCODEADDRESS=peer2.org3.example.com:11052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:11052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer2.org3.example.com:11051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer3.org3.example.com:12051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer2.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer2.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer2.org3.example.com:/var/hyperledger/production
    ports:
      - 11051:11051

  peer3.org3.example.com:
    container_name: peer3.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer3.org3.example.com
      - CORE_PEER_ADDRESS=peer3.org3.example.com:12051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:12051
      - CORE_PEER_CHAINCODEADDRESS=peer3.org3.example.com:12052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:12052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer3.org3.example.com:12051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:9051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer3.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer3.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer3.org3.example.com:/var/hyperledger/production
    ports:
      - 12051:12051
</code>```

When i write ./byfn.sh up, i get this error.

```<code>CONTAINER ID        IMAGE                               COMMAND             CREATED             STATUS                     PORTS                      NAMES
bc89f3e6ad9c        hyperledger/fabric-tools:latest     "/bin/bash"         3 seconds ago       Up Less than a second                                 cli
385652e2b469        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 8 seconds               0.0.0.0:8051->8051/tcp     peer0.org2.example.com
6712c3fc4dcf        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Exited (1) 5 seconds ago                              peer1.org3.example.com
ecb198db73aa        hyperledger/fabric-orderer:latest   "orderer"           13 seconds ago      Up 7 seconds               0.0.0.0:7050->7050/tcp     orderer.example.com
be9e0d491f63        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 3 seconds               0.0.0.0:7051->7051/tcp     peer0.org1.example.com
2639c5d85bd2        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 4 seconds               0.0.0.0:12051->12051/tcp   peer3.org3.example.com
5c87eb50608a        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 7 seconds               0.0.0.0:11051->11051/tcp   peer2.org3.example.com
1bae906c793c        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 5 seconds               0.0.0.0:9051->9051/tcp     peer0.org3.example.com

Build your first network (BYFN) end-to-end test

===================== peer0.org1 joined channel 'mychannel' =====================

+ peer channel join -b mychannel.block
+ res=1
+ set +x
Error: error getting endorser client for channel: endorser client failed to connect to peer0.org2.example.com:9051: failed to create new connection: connection error: desc = "transport: error while dialing: dial tcp 172.28.0.2:9051: connect: connection refused"
peer0.org2 failed to join the channel, Retry after 10 seconds

</code>```

Please help . Thank you again.

答: In the docker-compose file, you have assigned port 8051 to peer0.org2 whereas, you are trying to connect to the port 9051.

Body:
I am trying to build 3 Organisations of which , Org1 and Org2 has 1 node and Org3 has 4 nodes. i am using the same architecture as byfn.sh file. I have added extras for making the third organisation. When i run ./byfn.sh up it gives the following error.

Error: error getting endorser client for channel: endorser client failed to connect to peer0.org2.example.com:9051: failed to create new connection: connection error: desc = "transport: error while dialing: dial tcp 172.28.0.2:9051: connect: connection refused"
peer0.org2 failed to join the channel, Retry after 10 seconds

I am new to hyperledger fabric. Please help me.
Thanks in advance.

My Configtx.yaml file:

Organizations:
    - &OrdererOrg
        Name: OrdererOrg
        ID: OrdererMSP
        MSPDir: crypto-config/ordererOrganizations/example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Writers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Admins:
                Type: Signature
                Rule: "OR('OrdererMSP.admin')"

    - &Org1
        Name: Org1MSP
        ID: Org1MSP

        MSPDir: crypto-config/peerOrganizations/org1.example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org1MSP.admin', 'Org1MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org1MSP.admin')"

        AnchorPeers:
            - Host: peer0.org1.example.com
              Port: 7051

    - &Org2
        Name: Org2MSP

        ID: Org2MSP

        MSPDir: crypto-config/peerOrganizations/org2.example.com/msp

        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org2MSP.admin', 'Org2MSP.peer', 'Org2MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org2MSP.admin', 'Org2MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org2MSP.admin')"

        AnchorPeers:
            - Host: peer0.org2.example.com
              Port: 7051
    - &Org3

        Name: Org3MSP
        ID: Org3MSP
        MSPDir: crypto-config/peerOrganizations/org3.example.com/msp
        Policies:
            Readers:
                Type: Signature
                Rule: "OR('Org3MSP.admin', 'Org3MSP.peer', 'Org3MSP.client')"
            Writers:
                Type: Signature
                Rule: "OR('Org3MSP.admin', 'Org3MSP.client')"
            Admins:
                Type: Signature
                Rule: "OR('Org3MSP.admin')"
        AnchorPeers:
            - Host: peer0.org3.example.com
              Port: 7051
Capabilities:
    Channel: &ChannelCapabilities
         V1_4_2: true
    Orderer: &OrdererCapabilities
      V1_4_2: true
    Application: &ApplicationCapabilities
        V1_4_2: true
        V1_3: false
        V1_2: false
        V1_1: false
Application: &ApplicationDefaults
    Organizations:
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"

    Capabilities:
        <<: *ApplicationCapabilities

Orderer: &OrdererDefaults
    OrdererType: solo
    Addresses:
        - orderer.example.com:7050

    BatchTimeout: 2s
    BatchSize:
        MaxMessageCount: 10
        AbsoluteMaxBytes: 99 MB
        PreferredMaxBytes: 512 KB

    Kafka:
      Brokers:
            - 127.0.0.1:9092
    Organizations:
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"
        # BlockValidation specifies what signatures must be included in the block
        # from the orderer for the peer to validate it.
        BlockValidation:
            Type: ImplicitMeta
            Rule: "ANY Writers"

Channel: &ChannelDefaults
    Policies:
        Readers:
            Type: ImplicitMeta
            Rule: "ANY Readers"
        Writers:
            Type: ImplicitMeta
            Rule: "ANY Writers"
        Admins:
            Type: ImplicitMeta
            Rule: "MAJORITY Admins"

    Capabilities:
        <<: *ChannelCapabilities

Profiles:
    ThreeOrgsOrdererGenesis:
        <<: *ChannelDefaults
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
            Capabilities:
                <<: *OrdererCapabilities
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org1
                    - *Org2
                    - *Org3
    ThreeOrgsChannel:
        Consortium: SampleConsortium
        <<: *ChannelDefaults
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org1
                - *Org2
                - *Org3
            Capabilities:
                <<: *ApplicationCapabilities

Docker-compose-cli.yaml file:

  cli:
    container_name: cli
    image: hyperledger/fabric-tools:$IMAGE_TAG
    tty: true
    stdin_open: true
    environment:
      - SYS_CHANNEL=$SYS_CHANNEL
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      #- FABRIC_LOGGING_SPEC=DEBUG
      - FABRIC_LOGGING_SPEC=INFO
      - CORE_PEER_ID=cli
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
      - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: /bin/bash
    volumes:
        - /var/run/:/host/var/run/
        - ./../chaincode/:/opt/gopath/src/github.com/chaincode
        - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
        - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
        - ./channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel-artifacts
    depends_on:
      - orderer.example.com
      - peer0.org1.example.com
      - peer0.org2.example.com
      - peer0.org3.example.com
      - peer1.org3.example.com
      - peer2.org3.example.com
      - peer3.org3.example.com
    networks:
      - byfn

docker-compose-base.yaml file:

version: '2'

services:

  orderer.example.com:
    container_name: orderer.example.com
    image: hyperledger/fabric-orderer:$IMAGE_TAG
    environment:
      - ORDERER_GENERAL_LOGLEVEL=INFO
      - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0 # 0.0.0.0 it means it can listen to any ip-address in the network. If you want ordere to listen to specific ip address, you can override the same here.
      - ORDERER_GENERAL_GENESISMETHOD=file  # file= indicates the genesis file we are using is a file system
      - ORDERER_GENERAL_GENESISFILE=/var/hyperledger/orderer/orderer.genesis.block
      - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
      - ORDERER_GENERAL_LOCALMSPDIR=/var/hyperledger/orderer/msp
      # enabled TLS
      - ORDERER_GENERAL_TLS_ENABLED=true
      - ORDERER_GENERAL_TLS_PRIVATEKEY=/var/hyperledger/orderer/tls/server.key
      - ORDERER_GENERAL_TLS_CERTIFICATE=/var/hyperledger/orderer/tls/server.crt
      - ORDERER_GENERAL_TLS_ROOTCAS=[/var/hyperledger/orderer/tls/ca.crt]
      - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
      - ORDERER_KAFKA_VERBOSE=true
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
    command: orderer
    volumes:
        - ../channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
        - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp
        - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls
        - orderer.example.com:/var/hyperledger/production/orderer
    ports:
      - 7050:7050 # see the web page

  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051  #https://lists.hyperledger.org/g/fabric/topic/defining_peer_for_multiple/19199485?p=,,,20,0,0,0::recentpostdate%2Fsticky,,,20,2,0,19199485
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org1.example.com:7051    #if you only have 1 peer per org, you don't need a bootstrap config.
      - CORE_PEER_LISTENADDRESS=0.0.0.0:7051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org1.example.com:7052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org1.example.com:/var/hyperledger/production
    ports:
      - 7051:7051

  peer0.org2.example.com:
    container_name: peer0.org1.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org2.example.com
      - CORE_PEER_ADDRESS=peer0.org2.example.com:8051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:8051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org2.example.com:8052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:8052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org2.example.com:8051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org2.example.com:8051
      - CORE_PEER_LOCALMSPID=Org2MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org2.example.com:/var/hyperledger/production

    ports:
      - 8051:8051

  peer0.org3.example.com:
    container_name: peer0.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer0.org3.example.com
      - CORE_PEER_ADDRESS=peer0.org3.example.com:9051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:9051
      - CORE_PEER_CHAINCODEADDRESS=peer0.org3.example.com:9052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:9052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org3.example.com:9051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org3.example.com:10051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer0.org3.example.com:/var/hyperledger/production
    ports:
      - 9051:9051

  peer1.org3.example.com:
    container_name: peer1.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer1.org3.example.com
      - CORE_PEER_ADDRESS=peer1.org3.example.com:10051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:10051
      - CORE_PEER_CHAINCODEADDRESS=peer1.org3.example.com:10052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:10052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer1.org3.example.com:10051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer2.org3.example.com:11051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org2.example.com/peers/peer1.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer1.org3.example.com:/var/hyperledger/production
    ports:
      - 10051:10051

  peer2.org3.example.com:
    container_name: peer2.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer2.org3.example.com
      - CORE_PEER_ADDRESS=peer2.org3.example.com:11051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:11051
      - CORE_PEER_CHAINCODEADDRESS=peer2.org3.example.com:11052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:11052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer2.org3.example.com:11051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer3.org3.example.com:12051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer2.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer2.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer2.org3.example.com:/var/hyperledger/production
    ports:
      - 11051:11051

  peer3.org3.example.com:
    container_name: peer3.org3.example.com
    extends:
      file: peer-base.yaml
      service: peer-base
    environment:
      - CORE_PEER_ID=peer3.org3.example.com
      - CORE_PEER_ADDRESS=peer3.org3.example.com:12051
      - CORE_PEER_LISTENADDRESS=0.0.0.0:12051
      - CORE_PEER_CHAINCODEADDRESS=peer3.org3.example.com:12052
      - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:12052
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer3.org3.example.com:12051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer0.org3.example.com:9051
      - CORE_PEER_LOCALMSPID=Org3MSP
    volumes:
        - /var/run/:/host/var/run/
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer3.org3.example.com/msp:/etc/hyperledger/fabric/msp
        - ../crypto-config/peerOrganizations/org3.example.com/peers/peer3.org3.example.com/tls:/etc/hyperledger/fabric/tls
        - peer3.org3.example.com:/var/hyperledger/production
    ports:
      - 12051:12051

When i write ./byfn.sh up, i get this error.

CONTAINER ID        IMAGE                               COMMAND             CREATED             STATUS                     PORTS                      NAMES
bc89f3e6ad9c        hyperledger/fabric-tools:latest     "/bin/bash"         3 seconds ago       Up Less than a second                                 cli
385652e2b469        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 8 seconds               0.0.0.0:8051->8051/tcp     peer0.org2.example.com
6712c3fc4dcf        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Exited (1) 5 seconds ago                              peer1.org3.example.com
ecb198db73aa        hyperledger/fabric-orderer:latest   "orderer"           13 seconds ago      Up 7 seconds               0.0.0.0:7050->7050/tcp     orderer.example.com
be9e0d491f63        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 3 seconds               0.0.0.0:7051->7051/tcp     peer0.org1.example.com
2639c5d85bd2        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 4 seconds               0.0.0.0:12051->12051/tcp   peer3.org3.example.com
5c87eb50608a        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 7 seconds               0.0.0.0:11051->11051/tcp   peer2.org3.example.com
1bae906c793c        hyperledger/fabric-peer:latest      "peer node start"   13 seconds ago      Up 5 seconds               0.0.0.0:9051->9051/tcp     peer0.org3.example.com

Build your first network (BYFN) end-to-end test

===================== peer0.org1 joined channel 'mychannel' =====================

+ peer channel join -b mychannel.block
+ res=1
+ set +x
Error: error getting endorser client for channel: endorser client failed to connect to peer0.org2.example.com:9051: failed to create new connection: connection error: desc = "transport: error while dialing: dial tcp 172.28.0.2:9051: connect: connection refused"
peer0.org2 failed to join the channel, Retry after 10 seconds

Please help . Thank you again.


问:
resize image in xamarin without wrapping it in stacklayout
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

```<code>
               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

</code>```

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?

答:
According to your description, you just want to get the desire image size, I suggest you can use Grid and Frame to get it.The CornerRadius property of the Frame control can be used to create a circle image.

```<code><Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Frame
            Margin="10"
            BorderColor="Black"
            CornerRadius="50"
            HorizontalOptions="Center"
            IsClippedToBounds="True"
            VerticalOptions="Center">
            <Image
                Margin="-20"
                Aspect="AspectFill"
                HeightRequest="100"
                Source="a11.jpg"
                WidthRequest="100" />
        </Frame>
    </Grid>
</code>```

You can also just use Frame to circle image, to set Frame's HeightRequest and WidthRequest

```<code> <Frame
        Margin="10"
        BorderColor="Black"
        CornerRadius="50"
        HeightRequest="60"
        HorizontalOptions="Center"
        IsClippedToBounds="True"
        VerticalOptions="Center"
        WidthRequest="60">
        <Image
            Margin="-20"
            Aspect="AspectFill"
            HeightRequest="100"
            Source="a11.jpg"
            WidthRequest="100" />
    </Frame>
</code>```

Body:
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?

Body:
According to your description, you just want to get the desire image size, I suggest you can use Grid and Frame to get it.The CornerRadius property of the Frame control can be used to create a circle image.

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Frame
            Margin="10"
            BorderColor="Black"
            CornerRadius="50"
            HorizontalOptions="Center"
            IsClippedToBounds="True"
            VerticalOptions="Center">
            <Image
                Margin="-20"
                Aspect="AspectFill"
                HeightRequest="100"
                Source="a11.jpg"
                WidthRequest="100" />
        </Frame>
    </Grid>

You can also just use Frame to circle image, to set Frame's HeightRequest and WidthRequest

 <Frame
        Margin="10"
        BorderColor="Black"
        CornerRadius="50"
        HeightRequest="60"
        HorizontalOptions="Center"
        IsClippedToBounds="True"
        VerticalOptions="Center"
        WidthRequest="60">
        <Image
            Margin="-20"
            Aspect="AspectFill"
            HeightRequest="100"
            Source="a11.jpg"
            WidthRequest="100" />
    </Frame>


问:
JSON parsing error with axios (unexpected character in server response)
I'm getting a JSON parsing error when I try to fetch data from a server endpoint.

It's the first time that Axios cannot decode the JSON response automatically.

Debugging my code, I've seen that Axios catch some unexpected character in the server response that makes the JSON not valid.

```<code>7F5
{
  "message": "OK"
  ...cut
}
0

</code>```

Error:

```<code>(node:14940) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token F in JSON at position 1
</code>```

I suppose that could be a charset encoding problem.

Axios client configuration:

const pclClient = axios.create({
  baseURL: "http://server/endpoint",
  responseType: "json",
  responseEncoding: "utf8",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    charset: "utf-8"
  }
});
```

Using tools like postman or Chrome Extension Advanced Request Client, the problem is not present.

Can someone help me?

答:
The problem comes from transfer-encoding: chunked response header.

RFC 7230 tells that "A recipient MUST be able to parse and decode the chunked transfer
coding."

At the moment, Axios don't handle chunked responses (transfer-encoding chunked not handled for application/json)

To resolve this issue, I've made a chunk parser using regex to removing chunk's info.

const pclClient = axios.create({
  baseURL: "http://server/",
  responseType: "json",
  headers: {
    Accept: "application/json"
  }
});

const chunksParser = body => {
  return body
    .replace(/^(\w{1,3})\r\n/, "") // replace header chunks info
    .replace(/\r\n(\w{1,3})\r\n/, "") // replace in-body chunks info
    .replace(/(\r\n0\r\n\r\n)$/, ""); // replace end chunks info
};

const getData = async () => {
  response = await pclClient.get("data.json");
  const { data } = response;
  const body = chunksParser(data);
  const json = JSON.parse(body);
  return json;
};

```

I was looking for a built-in function inside Axios. I hope it will be available in the future.

Thank you for commenters that helped me to understand what was the problem.

Body:
I'm getting a JSON parsing error when I try to fetch data from a server endpoint.

It's the first time that Axios cannot decode the JSON response automatically.

Debugging my code, I've seen that Axios catch some unexpected character in the server response that makes the JSON not valid.

7F5
{
  "message": "OK"
  ...cut
}
0

Error:

(node:14940) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token F in JSON at position 1

I suppose that could be a charset encoding problem.

Axios client configuration:

const pclClient = axios.create({
  baseURL: "http://server/endpoint",
  responseType: "json",
  responseEncoding: "utf8",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    charset: "utf-8"
  }
});

Using tools like postman or Chrome Extension Advanced Request Client, the problem is not present.

Can someone help me?

Body:
The problem comes from transfer-encoding: chunked response header.

RFC 7230 tells that "A recipient MUST be able to parse and decode the chunked transfer
coding."

At the moment, Axios don't handle chunked responses (transfer-encoding chunked not handled for application/json)

To resolve this issue, I've made a chunk parser using regex to removing chunk's info.

const pclClient = axios.create({
  baseURL: "http://server/",
  responseType: "json",
  headers: {
    Accept: "application/json"
  }
});

const chunksParser = body => {
  return body
    .replace(/^(\w{1,3})\r\n/, "") // replace header chunks info
    .replace(/\r\n(\w{1,3})\r\n/, "") // replace in-body chunks info
    .replace(/(\r\n0\r\n\r\n)$/, ""); // replace end chunks info
};

const getData = async () => {
  response = await pclClient.get("data.json");
  const { data } = response;
  const body = chunksParser(data);
  const json = JSON.parse(body);
  return json;
};

I was looking for a built-in function inside Axios. I hope it will be available in the future.

Thank you for commenters that helped me to understand what was the problem.


问:
Need to parse a Json object and append it to a table
```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function myFunction() {
            var abc, obj, i, j;
            abc = {
                "cars": [
                    '{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
                    '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
                    '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
                ]
            }
            var obj = JSON.parse(abc);
            var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
            document.getElementById("dtable").appendChild(theader);
            var x;
            for (i = 0; i < abc.cars.length; i++) {
                x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors + "</td><td>" + obj.cars[i].lol[0] + "</td></tr>";
                document.getElementById("dtable").appendChild(x);
            }
        };
    </script>
</head>
<body>
    <div class="container" ,id="dsjson">
        <button type="button" onclick="myFunction()">display json</button>
        <br><br>
        <table id="dtable"></table>
    </div>
</body>
</html>
</code>```

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

答:
you dont need to parse abc since it is already an object, but you need to parse each car object</p>

```<code><html>
<head>
<script type="text/javascript">

function myFunction(){
var abc,obj,i,j;
abc =
    {"cars": [

           ' {"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
            '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
            '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'

]}
var obj = abc;
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").appendChild(theader);
var x;
for (i=0; i <  abc.cars.length; i++) {
    abc.cars[i]=JSON.parse(abc.cars[i]);
  x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors+ "</td><td>" + obj.cars[i].lol[0]+ "</td></tr>"  ;
document.getElementById("dtable").appendChild(x);

}

};

</script>
</head>
<body>
    <div class ="container" ,id = "dsjson">

<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>```
</code>```

Body:
<!DOCTYPE html>

        <button type="button" onclick="myFunction()">display json</button>

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

Body:
you dont need to parse abc since it is already an object, but you need to parse each car object

<html>
<head>
<script type="text/javascript">

function myFunction(){
var abc,obj,i,j;
abc =
    {"cars": [

           ' {"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
            '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
            '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'

]}
var obj = abc;
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").appendChild(theader);
var x;
for (i=0; i <  abc.cars.length; i++) {
    abc.cars[i]=JSON.parse(abc.cars[i]);
  x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors+ "</td><td>" + obj.cars[i].lol[0]+ "</td></tr>"  ;
document.getElementById("dtable").appendChild(x);

}

};

</script>
</head>
<body>
    <div class ="container" ,id = "dsjson">

<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>```


问:
Batch renaming files with Bash
How can Bash rename a series of packages to remove their version numbers? I've been toying around with both expr and %%, to no avail.

Examples:

Xft2-2.1.13.pkg becomes Xft2.pkg

jasper-1.900.1.pkg becomes jasper.pkg

xorg-libXrandr-1.2.3.pkg becomes xorg-libXrandr.pkg

答:
better use sed for this, something like:

```<code>find . -type f -name "*.pkg" |
 sed -e 's/((.*)-[0-9.]*\.pkg)/\1 \2.pkg/g' |
 while read nameA nameB; do
    mv $nameA $nameB;
 done
</code>```

figuring up the regular expression is left as an exercise (as is dealing with filenames that include spaces)

OwnerDisplayName: Nerdling

Title: Batch renaming files with Bash

Body:
better use sed for this, something like:

find . -type f -name "*.pkg" |
 sed -e 's/((.*)-[0-9.]*\.pkg)/\1 \2.pkg/g' |
 while read nameA nameB; do
    mv $nameA $nameB;
 done

figuring up the regular expression is left as an exercise (as is dealing with filenames that include spaces)

OwnerDisplayName: Javier


问:
axios get function not working in Reactjs
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

```<code>app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

</code>```

and I call the API in my reactjs page component

```<code>class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList
</code>```

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

答:
enduser_tbl.data will be undefined,
it will be either enduser_tbl.response or enduser_tbl which you are setting in your state.</p>

```<code>    this.setState({
        enduser_tbl : enduser_tbl.response
    })
</code>```

Body:
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

and I call the API in my reactjs page component

class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

Body:
enduser_tbl.data will be undefined,
it will be either enduser_tbl.response or enduser_tbl which you are setting in your state.

    this.setState({
        enduser_tbl : enduser_tbl.response
    })


问:
The need for pure in Applicatives
I'm learning Haskell's Applicatives. It seems to me (I'm probably wrong) that the pure function is not really needed, for example:

```<code>pure (+) <*> [1,2,3] <*> [3,4,5]
</code>```

can be written as

```<code>(+) <$> [1,2,3] <*> [3,4,5]
</code>```

Can someone explain the benefit that the pure function provides over explicit mapping with fmap?

答:
fmap doesn't always cut it. Specifically, pure is what lets you introduce f (where f is Applicative) when you don't already have it. A good example is

```<code>sequence :: Applicative f => [f a] -> f [a]
</code>```

It takes a list of "actions" producing values and turns it into an action producing  a list of values. What happens when there are no actions in the list? The only sane result is an action that produces no values:

```<code>sequence [] = pure [] -- no way to express this with an fmap
-- for completeness
sequence ((:) x xs) = (:) <$> x <*> sequence xs
</code>```

If you didn't have pure, you'd be forced to require a nonempty list of actions. You could definitely make it work, but it's like talking about addition without mentioning 0 or multiplication without 1 (as others have said, because Applicatives are monoidal). You will repeatedly run into edge cases that would be easily solved with pure but instead have to be solved by weird restrictions on your inputs and other band-aids.

Title: The need for pure in Applicatives

Body:
I'm learning Haskell's Applicatives. It seems to me (I'm probably wrong) that the pure function is not really needed, for example:

pure (+) <*> [1,2,3] <*> [3,4,5]

can be written as

(+) <$> [1,2,3] <*> [3,4,5]

Can someone explain the benefit that the pure function provides over explicit mapping with fmap?

Body:
fmap doesn't always cut it. Specifically, pure is what lets you introduce f (where f is Applicative) when you don't already have it. A good example is

sequence :: Applicative f => [f a] -> f [a]

It takes a list of "actions" producing values and turns it into an action producing  a list of values. What happens when there are no actions in the list? The only sane result is an action that produces no values:

sequence [] = pure [] -- no way to express this with an fmap
-- for completeness
sequence ((:) x xs) = (:) <$> x <*> sequence xs

If you didn't have pure, you'd be forced to require a nonempty list of actions. You could definitely make it work, but it's like talking about addition without mentioning 0 or multiplication without 1 (as others have said, because Applicatives are monoidal). You will repeatedly run into edge cases that would be easily solved with pure but instead have to be solved by weird restrictions on your inputs and other band-aids.


问:
What is impact of document archival because of time to live on the physical partition in Azure CosmosDB
Does physical partition get reclaimed once it becomes empty when all documents in that partition are archived because of Time to Live has been elapsed.</p>

答:
Based on Cosmos DB TTL document: When you configure TTL, the system will automatically delete the expired items based on the TTL value, without needing a delete operation that is explicitly issued by the client application,which means the items are deleted with TTL.

And you only can manage logical partitions. Azure Cosmos DB automatically manages the placement of logical partitions on physical partitions. The explanation here:

Azure Cosmos DB hashes the partition key value of an item. The hashed result determines the physical partition. Then, Azure Cosmos DB allocates the key space of partition key hashes evenly across the physical partitions,which means when you remove all documents in one partition,cosmos db will allocate the physical partitions automatically.You could just  need to care about your construction on logical partition.


问:
How can I use Spring Cloud Task with modular Spring Batch jobs?
I've developed couple of Spring Batch jobs in Spring Boot web application. For easier maintenance, I used @EnableBatchProcessing(modular = true) like this:

```<code>@Configuration
@EnableBatchProcessing(modular = true)
public class BatchConfiguration {

    @Bean
    @ConditionalOnProperty(value="first.batch.enabled", havingValue = "true")
    public ApplicationContextFactory firstJobs() {
        return new GenericApplicationContextFactory(FirstModule.class);
    }

    @Bean
    @ConditionalOnProperty(value="second.batch.enabled", havingValue = "true")
    public ApplicationContextFactory secondJobs() {
        return new GenericApplicationContextFactory(SecondModule.class);
    }
    ...
}
</code>```

and I have @Configuration classes, one for every Job defined respectively in base directories of modules. Everything works fine, but now I want to setup Spring Cloud Dataflow UI to have some basic monitoring of my Jobs.

The problem is, when I try to add @EnableTask annotation to this class BatchConfiguration, Spring is not associating job execution with task execution. It is only working, when I run tests (@SpringBatchTest).

I also tried to add @EnableTask annotation to FirstJobConfiguration class instead, and also add it to both BatchConfiguration and First|JobConfiguration, but with no effect. I also went through official documentation, but found nothing.

Is it possible to use Spring Cloud Task with modular Spring Batch ?

Thanks.

答:
The Spring Batch application can be converted into a Spring Cloud Task application and be managed using Spring Cloud Data Flow.

You should be able to use EnableTask in your SpringBoot application along with EnableBatchProcessing in your configuration.

Please see the SCDF sample which demonstrates this scenario.

Body:
I've developed couple of Spring Batch jobs in Spring Boot web application. For easier maintenance, I used @EnableBatchProcessing(modular = true) like this:

@Configuration
@EnableBatchProcessing(modular = true)
public class BatchConfiguration {

    @Bean
    @ConditionalOnProperty(value="first.batch.enabled", havingValue = "true")
    public ApplicationContextFactory firstJobs() {
        return new GenericApplicationContextFactory(FirstModule.class);
    }

    @Bean
    @ConditionalOnProperty(value="second.batch.enabled", havingValue = "true")
    public ApplicationContextFactory secondJobs() {
        return new GenericApplicationContextFactory(SecondModule.class);
    }
    ...
}

and I have @Configuration classes, one for every Job defined respectively in base directories of modules. Everything works fine, but now I want to setup Spring Cloud Dataflow UI to have some basic monitoring of my Jobs.

The problem is, when I try to add @EnableTask annotation to this class BatchConfiguration, Spring is not associating job execution with task execution. It is only working, when I run tests (@SpringBatchTest).

I also tried to add @EnableTask annotation to FirstJobConfiguration class instead, and also add it to both BatchConfiguration and First|JobConfiguration, but with no effect. I also went through official documentation, but found nothing.

Is it possible to use Spring Cloud Task with modular Spring Batch ?

Thanks.


答:
As per java docs:

The put returns the previous value associated with key, or null if
  there was no mapping for key. (A null return can also indicate that
  the map previously associated null with the key if the implementation
  supports null values.)

In your case when you did map.put(1, "ABC") nothing was associated with key 1 so it returns null but when you use put(1, "XYZ") then there was already an entry exists against the key 1 so it returns "ABC"

Title: What does map.put return?

Body:
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value.
So, can anyone tell me what is the return type of the put method in the map interface?

Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC


问:
Nested documents in ElasticSearch without mapping types
With the planned removal of mapping types coming to ElasticSearch, does this also mean the deprecation of nested documents and nested queries? How would/will ElasticSearch support queries of nested objects in typeless context?

The functionality I'm considering is being able to return only the hits in a nested array that match search criteria.

Edit 1: Example mapping + query in ElasticSearch version 6

ElasticSearch 6 Mapping

```<code>{
    "rec": {
        "mappings": {
            "history": {
                "properties": {
                    "dateCompleted": {
                        "type": "keyword"
                    },
                    "dateCreated": {
                        "type": "keyword"
                    },
                    "dateOrdered": {
                        "type": "keyword"
                    },
                    "dateToArrive": {
                        "type": "keyword"
                    },
                    "details": {
                        "type": "nested",
                        "properties": {

                            "clientId": {
                                "type": "keyword"
                            },
                            "company": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "orderNumber": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

ElasticSearch 6 Query

```<code>{
  "from": 0,
  "query": {
    "nested": {
      "inner_hits": {},
      "path": "details",
      "query": {
        "bool": {
          "must": [
            {
              "match_phrase": {
                "details.company.keyword": {
                  "query": "ABCD"
                }
              }
            }
          ]
        }
      }
    }
  },
  "size": 10,
  "sort": [],
  "_source": false
}
</code>```

答:
No, the removal of _type has no impact on nested documents and queries.

In the past, people used different types in one index for modeling serveral entities. The problem was, that some of the entities had the same field but different field type. For example "version", in one entity an string but integer in other. This caused a problem, because there is no solution for this scenario.

EDIT:
Nested objects is an mapping dataype for modeling complex properties within a document like this:

```<code>{
  "_id" : "12345",
  "user" : { "login":"foo", "email":"foo@example.com"}
}
</code>```

Please note the user object within the document itself or the "details" property in your mapping above. More examples are available here: https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

The document doctype is a set of properies defining a documents structure by its mapping.

In the past, there was the possibility of modelling a "car" and a "plane" in one index using two doctypes. In current versions there is just one doctype, mainly named _doc and it will be completely removed in future versions.

In the documentation you've linked (removal of types) there is a good example of multi doctype twitter index defining a user and tweet doctype in one index.

Body:
With the planned removal of mapping types coming to ElasticSearch, does this also mean the deprecation of nested documents and nested queries? How would/will ElasticSearch support queries of nested objects in typeless context?

The functionality I'm considering is being able to return only the hits in a nested array that match search criteria.

Edit 1: Example mapping + query in ElasticSearch version 6

ElasticSearch 6 Mapping

{
    "rec": {
        "mappings": {
            "history": {
                "properties": {
                    "dateCompleted": {
                        "type": "keyword"
                    },
                    "dateCreated": {
                        "type": "keyword"
                    },
                    "dateOrdered": {
                        "type": "keyword"
                    },
                    "dateToArrive": {
                        "type": "keyword"
                    },
                    "details": {
                        "type": "nested",
                        "properties": {

                            "clientId": {
                                "type": "keyword"
                            },
                            "company": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "orderNumber": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

ElasticSearch 6 Query

{
  "from": 0,
  "query": {
    "nested": {
      "inner_hits": {},
      "path": "details",
      "query": {
        "bool": {
          "must": [
            {
              "match_phrase": {
                "details.company.keyword": {
                  "query": "ABCD"
                }
              }
            }
          ]
        }
      }
    }
  },
  "size": 10,
  "sort": [],
  "_source": false
}

Body:
No, the removal of _type has no impact on nested documents and queries.

In the past, people used different types in one index for modeling serveral entities. The problem was, that some of the entities had the same field but different field type. For example "version", in one entity an string but integer in other. This caused a problem, because there is no solution for this scenario.

EDIT:
Nested objects is an mapping dataype for modeling complex properties within a document like this:

{
  "_id" : "12345",
  "user" : { "login":"foo", "email":"foo@example.com"}
}

Please note the user object within the document itself or the "details" property in your mapping above. More examples are available here: https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

The document doctype is a set of properies defining a documents structure by its mapping.

In the past, there was the possibility of modelling a "car" and a "plane" in one index using two doctypes. In current versions there is just one doctype, mainly named _doc and it will be completely removed in future versions.

In the documentation you've linked (removal of types) there is a good example of multi doctype twitter index defining a user and tweet doctype in one index.


问:
How to execute a file written in C from python while passing it string values and accepting/storing the string it returns as output.(Linux)
I have tried the subprocess module but providing the main function of C with string values but it doesn't seem to work for me. There are certain solutions available on the web but I'm having difficulty in understanding and implementing them. Any help will be appreciated.

I want to execute a file written in C passing it arguments from my pyhthon code and after that C file is executed I want to capture what it returns in my python code.

```<code>const char* main(int argc , char* argv[])
{
    printf("Hello World from C \n");
    printf("1st string passed is %s \n ",argv[1]);
    printf("2nd string passed is %s \n ", argv[2]);
    char b[] = "success";
    return b;
}

</code>```

This is the code in C from where I wish to return a string to the python code.

```<code>import subprocess
import os

def excuteC():

    s = subprocess.call("./Cvishad hello you;", shell = True)
    print("status is "+ str(s))

if __name__=="__main__":
    excuteC()

</code>```

This is the code in python where I am calling the C code. It seems to work but I think it is returning a pointer/address but not the actual string "success" that I want.
The output I get is something like this -

```<code>Hello World from C
1st string passed is hello
2nd string passed is you
status is 80
</code>```

I'm trying out things for the first time in C, so kindly excuse the silly mistakes.

答:
Your C program is returning a pointer to a string as the process return value, and it gets truncated to an unsigned byte (which you're seeing as e.g. 80).

You can transfer arbitrary data between processes by e.g. (and I'm sure I'm forgetting something)

sockets

files

streams (stdout/stderr; subprocess.check_output() in Python)

shared memory

Body:
I have tried the subprocess module but providing the main function of C with string values but it doesn't seem to work for me. There are certain solutions available on the web but I'm having difficulty in understanding and implementing them. Any help will be appreciated.

I want to execute a file written in C passing it arguments from my pyhthon code and after that C file is executed I want to capture what it returns in my python code.

const char* main(int argc , char* argv[])
{
    printf("Hello World from C \n");
    printf("1st string passed is %s \n ",argv[1]);
    printf("2nd string passed is %s \n ", argv[2]);
    char b[] = "success";
    return b;
}

This is the code in C from where I wish to return a string to the python code.

import subprocess
import os

def excuteC():

    s = subprocess.call("./Cvishad hello you;", shell = True)
    print("status is "+ str(s))

if __name__=="__main__":
    excuteC()

This is the code in python where I am calling the C code. It seems to work but I think it is returning a pointer/address but not the actual string "success" that I want.
The output I get is something like this -

Hello World from C
1st string passed is hello
2nd string passed is you
status is 80

I'm trying out things for the first time in C, so kindly excuse the silly mistakes.